Peios Learn
Documentation

Peios

Peios Peios Kernel Universal Directory Project

Developer Tools

Trail Acta Provium clackatoo CAF GCSL Pekit

Applications

Framewright

Standards and Conventions

Standards and Conventions Peios Specifications
Peios Kernel

Core APIs

Single-page view · as markdown

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!

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
  • Workqueue
  • General notification mechanism
  • Message logging with printk
  • How to get printk format specifiers right
  • Printk Index
  • Symbol Namespaces
  • Assembler Annotations
  • Real-time preemption
  • Housekeeping

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
  • Adding reference counters (krefs) to kernel objects
  • Scope-based Cleanup Helpers
  • Generic Associative Array Implementation
  • Folio Queue
  • XArray
  • Maple Tree
  • ID Allocation
  • Circular Buffers
  • Red-black Trees (rbtree) in Linux
  • Generic radix trees/sparse arrays
  • Generic bitfield packing and unpacking functions
  • this_cpu operations
  • ktime accessors
  • The errseq_t datatype
  • atomic_t
  • atomic_bitops
  • Floating-point API
  • Union-Find in Linux
  • Min Heap API
  • Generic parser
  • Linked Lists in Linux

Low level entry and exit #

  • Entry/exit handling for exceptions, interrupts, syscalls and KVM

Concurrency primitives #

How Linux keeps everything from happening at the same time. See Documentation/locking/index.rst for more related documentation.

  • refcount_t API compared to atomic_t
  • IRQs
  • Semantics and Behavior of Local Atomic Operations
  • The padata parallel execution mechanism
  • RCU Handbook
  • memory-barriers

Low-level hardware management #

Cache management, managing CPU hotplug, etc.

  • Cache and TLB Flushing Under Linux
  • CPU hotplug in the Kernel
  • Memory hotplug
  • Linux generic IRQ handling
  • Memory Protection Keys

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.

  • Memory Allocation Guide
  • Unaligned Memory Accesses
  • Dynamic DMA mapping using the generic device
  • Dynamic DMA mapping Guide
  • DMA attributes
  • DMA with ISA and LPC devices
  • DMA and swiotlb
  • Memory Management APIs
  • Cgroup Kernel APIs
  • The genalloc/genpool subsystem
  • pin_user_pages() and related calls
  • Boot time memory management
  • GFP masks used from FS/IO context
  • Kexec Handover Subsystem

Interfaces for kernel debugging #

  • The object-lifetime debugging infrastructure
  • The Linux Kernel Tracepoint API
  • Using physical DMA provided by OHCI-1394 FireWire controllers for debugging

Everything else #

Documents that don't fit elsewhere or which have yet to be categorized.

  • Reed-Solomon Library Programming Interface
  • Live Update Orchestrator
  • Netlink notes for kernel developers

Assembler Annotations

Peios Kernel / Internals / Core APIs

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.

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:

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) 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).

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 and instead of extending the current ENTRY/END* macros, it was decided that brand new macros should be introduced instead:

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?

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.

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:

    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:

    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:

    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:

    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)
    

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:

    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:

    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.

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.

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

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.

The Public API #

The public API can be found in <linux/assoc_array.h>. The associative array is rooted on the following structure:

struct assoc_array {
        ...
};

The code is selected by enabling CONFIG_ASSOCIATIVE_ARRAY with:

./script/config -e ASSOCIATIVE_ARRAY

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:

struct assoc_array_edit;

There are two functions for dealing with the script:

  1. Apply an edit script:

    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:

    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.

Operations Table #

Various functions take a table of operations:

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:

    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:

    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:

    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:

    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:

    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.

Manipulation Functions #

There are a number of functions for manipulating an associative array:

  1. Initialise an associative array:

    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:

    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:

    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.

  1. Delete all objects from an associative array:

    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.

  2. Destroy an associative array, deleting all objects:

    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.

  3. Garbage collect an associative array:

    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.

Access Functions #

There are two functions for accessing an associative array:

  1. Iterate over all the objects in an associative array:

    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:

    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.

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.

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.

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:

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:

KEY PREFIX

NODE

137*

D

138*

E

13[0-69-f]*

C

1[0-24-f]*

B

e6*

G

e[0-57-f]*

F

[02-df]*

A

So, for instance, keys with the following example index keys will be found in the appropriate nodes:

INDEX KEY

PREFIX

NODE

13694892892489

13

C

13795289025897

137

D

13889dde88793

138

E

138bbb89003093

138

E

1394879524789

12

C

1458952489

1

B

9431809de993ba

A

b4542910809cd

A

e5284310def98

e

F

e68428974237

e6

G

e7fffcbd443

e

F

f3842239082

A

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:

SLOT

CONTENT

INDEX KEY (PREFIX)

1

PTR TO NODE B

1*

any

LEAF

9431809de993ba

any

LEAF

b4542910809cd

e

PTR TO NODE F

e*

any

LEAF

f3842239082

and node B:

SLOT

CONTENT

INDEX KEY (PREFIX)

3

PTR TO NODE C

13*

any

LEAF

1458952489

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.

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.

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.

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 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.

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() or 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(). The 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() and 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.

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.

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() 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.

struct memblock_region #

represents a memory region

Definition

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

struct memblock_type #

collection of memory regions of certain type

Definition

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

struct memblock #

memblock allocator metadata

Definition

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

for_each_physmem_range() #

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

__for_each_mem_range() #

__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

__for_each_mem_range_rev() #

__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

for_each_mem_range() #

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

for_each_mem_range_rev() #

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

for_each_reserved_mem_range() #

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.

for_each_mem_pfn_range() #

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.

for_each_free_mem_range() #

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.

for_each_free_mem_range_reverse() #

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.

memblock_set_current_limit() #

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)

memblock_region_memory_base_pfn() #

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

memblock_region_memory_end_pfn() #

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

memblock_region_reserved_base_pfn() #

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

memblock_region_reserved_end_pfn() #

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

for_each_mem_region() #

for_each_mem_region(region)

iterate over memory regions

Parameters

  • region: loop variable

for_each_reserved_mem_region() #

for_each_reserved_mem_region(region)

itereate over reserved memory regions

Parameters

  • region: loop variable

__memblock_find_range_bottom_up() #

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(), find free area bottom-up.

Return

Found address on success, 0 on failure.

__memblock_find_range_top_down() #

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(), find free area top-down.

Return

Found address on success, 0 on failure.

memblock_find_in_range_node() #

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.

memblock_find_in_range() #

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.

memblock_discard() #

void memblock_discard(void)

discard memory and reserved arrays if they were allocated

Parameters

  • void: no arguments

memblock_double_array() #

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.

memblock_merge_regions() #

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)

memblock_insert_region() #

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.

memblock_add_range() #

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.

memblock_add_node() #

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() description for mode details

Return

0 on success, -errno on failure.

memblock_add() #

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() description for mode details

Return

0 on success, -errno on failure.

memblock_validate_numa_coverage() #

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.

memblock_isolate_range() #

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.

memblock_free() #

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.

memblock_phys_free() #

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.

memblock_setclr_flag() #

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.

memblock_mark_hotplug() #

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.

memblock_clear_hotplug() #

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.

memblock_mark_mirror() #

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.

memblock_mark_nomap() #

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.

memblock_clear_nomap() #

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.

memblock_reserved_mark_noinit() #

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.

memblock_mark_kho_scratch() #

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.

memblock_clear_kho_scratch() #

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.

__next_mem_range() #

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() 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.

__next_mem_range_rev() #

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().

memblock_set_node() #

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.

memblock_alloc_range_nid() #

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.

memblock_phys_alloc_range() #

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.

memblock_phys_alloc_try_nid() #

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.

memblock_alloc_internal() #

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() 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().

Return

Virtual address of allocated memory block on success, NULL on failure.

memblock_alloc_exact_nid_raw() #

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.

memblock_alloc_try_nid_raw() #

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.

memblock_alloc_try_nid() #

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.

__memblock_alloc_or_panic() #

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.

memblock_free_late() #

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.

memblock_estimated_nr_free_pages() #

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.

memblock_is_region_memory() #

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

memblock_is_region_reserved() #

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.

memblock_free_all() #

void memblock_free_all(void)

release free pages to the buddy allocator

Parameters

  • void: no arguments

reserve_mem_find_by_name() #

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.

reserve_mem_release_by_name() #

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

Author: David S. Miller <davem@redhat.com>

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-->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->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->vm_mm. Also, one may test (vma->vm_flags & 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->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->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->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-->physical mapping to a new value, the sequence will be in one of the following forms:

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-->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-->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->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->vm_mm. Also, one may test (vma->vm_flags & 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->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->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

Device Memory Cgroup API (dmemcg) #

dmem_cgroup_state_evict_valuable() #

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

dmem_cgroup_unregister_region() #

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.

dmem_cgroup_register_region() #

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.

dmem_cgroup_pool_state_put() #

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().

dmem_cgroup_uncharge() #

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.

dmem_cgroup_try_charge() #

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() 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

Author: David Howells <dhowells@redhat.com>

Author: Paul E. McKenney <paulmck@linux.ibm.com>

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.

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.

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:

#include <linux/circ_buf.h>

The macros are:

  1. Measure the remaining capacity of a buffer:

    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:

    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:

    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:

    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.

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.

The producer #

The producer will look something like this:

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.

The Consumer #

The consumer will look something like this:

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.

Further reading #

See also Documentation/memory-barriers.txt for a description of Linux's memory barrier facilities.

Scope-based Cleanup Helpers

Peios Kernel / Internals / Core APIs

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()), 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:

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() if dev is non-NULL when dev goes out of scope (automatic variable scope). If a function wants to invoke pci_dev_put() on error, but return dev (i.e. without freeing it) on success, it can do:

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:

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:

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:

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 "!!":

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:

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

Date: September, 2021

Author: Sebastian Andrzej Siewior <bigeasy@linutronix.de>, Rusty Russell <rusty@rustcorp.com.au>, Srivatsa Vaddagiri <vatsa@in.ibm.com>, Ashok Raj <ashok.raj@intel.com>, Joel Schopp <jschopp@austin.ibm.com>, Thomas Gleixner <tglx@kernel.org>

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.

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.

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.

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:

$ 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:

$ 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:

$ 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.

The CPU hotplug coordination #

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.

The CPU hotplug API #

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.

CPU online/offline operations #

A successful online operation looks like this:

[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:

[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:

[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:

[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:

[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:

[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:

[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.

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.

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:

prepare

For states in the PREPARE section

dead

For states in the PREPARE section which do not provide a startup callback

starting

For states in the STARTING section

dying

For states in the STARTING section which do not provide a startup callback

online

For states in the ONLINE section

offline

For states in the ONLINE section which do not provide a startup callback

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:

    0

    Statically allocated state was successfully set up

    >0

    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.

    <0

    Operation failed

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.

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.

Examples #

Setup and teardown a statically allocated state in the STARTING section for notifications on online and offline operations:

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:

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:

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:

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);

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

$ 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:

$ 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:

$ 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:

#  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.

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.

User Space Notification #

After CPU successfully onlined or offline udev events are sent. A udev rule like:

SUBSYSTEM=="cpu", DRIVERS=="processor", DEVPATH=="/devices/system/cpu/*", RUN+="the_hotplug_receiver.sh"

will receive all events. A script like:

#!/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.

Kernel Inline Documentations Reference #

cpuhp_setup_state() #

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.

cpuhp_setup_state_cpuslocked() #

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() except that it must be invoked from within a cpus_read_lock() held region.

cpuhp_setup_state_nocalls() #

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() except that the startup callback is not invoked during installation. NOP if SMP=n or HOTPLUG_CPU=n.

cpuhp_setup_state_nocalls_cpuslocked() #

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() except that it must be invoked from within a cpus_read_lock() held region.

cpuhp_setup_state_multi() #

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() or cpuhp_state_add_instance_nocalls()

cpuhp_state_add_instance() #

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().

cpuhp_state_add_instance_nocalls() #

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.

cpuhp_state_add_instance_nocalls_cpuslocked() #

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() except that it must be invoked from within a cpus_read_lock() held region.

cpuhp_remove_state() #

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.

cpuhp_remove_state_nocalls() #

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

cpuhp_remove_state_nocalls_cpuslocked() #

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.

cpuhp_remove_multi_state() #

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(). All instances should have been removed before invoking this function.

cpuhp_state_remove_instance() #

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.

cpuhp_state_remove_instance_nocalls() #

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

Author: Thomas Gleixner

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.

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.

Debug functions #

debug_object_init() #

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.

debug_object_init_on_stack() #

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.

debug_object_activate() #

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.

debug_object_deactivate() #

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.

debug_object_destroy() #

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.

debug_object_free() #

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.

debug_object_assert_init() #

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.

Fixup functions #

Debug object type description structure #

struct debug_obj #

representation of an tracked object

Definition

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

struct debug_obj_descr #

object type specific debug description structure

Definition

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

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.

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.

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.

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.

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.

Known Bugs And Assumptions #

None (knock on wood).

Using physical DMA provided by OHCI-1394 FireWire controllers for debugging

Peios Kernel / Internals / Core APIs

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).

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.

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/

and he implemented fast system dump (alpha version - read README.txt): - 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

The latest version of this gdb proxy (fireproxy-0.34) can communicate (not yet stable) with kgdb over an memory-based communication module (kgdbom).

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:

    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:

    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:

        $ 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:

    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.

Notes #

Documentation and specifications: http://halobates.de/firewire/

FireWire is a trademark of Apple Inc. - for more information please refer to: https://en.wikipedia.org/wiki/FireWire

Dynamic DMA mapping Guide

Peios Kernel / Internals / Core APIs

Author: David S. Miller <davem@redhat.com>

Author: Richard Henderson <rth@cygnus.com>

Author: Jakub Jelinek <jakub@redhat.com>

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.

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:

             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:

#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.

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.

__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:

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):

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.

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():

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():

int dma_set_mask(struct device *dev, u64 mask);

The setup for coherent allocations is performed via a call to dma_set_coherent_mask():

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, &pdev->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:

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:

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:

/* 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:

/* 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:

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:

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:

#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.

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:

    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.

Using Coherent DMA mappings #

To allocate and map large (PAGE_SIZE or so) coherent DMA regions, you should do:

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 > 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:

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:

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:

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:

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:

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.

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:

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.

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:

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:

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:

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:

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->address and sg->length as shown above.

To unmap a scatterlist, just call:

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:

dma_sync_single_for_cpu(dev, dma_handle, size, direction);

or:

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:

dma_sync_single_for_device(dev, dma_handle, size, direction);

or:

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:

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);
                }
        }
}

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():

    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:

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:

/*
 * 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.

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:

    struct ring_state {
            struct sk_buff *skb;
            dma_addr_t mapping;
            __u32 len;
    };
    

    after:

    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:

    ringp->mapping = FOO;
    ringp->len = BAR;
    

    after:

    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:

    dma_unmap_single(dev, ringp->mapping, ringp->len,
                     DMA_FROM_DEVICE);
    

    after:

    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.

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).

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:

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

Author: James E.J. Bottomley <James.Bottomley@HansenPartnership.com>

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.

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.

Part I - DMA API #

To get the DMA API, you must #include <linux/dma-mapping.h>. 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.

Part Ia - Using large DMA-coherent buffers #

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 <size> 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 <dma_handle> 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).

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.

Part Ib - Using small DMA-coherent buffers #

To get this part of the DMA API, you must #include <linux/dmapool.h>

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.

dma_pool_create_node() #

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() 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() 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.

dma_pool_destroy() #

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.

dma_pool_alloc() #

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.

dma_pool_free() #

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.

dmam_pool_create() #

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.

dmam_pool_destroy() #

void dmam_pool_destroy(struct dma_pool *pool)

Managed dma_pool_destroy()

Parameters

  • struct dma_pool *pool: dma pool that will be destroyed

Description

Managed dma_pool_destroy().

dma_pool_zalloc() #

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(), but the returned memory is zeroed.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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. 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.

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:

DMA_NONE

no direction (used for debugging)

DMA_TO_DEVICE

data is going from the memory to the device

DMA_FROM_DEVICE

data is coming from the device to the memory

DMA_BIDIRECTIONAL

direction isn't known

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).

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().

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 <offset> and <size> 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.

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.

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).

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 <nents> 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:

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->address and sg->length as shown above.

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: <nents> must be the number you passed in, not the number of DMA address entries returned.

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().

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.

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:

#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.::

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 */
        ....
}

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.

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.

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.

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.

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:

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

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

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().

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.

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 <size> 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 <dma_handle> 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.

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().

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().

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.

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().

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 <size> 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->nents, but it might have multiple CPU side segments as indicated by sgt->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.

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().

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).

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().

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().

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.

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:

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:

dma-api/all_errors

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.

dma-api/disabled

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

dma-api/dump

This read-only file contains current DMA mappings.

dma-api/error_count

This file is read-only and shows the total numbers of errors found.

dma-api/num_errors

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

dma-api/min_free_entries

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.

dma-api/num_free_entries

The current number of free dma_debug_entries in the allocator.

dma-api/nr_total_entries

The total number of dma_debug_entries in the allocator, both free and used.

dma-api/driver_filter

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.

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=<drivername> 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=<your_desired_number>' 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.

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.

Functions and structures #

sg_next() #

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.

sg_assign_page() #

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(), the most commonly used variant.

sg_set_page() #

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.

sg_set_folio() #

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.

sg_set_buf() #

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

sg_chain() #

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.

sg_mark_end() #

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() on this entry will return NULL.

sg_unmark_end() #

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.

sg_dma_is_bus_address() #

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() has been called on this segment.

sg_dma_mark_bus_address() #

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().

sg_dma_unmark_bus_address() #

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.

sg_dma_is_swiotlb() #

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().

sg_dma_mark_swiotlb() #

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.

sg_phys() #

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.

sg_virt() #

void * sg_virt(struct scatterlist *sg)

Return virtual address of an sg entry

Parameters

  • struct scatterlist *sg: SG entry

Description

This calls 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.

sg_init_marker() #

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

sg_alloc_table_from_pages() #

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

sg_page_iter_page() #

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

sg_page_iter_dma_address() #

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

for_each_sg_page() #

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() to get each page pointer. In each loop it operates on PAGE_SIZE unit.

for_each_sg_dma_page() #

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() to get each page's DMA address. In each loop it operates on PAGE_SIZE unit.

for_each_sgtable_page() #

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(). In each loop it operates on PAGE_SIZE unit.

for_each_sgtable_dma_page() #

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(). In each loop it operates on PAGE_SIZE unit.

sg_nents() #

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

sg_nents_for_len() #

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

sg_nents_for_dma() #

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

sg_last() #

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.

sg_init_table() #

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() should be used only on the last table part.

sg_init_one() #

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

__sg_free_table() #

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(). The max_ents value must be identical to that previously used with __sg_alloc_table().

sg_free_append_table() #

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

sg_free_table() #

void sg_free_table(struct sg_table *table)

Free a previously allocated sg table

Parameters

  • struct sg_table *table: The mapped sg table header

__sg_alloc_table() #

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() to cleanup any leftover allocations.

sg_alloc_table() #

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.

sg_alloc_append_table_from_pages() #

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() to cleanup any leftover allocations.

In the fist call, sgt_append must by initialized.

sg_alloc_table_from_pages_segment() #

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

sgl_alloc_order() #

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()
  • 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.

sgl_alloc() #

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.

sgl_free_n_order() #

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()

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.

sgl_free_order() #

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()

sgl_free() #

void sgl_free(struct scatterlist *sgl)

free a scatterlist and its pages

Parameters

  • struct scatterlist *sgl: Scatterlist with one or more elements

sg_miter_start() #

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.

sg_miter_skip() #

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(), this stops miter.

Context

Don't care.

Return

true if miter contains the valid mapping. false if end of sg list is reached.

sg_miter_next() #

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(). 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.

sg_miter_stop() #

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(). A stopped iteration can be resumed by calling sg_miter_next() on it. This is useful when resources (kmap) need to be released during iteration.

Context

Don't care otherwise.

sg_copy_buffer() #

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.

sg_copy_from_buffer() #

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.

sg_copy_to_buffer() #

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.

sg_pcopy_from_buffer() #

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.

sg_pcopy_to_buffer() #

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.

sg_zero_buffer() #

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.

extract_iter_to_sg() #

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.

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.

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.

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.

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!

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.

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.

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.

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).

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.

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.

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

Author: Pierre Ossman <drzeus@drzeus.cx>

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.

Headers and dependencies #

To do ISA style DMA you need to include two headers:

#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 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.

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.)

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.

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.

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:

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);

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:

  • 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, KVM, Interrupts and regular exceptions, NMI and NMI-like exceptions.

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:

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.

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:

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.

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.

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:

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.

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:

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:

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.

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:

31..13

12

11..0

counter

SF

errno

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.

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:

struct worker_drone {
        errseq_t        wd_err; /* for recording errors */
};

Every day, the worker_drone starts out with a blank slate:

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:

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:

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:

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:

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.

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.:

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.

Functions #

errseq_set() #

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.

errseq_sample() #

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.

errseq_check() #

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.

errseq_check_and_advance() #

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 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.

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:

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:

CC_FLAGS_FPU := -mhard-float

or:

CC_FLAGS_NO_FPU := -msoft-float

Normal kernel code is assumed to use the equivalent of CC_FLAGS_NO_FPU.

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.

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.

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

Author: David Howells <dhowells@redhat.com>

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:

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:

#include <linux/folio_queue.h>

and to use the iterator:

#include <linux/uio.h>

Initialisation #

A segment should be initialised by calling:

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.

Adding and removing folios #

Folios can be set in the next unused slot in a segment struct by calling one of:

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:

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.

Querying information about a folio #

Information about the folio in a particular slot may be queried by the following function:

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:

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.

Querying information about a folio_queue #

Information may be retrieved about a particular segment with the following functions:

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.

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:

void folioq_mark(struct folio_queue *folioq, unsigned int slot);
void folioq_mark2(struct folio_queue *folioq, unsigned int slot);

Cleared by:

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:

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.

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:

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.

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.

API Function Reference #

folioq_init() #

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.

folioq_nr_slots() #

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!

folioq_count() #

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.

folioq_full() #

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.

folioq_is_marked() #

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.

folioq_mark() #

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.

folioq_unmark() #

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.

folioq_is_marked2() #

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.

folioq_mark2() #

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.

folioq_unmark2() #

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.

folioq_append() #

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.

folioq_append_mark() #

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.

folioq_folio() #

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.

folioq_folio_order() #

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.

folioq_folio_size() #

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.

folioq_clear() #

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 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 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.

Code using this allocator should include <linux/genalloc.h>. The action begins with the creation of a pool using one of:

gen_pool_create() #

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.

devm_gen_pool_create() #

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:

gen_pool_destroy() #

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:

gen_pool_add() #

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.

gen_pool_add_owner() #

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:

gen_pool_alloc() #

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.

gen_pool_dma_alloc() #

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

gen_pool_free_owner() #

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() 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< 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:

gen_pool_alloc_algo_owner() #

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.

gen_pool_set_algo() #

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.

gen_pool_virt_to_phys() #

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.

gen_pool_for_each_chunk() #

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.

gen_pool_has_addr() #

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.

gen_pool_avail() #

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.

gen_pool_size() #

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.

gen_pool_get() #

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.

of_gen_pool_get() #

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

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.

generic radix tree functions #

genradix_init() #

genradix_init(_radix)

initialize a genradix

Parameters

  • _radix: genradix to initialize

Description

Does not fail

genradix_free() #

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

genradix_ptr() #

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.

genradix_ptr_alloc() #

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

genradix_iter_init() #

genradix_iter_init(_radix, _idx)

initialize a genradix_iter

Parameters

  • _radix: genradix that will be iterated over
  • _idx: index to start iterating from

genradix_iter_peek() #

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

genradix_iter_peek_prev() #

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

genradix_for_each() #

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.

genradix_for_each_reverse() #

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.

genradix_prealloc() #

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

Copyright: © 2005-2010: Thomas Gleixner

Copyright: © 2005-2006: Ingo Molnar

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.

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.

Known Bugs And Assumptions #

None (knock on wood).

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

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->handle_irq(). This high-level IRQ handling function only uses desc->irq_data.chip primitives referenced by the assigned chip descriptor structure.

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.

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.

Default flow implementations #

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):

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)
{
}

Default flow handler implementations #

Default Level IRQ flow handler #

handle_level_irq provides a generic implementation for level-triggered interrupts.

The following control flow is implemented (simplified excerpt):

desc->irq_data.chip->irq_mask_ack();
handle_irq_event(desc->action);
desc->irq_data.chip->irq_unmask();

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):

handle_irq_event(desc->action);
desc->irq_data.chip->irq_eoi();

Default Edge IRQ flow handler #

handle_edge_irq provides a generic implementation for edge-triggered interrupts.

The following control flow is implemented (simplified excerpt):

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;

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):

handle_irq_event(desc->action);

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):

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();

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.

Bad IRQ flow handler #

handle_bad_irq is used for spurious interrupts which have no real handler assigned..

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.

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.

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.

__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.

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->lock, by the generic layer.

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.

irq_gc_noop() #

void irq_gc_noop(struct irq_data *d)

NOOP function

Parameters

  • struct irq_data *d: irq_data

irq_gc_mask_disable_reg() #

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.

irq_gc_mask_set_bit() #

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

irq_gc_mask_clr_bit() #

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

irq_gc_unmask_enable_reg() #

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.

irq_gc_ack_set_bit() #

void irq_gc_ack_set_bit(struct irq_data *d)

Ack pending interrupt via setting bit

Parameters

  • struct irq_data *d: irq_data

irq_gc_mask_disable_and_ack_set() #

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.

irq_gc_set_wake() #

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.

irq_alloc_generic_chip() #

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

irq_domain_alloc_generic_chips() #

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

irq_domain_remove_generic_chips() #

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

__irq_alloc_domain_generic_chips() #

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

irq_get_domain_generic_chip() #

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

irq_setup_generic_chip() #

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.

irq_setup_alt_chip() #

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.

irq_remove_generic_chip() #

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.

Structures #

This chapter contains the autogenerated documentation of the structures which are used in the generic IRQ layer.

struct irq_common_data #

per irq data shared by all irqchips

Definition

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.

struct irq_data #

per irq chip data passed down to chip functions

Definition

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

struct irq_chip #

hardware interrupt chip descriptor

Definition

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

struct irq_chip_regs #

register offsets for struct irq_gci

Definition

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

struct irq_chip_type #

Generic interrupt chip instance for a flow type

Definition

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.

struct irq_chip_generic #

Generic irq chip data structure

Definition

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.

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)

struct irq_domain_chip_generic_info #

Generic chip information structure

Definition

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.

struct irqaction #

per interrupt action descriptor

Definition

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

request_irq() #

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() for details.

struct irq_affinity_notify #

context for notification of IRQ affinity changes

Definition

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.

struct irq_affinity #

Description for automatic irq affinity assignments

Definition

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.

struct irq_affinity_desc #

Interrupt affinity descriptor

Definition

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

irq_update_affinity_hint() #

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.

irq_set_affinity_and_hint() #

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.

Public Functions Provided #

This chapter contains the autogenerated documentation of the kernel API functions which are exported.

synchronize_hardirq() #

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.

synchronize_irq() #

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.

irq_can_set_affinity() #

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

irq_can_set_affinity_usr() #

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() above, but additionally checks for the AFFINITY_MANAGED flag.

irq_set_thread_affinity() #

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() here as we hold desc->lock and this code can be called from hard interrupt context.

irq_affinity_schedule_notify_work() #

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

irq_update_affinity_desc() #

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.

irq_set_affinity() #

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

irq_force_affinity() #

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.

irq_set_affinity_notifier() #

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().

irq_set_vcpu_affinity() #

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().

disable_irq_nosync() #

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(), this function does not ensure existing instances of the IRQ handler have completed before returning.

This function may be called from IRQ context.

disable_irq() #

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.

disable_hardirq() #

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.

disable_nmi_nosync() #

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.

enable_irq() #

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(). 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 !

enable_nmi() #

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.

irq_set_irq_wake() #

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() 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.

irq_wake_thread() #

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

free_irq() #

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.

request_threaded_irq() #

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

request_any_context_irq() #

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.

request_nmi() #

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.

irq_percpu_is_enabled() #

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.

free_percpu_irq() #

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.

request_percpu_irq_affinity() #

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.

request_percpu_nmi() #

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() 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.

prepare_percpu_nmi() #

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.

teardown_percpu_nmi() #

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().

IRQ line should not be enabled for the current CPU. As a CPU local operation, this should be called from non-preemptible context.

irq_get_irqchip_state() #

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.

irq_set_irqchip_state() #

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.

irq_has_action() #

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

irq_check_status_bit() #

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

irq_set_chip() #

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

irq_set_irq_type() #

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

irq_set_handler_data() #

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

irq_set_chip_data() #

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

handle_nested_irq() #

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.

handle_simple_irq() #

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.

handle_untracked_irq() #

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.

handle_level_irq() #

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.

handle_fasteoi_irq() #

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.

handle_fasteoi_nmi() #

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.

handle_edge_irq() #

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.

handle_fasteoi_ack_irq() #

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(), but for use with hierarchy where the irq_chip also needs to have its ->irq_ack() function called.

handle_fasteoi_mask_irq() #

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(), but for use with hierarchy where the irq_chip also needs to have its ->irq_mask_ack() function called.

irq_chip_set_parent_state() #

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.

irq_chip_get_parent_state() #

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.

irq_chip_shutdown_parent() #

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().

irq_chip_startup_parent() #

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().

irq_chip_enable_parent() #

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

irq_chip_disable_parent() #

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

irq_chip_ack_parent() #

void irq_chip_ack_parent(struct irq_data *data)

Acknowledge the parent interrupt

Parameters

  • struct irq_data *data: Pointer to interrupt specific data

irq_chip_mask_parent() #

void irq_chip_mask_parent(struct irq_data *data)

Mask the parent interrupt

Parameters

  • struct irq_data *data: Pointer to interrupt specific data

irq_chip_mask_ack_parent() #

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

irq_chip_unmask_parent() #

void irq_chip_unmask_parent(struct irq_data *data)

Unmask the parent interrupt

Parameters

  • struct irq_data *data: Pointer to interrupt specific data

irq_chip_eoi_parent() #

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

irq_chip_set_affinity_parent() #

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.

irq_chip_set_type_parent() #

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.

irq_chip_retrigger_hierarchy() #

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.

irq_chip_set_vcpu_affinity_parent() #

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

irq_chip_set_wake_parent() #

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.

irq_chip_request_resources_parent() #

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

irq_chip_release_resources_parent() #

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

Internal Functions Provided #

This chapter contains the autogenerated documentation of the internal functions.

irq_get_nr_irqs() #

unsigned int irq_get_nr_irqs(void)

Number of interrupts supported by the system.

Parameters

  • void: no arguments

irq_set_nr_irqs() #

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.

generic_handle_irq() #

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.

generic_handle_irq_safe() #

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.

generic_handle_domain_irq() #

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.

generic_handle_domain_nmi() #

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.

generic_handle_demux_domain_irq() #

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

irq_free_descs() #

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

__irq_alloc_descs() #

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

irq_get_next_irq() #

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.

kstat_irqs_cpu() #

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.

kstat_irqs_usr() #

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().

handle_bad_irq() #

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.

generic_handle_arch_irq() #

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

irq_set_msi_desc_off() #

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

irq_set_msi_desc() #

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

irq_disable() #

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.

handle_percpu_irq() #

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

handle_percpu_devid_irq() #

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() 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

irq_cpu_online() #

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() for each.

irq_cpu_offline() #

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() for each.

irq_chip_compose_msi_msg() #

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.

irq_chip_pm_get() #

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.

irq_chip_pm_put() #

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(), 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() and it may not disable power at all (if user space prevents that, for example).

Credits #

The following people have contributed to this document:

  1. Thomas Gleixner tglx@kernel.org

  2. Ingo Molnar mingo@elte.hu

GFP masks used from FS/IO context

Peios Kernel / Internals / Core APIs

Date: May, 2018

Author: Michal Hocko <mhocko@kernel.org>

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.

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.

memalloc_nofs_save() #

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.

memalloc_nofs_restore() #

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.

memalloc_noio_save() #

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.

memalloc_noio_restore() #

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.

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.

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.

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:

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:

housekeeping_cpumask(HK_TYPE_DOMAIN)

Similarly with nohz_full=5,6 the following will return a mask with all possible CPUs except 5,6:

housekeeping_cpumask(HK_TYPE_KERNEL_NOISE)

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()):

rcu_assign_pointer(housekeeping_cpumasks[type], trial);
synchronize_rcu();
flush_workqueue(example_workqueue);

And then on the read side:

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

Author: Matthew Wilcox

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 instead.

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() is able to be called locklessly, using RCU. The caller must ensure calls to this function are made within 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() grace period).

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(), ida_alloc_min(), ida_alloc_max() or ida_alloc_range(). To free an ID, call ida_free().

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.

Functions and structures #

IDR_INIT() #

IDR_INIT(name)

Initialise an IDR.

Parameters

  • name: Name of IDR.

Description

A freshly-initialised IDR contains no IDs.

DEFINE_IDR() #

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.

idr_get_cursor() #

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() if it is free (otherwise the search will start from this position).

idr_set_cursor() #

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() will return val if it is free (otherwise the search will start from this position).

idr_init_base() #

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() creates an IDR which will allocate IDs starting at base.

idr_init() #

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().

idr_is_empty() #

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.

idr_preload_end() #

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.

idr_for_each_entry() #

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.

idr_for_each_entry_ul() #

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.

idr_for_each_entry_continue() #

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.

idr_for_each_entry_continue_ul() #

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.

ida_alloc() #

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.

ida_alloc_min() #

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.

ida_alloc_max() #

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.

idr_alloc_u32() #

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() 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.

idr_alloc() #

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.

idr_alloc_cyclic() #

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.

idr_remove() #

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.

idr_find() #

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(), given that the leaf pointers lifetimes are correctly managed.

Return

The pointer associated with this ID.

idr_for_each() #

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() can be called concurrently with idr_alloc() and 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.

idr_get_next_ul() #

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.

idr_get_next() #

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.

idr_replace() #

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() and 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.

ida_alloc_range() #

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.

ida_find_first_range() #

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.

ida_free() #

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.

ida_destroy() #

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

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 and the VFS callback reference for the Peios integration contracts.

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.

String Conversions #

simple_strtoull() #

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.

simple_strtoul() #

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.

simple_strtol() #

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.

simple_strtoll() #

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.

vsnprintf() #

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(). 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().

vscnprintf() #

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().

See the vsnprintf() documentation for format string extensions over C99.

snprintf() #

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() documentation for format string extensions over C99.

scnprintf() #

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.

vsprintf() #

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() or vscnprintf() in order to avoid buffer overflows.

If you're not already dealing with a va_list consider using sprintf().

See the vsnprintf() documentation for format string extensions over C99.

sprintf() #

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() or scnprintf() in order to avoid buffer overflows.

See the vsnprintf() documentation for format string extensions over C99.

vbin_printf() #

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().

bstr_printf() #

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(). If the return is greater than or equal to size, the resulting string is truncated.

vsscanf() #

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

sscanf() #

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

kstrtoul() #

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(). Return code must be checked.

kstrtol() #

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(). Return code must be checked.

kstrtoull() #

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(). Return code must be checked.

kstrtoll() #

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(). Return code must be checked.

kstrtouint() #

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(). Return code must be checked.

kstrtoint() #

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(). Return code must be checked.

kstrtobool() #

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.

string_get_size() #

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).

parse_int_array_user() #

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.

string_unescape() #

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:

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.

string_escape_mem() #

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:

%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.

kasprintf_strarray() #

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() after use.

Returns array of strings or NULL when memory can't be allocated.

kfree_strarray() #

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.

skip_spaces() #

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.

strim() #

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.

sysfs_streq() #

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.

match_string() #

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.

__sysfs_match_string() #

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(). 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.

strreplace() #

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.

memcpy_and_pad() #

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.

String Manipulation #

unsafe_memcpy() #

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.

strncpy() #

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() remains ambiguous and fragile. Instead, please choose an alternative, so that the expectation of p's contents is unambiguous:

+--------------------+--------------------+------------+
| **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.

strnlen() #

__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.

strlen() #

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().

Returns number of characters in p (NOT including the final NUL).

strlcat() #

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(), seq_buf, or similar.

Returns total bytes that would have been contained by p regardless of truncation, similar to snprintf(). If return value is >= avail, the string has been truncated.

strcat() #

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() or similar. At the very least, use strncat().

Returns p.

strncat() #

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() or similar.

Returns p.

strcpy() #

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(), though note its different return values for detecting truncation.

Returns p.

strncasecmp() #

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

stpcpy() #

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.

strcmp() #

int strcmp(const char *cs, const char *ct)

Compare two strings

Parameters

  • const char *cs: One string
  • const char *ct: Another string

strncmp() #

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

strchr() #

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.

strchrnul() #

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.

strrchr() #

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

strnchr() #

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.

strspn() #

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

strcspn() #

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

strpbrk() #

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

strsep() #

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() 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. ;)

memset() #

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() to access IO space, use memset_io() instead.

memset16() #

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() 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.

memset32() #

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() 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.

memset64() #

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() 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.

memcpy() #

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.

memmove() #

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(), memmove() copes with overlapping areas.

memcmp() #

__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.

bcmp() #

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(). 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.

memscan() #

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

strstr() #

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

strnstr() #

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

memchr() #

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

memchr_inv() #

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.

memdup_array_user() #

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() on failure. Result is physically contiguous, to be freed by kfree().

vmemdup_array_user() #

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() on failure. Result may be not physically contiguous. Use kvfree() to free.

strscpy() #

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() 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().

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.

strscpy_pad() #

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().

Return

  • The number of characters copied (not including the trailing NULs)
  • -E2BIG if count is 0 or src was truncated.

mem_is_zero() #

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.

sysfs_match_string() #

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(). Calculates the size of a automatically.

memzero_explicit() #

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() is just fine (!), but in cases where clearing out local data at the end of a scope is necessary, memzero_explicit() should be used instead in order to prevent the compiler from optimising away zeroing.

memzero_explicit() doesn't need an arch-specific version as it just invokes the one of memset() implicitly.

kbasename() #

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.

strtomem_pad() #

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() 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().

Note that the size of dest is not an argument, as the length of dest must be discoverable by the compiler.

strtomem() #

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() 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().

Note that the size of dest is not an argument, as the length of dest must be discoverable by the compiler.

memtostr() #

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() uses where the source is not a NUL-terminated string.

Note that sizes of dest and src must be known at compile-time.

memtostr_pad() #

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() uses where the source is not a NUL-terminated string.

Note that sizes of dest and src must be known at compile-time.

memset_after() #

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.

memset_startat() #

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() should be used to clear the prior padding.

str_has_prefix() #

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().

Return

  • strlen(prefix) if str starts with prefix
  • 0 if str does not start with prefix

strstarts() #

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.

strends() #

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.

kstrdup() #

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() call when allocating memory

Return

newly allocated copy of s or NULL in case of error

kstrdup_const() #

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() 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.

kstrndup() #

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() call when allocating memory

Note

Use kmemdup_nul() instead if the size is known exactly.

Return

newly allocated copy of s or NULL in case of error

kmemdup() #

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() to free.

kmemdup_nul() #

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() call when allocating memory

Return

newly allocated copy of s with NUL-termination or NULL in case of error

memdup_user() #

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() on failure. Result is physically contiguous, to be freed by kfree().

vmemdup_user() #

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() on failure. Result may be not physically contiguous. Use kvfree() to free.

strndup_user() #

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() in case of error

memdup_user_nul() #

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() on failure.

Basic Kernel Library Functions #

The Linux kernel provides more basic utility functions.

Bit Operations #

set_bit() #

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.

clear_bit() #

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).

change_bit() #

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.

test_and_set_bit() #

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).

test_and_clear_bit() #

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).

test_and_change_bit() #

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).

___set_bit() #

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(), 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.

___clear_bit() #

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(), 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.

___change_bit() #

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(), 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.

___test_and_set_bit() #

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.

___test_and_clear_bit() #

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.

___test_and_change_bit() #

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.

_test_bit() #

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

_test_bit_acquire() #

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

clear_bit_unlock() #

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.

__clear_bit_unlock() #

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.

test_and_set_bit_lock() #

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.

xor_unlock_is_negative_byte() #

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.

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.

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.:

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)

__bitmap_shift_right() #

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.

__bitmap_shift_left() #

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.

bitmap_cut() #

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:

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:

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.

bitmap_find_next_zero_area_off() #

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.

bitmap_remap() #

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.

bitmap_bitremap() #

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.

bitmap_from_arr32() #

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

bitmap_to_arr32() #

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

bitmap_from_arr64() #

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

bitmap_to_arr64() #

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

bitmap_pos_to_ord() #

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.

bitmap_onto() #

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() 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() operator does this by setting the bit (m % W) in dst, for each bit (m) set in orig.

  • Example [1] for 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() + bitmap_onto(): Let's say relmap has these ten bits set:

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() then bitmap_onto, as suggested above to avoid the possibility of an empty dst result:

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() to fold the orig bitmap modulo ten (the weight of relmap):

=============== ============== =================
@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.

bitmap_fold() #

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() for why and how to use this.

bitmap_find_next_zero_area() #

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.

bitmap_or_equal() #

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

bitmap_scatter() #

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:

src:  0000000001011010
                ||||||
         +------+|||||
         |  +----+||||
         |  |+----+|||
         |  ||   +-+||
         |  ||   |  ||
mask: ...v..vv...v..vv
      ...0..11...0..10
dst:  0000001100000010

A relationship exists between bitmap_scatter() and bitmap_gather(). See bitmap_gather() for the bitmap gather detailed operations. TL;DR: bitmap_gather() can be seen as the 'reverse' bitmap_scatter() operation.

bitmap_gather() #

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:

mask: ...v..vv...v..vv
src:  0000001100000010
         ^  ^^   ^   0
         |  ||   |  10
         |  ||   > 010
         |  |+--> 1010
         |  +--> 11010
         +----> 011010
dst:  0000000000011010

A relationship exists between bitmap_gather() and bitmap_scatter(). See bitmap_scatter() for the bitmap scatter detailed operations. TL;DR: bitmap_scatter() can be seen as the 'reverse' 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() and 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.

bitmap_release_region() #

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).

bitmap_allocate_region() #

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).

bitmap_find_free_region() #

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.

BITMAP_FROM_U64() #

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 #(N32) 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() 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.

bitmap_from_u64() #

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.

bitmap_read() #

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.

bitmap_write() #

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() 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.

Command-line Parsing #

get_option() #

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.

get_options() #

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).

memparse() #

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.

Error Pointers #

IS_ERR_VALUE() #

IS_ERR_VALUE(x)

Detect an error pointer.

Parameters

  • x: The pointer to check.

Description

Like IS_ERR(), but does not generate a compiler warning if result is unused.

ERR_PTR() #

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.

INIT_ERR_PTR() #

INIT_ERR_PTR(error)

Init a const error pointer.

Parameters

  • error: A negative error code.

Description

Like ERR_PTR(), but usable to initialize static variables.

PTR_ERR() #

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.

IS_ERR() #

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.

IS_ERR_OR_NULL() #

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(), but also returns true for a null pointer.

ERR_CAST() #

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.

PTR_ERR_OR_ZERO() #

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:

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.

Sorting #

sort_r() #

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.

sort_r_nonatomic() #

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().

list_sort() #

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(), 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:

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 32^k elements can fit into the cache. Not quite as good as a fully-eager bottom-up mergesort, but it does use 0.2n 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).

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

  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() 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() for linear data or by providing an own get_next_block() implementation and calling 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() regardless of the linearity of the data.

Once you're done using a configuration it must be given back via textsearch_destroy.

EXAMPLE:

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);

textsearch_register() #

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.

textsearch_unregister() #

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.

textsearch_find_continuous() #

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() for continuous/linear data. Call textsearch_next() to retrieve subsequent matches.

Returns the position of first occurrence of the pattern or UINT_MAX if no occurrence was found.

textsearch_prepare() #

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(). If a zero length pattern is passed, this function returns EINVAL.

textsearch_destroy() #

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.

textsearch_next() #

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() 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.

textsearch_find() #

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.

textsearch_get_pattern() #

void * textsearch_get_pattern(struct ts_config *conf)

return head of the pattern

Parameters

  • struct ts_config *conf: search configuration

textsearch_get_pattern_len() #

unsigned int textsearch_get_pattern_len(struct ts_config *conf)

return length of the pattern

Parameters

  • struct ts_config *conf: search configuration

CRC and Math Functions in Linux #

Arithmetic Overflow Checking #

check_add_overflow() #

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.

wrapping_add() #

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.

wrapping_assign_add() #

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.

check_sub_overflow() #

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.

wrapping_sub() #

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.

wrapping_assign_sub() #

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.

check_mul_overflow() #

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.

wrapping_mul() #

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.

check_shl_overflow() #

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.

overflows_type() #

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.

range_overflows() #

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.

range_overflows_t() #

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() but forcing the parameters to type.

Return

true if the range is out of bounds.

range_end_overflows() #

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(), 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.

range_end_overflows_t() #

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() but forcing the parameters to type.

Return

true if the endpoint exceeds the boundary.

castable_to_type() #

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().

size_mul() #

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.

size_add() #

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.

size_sub() #

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() and 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.

array_size() #

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.

array3_size() #

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.

flex_array_size() #

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.

struct_size() #

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.

struct_size_t() #

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() 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.

struct_offset() #

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.

__DEFINE_FLEX() #

__DEFINE_FLEX(type, name, member, count, trailer...)

helper macro for 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.

_DEFINE_FLEX() #

_DEFINE_FLEX(type, name, member, count, initializer...)

helper macro for 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).

DEFINE_RAW_FLEX() #

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.

DEFINE_FLEX() #

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.

STACK_FLEX_ARRAY_SIZE() #

STACK_FLEX_ARRAY_SIZE(name, array)

helper macro for DEFINE_FLEX() family. Returns the number of elements in array.

Parameters

  • name: Name for a variable defined in DEFINE_RAW_FLEX()/DEFINE_FLEX().
  • array: Name of the array member.

typeof_flex_counter() #

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.

overflows_flex_counter_type() #

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.

__set_flex_counter() #

__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() before using this function.

CRC Functions #

crc4() #

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.

crc7_be() #

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.

crc8_populate_msb() #

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.

crc8_populate_lsb() #

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.

crc8() #

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.

crc16() #

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.

crc_ccitt() #

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

crc_itu_t() #

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

crc32_le() #

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().

Context

Any context

Return

The new CRC value

crc32_be() #

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() is the same as crc32_le() except that 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

crc32c() #

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

crc64_be() #

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

crc64_nvme() #

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.

Base 2 log and power Functions #

is_power_of_2() #

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.

__roundup_pow_of_two() #

unsigned long __roundup_pow_of_two(unsigned long n)

round up to nearest power of two

Parameters

  • unsigned long n: value to round up

__rounddown_pow_of_two() #

unsigned long __rounddown_pow_of_two(unsigned long n)

round down to nearest power of two

Parameters

  • unsigned long n: value to round down

const_ilog2() #

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.

ilog2() #

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)

roundup_pow_of_two() #

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

rounddown_pow_of_two() #

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

order_base_2() #

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.

bits_per() #

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.

max_pow_of_two_factor() #

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.

Integer log and power Functions #

intlog2() #

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

intlog10() #

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

int_pow() #

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

int_sqrt() #

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))

int_sqrt64() #

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

Division Functions #

do_div() #

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!

div_u64_rem() #

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.

div_s64_rem() #

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

div64_u64_rem() #

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

div64_u64() #

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

div64_s64() #

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

div_u64() #

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

div_s64() #

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

mul_u64_add_u64_div_u64() #

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

mul_u64_u64_div_u64() #

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

mul_u64_u64_div_u64_roundup() #

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

DIV64_U64_ROUND_UP() #

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

DIV_U64_ROUND_UP() #

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

DIV64_U64_ROUND_CLOSEST() #

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

DIV_U64_ROUND_CLOSEST() #

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

DIV_S64_ROUND_CLOSEST() #

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

roundup_u64() #

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.

gcd() #

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

UUID/GUID #

generate_random_uuid() #

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.

uuid_is_valid() #

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.

Kernel IPC facilities #

IPC utilities #

ipc_init() #

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.

ipc_init_ids() #

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.

ipc_init_proc_interface() #

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.

ipc_findkey() #

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.

ipc_addid() #

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.

ipcget_new() #

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.

ipc_check_perms() #

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.

ipcget_public() #

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.

ipc_kht_remove() #

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.

ipc_search_maxidx() #

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.

ipc_rmid() #

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.

ipc_set_key_private() #

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.

ipcperms() #

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>

kernel_to_ipc64_perm() #

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).

ipc64_perm_to_ipc_perm() #

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.

ipc_obtain_object_idr() #

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.

ipc_obtain_object_check() #

struct kern_ipc_perm * ipc_obtain_object_check(struct ipc_ids *ids, int id)

Similar to 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.

ipcget() #

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().

ipc_update_perm() #

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.

ipcctl_obtain_check() #

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.

ipc_parse_version() #

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.

sysvipc_find_ipc() #

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() 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.

FIFO Buffer #

kfifo interface #

DECLARE_KFIFO_PTR() #

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

DECLARE_KFIFO() #

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

INIT_KFIFO() #

INIT_KFIFO(fifo)

Initialize a fifo declared by DECLARE_KFIFO

Parameters

  • fifo: name of the declared fifo datatype

DEFINE_KFIFO() #

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.

kfifo_initialized() #

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.

kfifo_esize() #

kfifo_esize(fifo)

returns the size of the element managed by the fifo

Parameters

  • fifo: address of the fifo to be used

kfifo_recsize() #

kfifo_recsize(fifo)

returns the size of the record length field

Parameters

  • fifo: address of the fifo to be used

kfifo_size() #

kfifo_size(fifo)

returns the size of the fifo in elements

Parameters

  • fifo: address of the fifo to be used

kfifo_reset() #

kfifo_reset(fifo)

removes the entire fifo content

Parameters

  • fifo: address of the fifo to be used

Note

usage of 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.

kfifo_reset_out() #

kfifo_reset_out(fifo)

skip fifo content

Parameters

  • fifo: address of the fifo to be used

Note

The usage of 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().

kfifo_len() #

kfifo_len(fifo)

returns the number of used elements in the fifo

Parameters

  • fifo: address of the fifo to be used

kfifo_is_empty() #

kfifo_is_empty(fifo)

returns true if the fifo is empty

Parameters

  • fifo: address of the fifo to be used

kfifo_is_empty_spinlocked() #

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

kfifo_is_empty_spinlocked_noirqsave() #

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

kfifo_is_full() #

kfifo_is_full(fifo)

returns true if the fifo is full

Parameters

  • fifo: address of the fifo to be used

kfifo_avail() #

kfifo_avail(fifo)

returns the number of unused elements in the fifo

Parameters

  • fifo: address of the fifo to be used

kfifo_skip_count() #

kfifo_skip_count(fifo, count)

skip output data

Parameters

  • fifo: address of the fifo to be used
  • count: count of data to skip

kfifo_skip() #

kfifo_skip(fifo)

skip output data

Parameters

  • fifo: address of the fifo to be used

kfifo_peek_len() #

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.

kfifo_alloc() #

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()

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(). Return 0 if no error, otherwise an error code.

kfifo_alloc_node() #

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()
  • 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(). Return 0 if no error, otherwise an error code.

kfifo_free() #

kfifo_free(fifo)

frees the fifo

Parameters

  • fifo: the fifo to be freed

kfifo_init() #

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.

kfifo_put() #

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.

kfifo_get() #

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.

kfifo_peek() #

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.

kfifo_in() #

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.

kfifo_in_spinlocked() #

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.

kfifo_in_spinlocked_noirqsave() #

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() but uses spin_lock/unlock() for locking and doesn't disable interrupts.

kfifo_out() #

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.

kfifo_out_spinlocked() #

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.

kfifo_out_spinlocked_noirqsave() #

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() which uses spin_lock/unlock() for locking and doesn't disable interrupts.

kfifo_from_user() #

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.

kfifo_to_user() #

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.

kfifo_dma_in_prepare_mapped() #

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.

kfifo_dma_in_finish() #

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.

kfifo_dma_out_prepare_mapped() #

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.

kfifo_dma_out_finish() #

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.

kfifo_out_peek() #

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.

kfifo_out_linear() #

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() 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.

kfifo_out_linear_ptr() #

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(), 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() 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.

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.

relay interface #

relay_buf_full() #

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.

relay_reset() #

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.

relay_open() #

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.

relay_switch_subbuf() #

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.

relay_subbufs_consumed() #

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'.

relay_close() #

void relay_close(struct rchan *chan)

close the channel

Parameters

  • struct rchan *chan: the channel

Description

Closes all channel buffers and frees the channel.

relay_flush() #

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.

relay_mmap_prepare_buf() #

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.

relay_alloc_buf() #

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.

relay_create_buf() #

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.

relay_destroy_channel() #

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().

relay_destroy_buf() #

void relay_destroy_buf(struct rchan_buf *buf)

destroy an rchan_buf struct and associated buffer

Parameters

  • struct rchan_buf *buf: the buffer struct

relay_remove_buf() #

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().

relay_buf_empty() #

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.

wakeup_readers() #

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

__relay_reset() #

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() for description of effect.

relay_close_buf() #

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.

relay_stats() #

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.

relay_file_open() #

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.

relay_file_mmap_prepare() #

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() to map the file into user space.

relay_file_poll() #

__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.

relay_file_release() #

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.

relay_file_read_subbuf_avail() #

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

relay_file_read_start_pos() #

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.

relay_file_read_end_pos() #

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

Module Support #

Kernel module auto-loading #

__request_module() #

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.

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() 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.

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()
  2. optional module decompression uses vmap()
  3. layout_and allocate() can use 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.

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(). 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(). 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() 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.

Inter Module support #

Refer to the files in kernel/module/ for more information.

Hardware Interfaces #

DMA Channels #

request_dma() #

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

free_dma() #

void free_dma(unsigned int dmanr)

free a reserved system DMA channel

Parameters

  • unsigned int dmanr: DMA channel number

Resources Management #

request_resource_conflict() #

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.

find_next_res() #

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).

reallocate_resource() #

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.

lookup_resource() #

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

insert_resource_conflict() #

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.

resource_alignment() #

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.

release_mem_region_adjustable() #

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.

merge_system_ram_resource() #

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() will split on demand on memory hotunplug

request_resource() #

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.

release_resource() #

int release_resource(struct resource *old)

release a previously reserved resource

Parameters

  • struct resource *old: resource pointer

walk_iomem_res_desc() #

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.

region_intersects() #

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.

find_resource_space() #

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.

allocate_resource() #

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

insert_resource() #

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.

insert_resource_expand_to_fit() #

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.

remove_resource() #

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() or insert_resource_conflict(), and moves the children (if any) up to where they were before. insert_resource() and insert_resource_conflict() insert a new resource, and move any conflicting resources down to the children of the new resource.

insert_resource(), insert_resource_conflict() and remove_resource() are intended for producers of resources, such as FW modules and bus drivers.

adjust_resource() #

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.

__request_region() #

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

__release_region() #

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.

devm_request_resource() #

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(). 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() rather than the regular 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.

devm_release_resource() #

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().

devm_request_free_mem_region() #

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.

alloc_free_mem_region() #

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.

MTRR Handling #

arch_phys_wc_add() #

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.

Security Framework #

lsm_file_alloc() #

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.

lsm_backing_file_alloc() #

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.

lsm_blob_alloc() #

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.

lsm_cred_alloc() #

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.

lsm_inode_alloc() #

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.

lsm_task_alloc() #

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.

lsm_ipc_alloc() #

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.

lsm_key_alloc() #

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.

lsm_msg_msg_alloc() #

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.

lsm_bdev_alloc() #

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.

lsm_bpf_map_alloc() #

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.

lsm_bpf_prog_alloc() #

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.

lsm_bpf_token_alloc() #

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.

lsm_superblock_alloc() #

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.

lsm_fill_user_ctx() #

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.

security_binder_set_context_mgr() #

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.

security_binder_transaction() #

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.

security_binder_transfer_binder() #

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.

security_binder_transfer_file() #

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.

security_ptrace_access_check() #

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.

security_ptrace_traceme() #

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.

security_capget() #

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.

security_capset() #

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.

security_capable() #

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.

security_quotactl() #

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.

security_quota_on() #

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.

security_syslog() #

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.

security_settime64() #

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.

security_vm_enough_memory_mm() #

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.

security_bprm_creds_for_exec() #

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.

security_bprm_creds_from_file() #

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.

security_bprm_check() #

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.

security_bprm_committing_creds() #

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().

security_bprm_committed_creds() #

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().

security_fs_context_submount() #

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.

security_fs_context_dup() #

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.

security_fs_context_parse_param() #

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.

security_sb_alloc() #

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.

security_sb_delete() #

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.

security_sb_free() #

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.

security_sb_kern_mount() #

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.

security_sb_show_options() #

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.

security_sb_statfs() #

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.

security_sb_mount() #

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.

security_sb_umount() #

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.

security_sb_pivotroot() #

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.

security_move_mount() #

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.

security_path_notify() #

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.

security_inode_alloc() #

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.

security_inode_free() #

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(), inode may still be referenced in a VFS path walk and calls to security_inode_permission() may be made during, or after, a call to security_inode_free(). For this reason the inode->i_security field is released via a call_rcu() callback and any LSMs which need to retain inode state for use in security_inode_permission() should only release that state in the inode_free_security_rcu() LSM hook callback.

security_inode_init_security_anon() #

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.

security_path_post_mknod() #

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.

security_path_rmdir() #

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.

security_path_symlink() #

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.

security_path_link() #

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.

security_path_truncate() #

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() hook.

Return

Returns 0 if permission is granted.

security_path_chmod() #

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.

security_path_chown() #

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.

security_path_chroot() #

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.

security_inode_post_create_tmpfile() #

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.

security_inode_link() #

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.

security_inode_unlink() #

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.

security_inode_symlink() #

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.

security_inode_rmdir() #

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.

security_inode_mknod() #

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.

security_inode_rename() #

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.

security_inode_readlink() #

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.

security_inode_follow_link() #

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.

security_inode_permission() #

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.

security_inode_post_setattr() #

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.

security_inode_getattr() #

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.

security_inode_setxattr() #

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.

security_inode_set_acl() #

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.

security_inode_post_set_acl() #

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.

security_inode_get_acl() #

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.

security_inode_remove_acl() #

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.

security_inode_post_remove_acl() #

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.

security_inode_post_setxattr() #

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.

security_inode_getxattr() #

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.

security_inode_listxattr() #

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.

security_inode_removexattr() #

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.

security_inode_post_removexattr() #

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.

security_inode_file_setattr() #

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.

security_inode_file_getattr() #

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.

security_inode_need_killpriv() #

int security_inode_need_killpriv(struct dentry *dentry)

Check if security_inode_killpriv() required

Parameters

  • struct dentry *dentry: associated dentry

Description

Called when an inode has been changed to determine if security_inode_killpriv() should be called.

Return

Return <0 on error to abort the inode change operation, return 0 if security_inode_killpriv() does not need to be called, return >0 if security_inode_killpriv() does need to be called.

security_inode_killpriv() #

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.

security_inode_getsecurity() #

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.

security_inode_setsecurity() #

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.

security_inode_getlsmprop() #

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.

security_kernfs_init_security() #

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.

security_file_permission() #

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.

security_file_alloc() #

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.

security_file_release() #

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.

security_file_free() #

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.

security_backing_file_alloc() #

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.

security_backing_file_free() #

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.

security_mmap_file() #

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.

security_mmap_addr() #

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.

security_file_mprotect() #

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.

security_file_lock() #

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.

security_file_fcntl() #

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.

security_file_set_fowner() #

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.

security_file_send_sigiotask() #

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.

security_file_receive() #

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.

security_file_open() #

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.

security_file_truncate() #

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.

security_task_alloc() #

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.

security_task_free() #

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.

security_cred_alloc_blank() #

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.

security_cred_free() #

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.

security_prepare_creds() #

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.

security_transfer_creds() #

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.

security_kernel_act_as() #

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.

security_kernel_create_files_as() #

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.

security_kernel_module_request() #

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.

security_task_fix_setuid() #

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.

security_task_fix_setgid() #

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.

security_task_fix_setgroups() #

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.

security_task_setpgid() #

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.

security_task_getpgid() #

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.

security_task_getsid() #

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.

security_task_setnice() #

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.

security_task_setioprio() #

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.

security_task_getioprio() #

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.

security_task_prlimit() #

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.

security_task_setrlimit() #

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.

security_task_setscheduler() #

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.

security_task_getscheduler() #

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.

security_task_movememory() #

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.

security_task_kill() #

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.

security_task_prctl() #

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.

security_task_to_inode() #

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.

security_create_user_ns() #

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.

security_ipc_permission() #

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.

security_ipc_getlsmprop() #

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.

security_msg_msg_alloc() #

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.

security_msg_msg_free() #

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.

security_msg_queue_alloc() #

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.

security_msg_queue_free() #

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.

security_msg_queue_associate() #

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.

security_msg_queue_msgctl() #

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.

security_msg_queue_msgsnd() #

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.

security_msg_queue_msgrcv() #

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.

security_shm_alloc() #

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.

security_shm_free() #

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.

security_shm_associate() #

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.

security_shm_shmctl() #

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.

security_shm_shmat() #

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.

security_sem_alloc() #

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.

security_sem_free() #

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.

security_sem_associate() #

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.

security_sem_semctl() #

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.

security_sem_semop() #

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.

security_getselfattr() #

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.

security_setselfattr() #

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.

security_getprocattr() #

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.

security_setprocattr() #

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.

security_post_notification() #

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.

security_watch_key() #

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.

security_netlink_send() #

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.

security_socket_create() #

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.

security_socket_post_create() #

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.

security_socket_bind() #

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.

security_socket_connect() #

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.

security_socket_listen() #

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.

security_socket_accept() #

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.

security_socket_sendmsg() #

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.

security_socket_recvmsg() #

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.

security_socket_getsockname() #

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.

security_socket_getpeername() #

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.

security_socket_getsockopt() #

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.

security_socket_setsockopt() #

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.

security_socket_shutdown() #

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.

security_socket_getpeersec_stream() #

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.

lsm_sock_alloc() #

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.

security_sk_alloc() #

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.

security_sk_free() #

void security_sk_free(struct sock *sk)

Free the sock's LSM blob

Parameters

  • struct sock *sk: sock

Description

Deallocate security structure.

security_inet_csk_clone() #

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.

security_mptcp_add_subflow() #

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() and security_socket_post_create() LSM hooks.

Return

Returns 0 on success or a negative error code on failure.

security_xfrm_policy_clone() #

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.

security_xfrm_policy_delete() #

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.

security_xfrm_state_alloc_acquire() #

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.

security_xfrm_state_free() #

void security_xfrm_state_free(struct xfrm_state *x)

Free a xfrm state

Parameters

  • struct xfrm_state *x: xfrm state

Description

Deallocate x->security.

security_xfrm_policy_lookup() #

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.

security_xfrm_state_pol_flow_match() #

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.

security_xfrm_decode_session() #

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.

security_key_alloc() #

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.

security_key_free() #

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.

security_key_permission() #

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.

security_key_getsecurity() #

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.

security_key_post_create_or_update() #

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.

security_audit_rule_init() #

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.

security_audit_rule_known() #

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.

security_audit_rule_free() #

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().

security_audit_rule_match() #

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().

Return

Returns 1 if secid matches the rule, 0 if it does not, -ERRNO on failure.

security_bpf() #

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.

security_bpf_map() #

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.

security_bpf_prog() #

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.

security_bpf_map_create() #

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.

security_bpf_prog_load() #

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.

security_bpf_token_create() #

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.

security_bpf_token_cmd() #

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.

security_bpf_token_capable() #

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.

security_bpf_map_free() #

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.

security_bpf_prog_free() #

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.

security_bpf_token_free() #

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.

security_perf_event_open() #

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.

security_perf_event_alloc() #

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.

security_perf_event_free() #

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.

security_perf_event_read() #

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.

security_perf_event_write() #

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.

security_uring_override_creds() #

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.

security_uring_sqpoll() #

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.

security_uring_cmd() #

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.

security_uring_allowed() #

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.

security_initramfs_populated() #

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.

securityfs_create_file() #

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() 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.

securityfs_create_dir() #

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() 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.

securityfs_create_symlink() #

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() 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.

securityfs_remove() #

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() 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.

Audit Interfaces #

audit_log_start() #

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.

audit_log_format() #

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.

audit_log_subj_ctx() #

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.

audit_log_end() #

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.

audit_log() #

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.

__audit_filter_op() #

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.

audit_filter_uring() #

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

audit_reset_context() #

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.

audit_alloc() #

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.

audit_log_uring() #

void audit_log_uring(struct audit_context *ctx)

generate a AUDIT_URINGOP record

Parameters

  • struct audit_context *ctx: the audit context

__audit_free() #

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

audit_return_fixup() #

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.

__audit_uring_entry() #

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.

__audit_uring_exit() #

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.

__audit_syscall_entry() #

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).

__audit_syscall_exit() #

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().

__audit_getname() #

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().

__audit_inode() #

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

auditsc_get_stamp() #

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.

__audit_mq_open() #

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

__audit_mq_sendrecv() #

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

__audit_mq_notify() #

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

__audit_mq_getsetattr() #

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

__audit_ipc_obj() #

void __audit_ipc_obj(struct kern_ipc_perm *ipcp)

record audit data for ipc object

Parameters

  • struct kern_ipc_perm *ipcp: ipc permissions

__audit_ipc_set_perm() #

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().

__audit_socketcall() #

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

__audit_fd_pair() #

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

__audit_sockaddr() #

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.

audit_signal_info_syscall() #

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.

__audit_log_bprm_fcaps() #

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

__audit_log_capset() #

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

audit_core_dumps() #

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.

audit_seccomp() #

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.

audit_rule_change() #

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

audit_list_rules_send() #

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

parent_len() #

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

audit_compare_dname_path() #

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.

Accounting Framework #

sys_acct() #

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() 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.

acct_collect() #

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.

acct_process() #

void acct_process(void)

handles process accounting for an exiting task

Parameters

  • void: no arguments

Block Devices #

bio_advance() #

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.

struct folio_iter #

State for iterating all folios in a bio.

Definition

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).

bio_for_each_folio_all() #

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.

bio_next_split() #

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.

bio_iov_bounce_nr_vecs() #

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.

bio_add_max_vecs() #

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.

bio_is_zone_append() #

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.

blk_queue_flag_set() #

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

blk_queue_flag_clear() #

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

blk_op_str() #

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.

blk_sync_queue() #

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.

blk_set_pm_only() #

void blk_set_pm_only(struct request_queue *q)

increment pm_only counter

Parameters

  • struct request_queue *q: request queue pointer

blk_put_queue() #

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.

blk_get_queue() #

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.

submit_bio_noacct() #

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() 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() instead.

submit_bio() #

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() 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.

bio_poll() #

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.

bio_start_io_acct() #

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().

blk_lld_busy() #

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)

blk_start_plug() #

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() 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() is called. However, the block layer may choose to submit requests before a call to 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() and 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.

blk_finish_plug() #

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()

Description

Indicate that a batch of I/O submissions is complete. This function must be paired with an initial call to blk_start_plug(). The intent is to allow the block layer to optimize I/O submission. See the documentation for blk_start_plug() for more information.

blk_queue_enter() #

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

blk_rq_map_user_iov() #

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() must be issued at the end of I/O, while still in process context.

blk_rq_unmap_user() #

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.

blk_rq_map_kern() #

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.

blk_register_queue() #

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.

blk_unregister_queue() #

void blk_unregister_queue(struct gendisk *disk)

counterpart of 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() has finished.

blk_set_stacking_limits() #

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().

queue_limits_commit_update() #

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.

queue_limits_commit_update_frozen() #

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.

queue_limits_set() #

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() instead.

Returns 0 if successful, else a negative error code.

blk_stack_limits() #

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.

queue_limits_stack_bdev() #

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.

queue_limits_stack_integrity() #

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.

blk_set_queue_depth() #

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

blkdev_issue_flush() #

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.

blkdev_issue_discard() #

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.

__blkdev_issue_zeroout() #

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.

blkdev_issue_zeroout() #

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() for the valid values for flags.

blk_trace_ioctl() #

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

blk_trace_shutdown() #

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

blk_add_trace_rq() #

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.

blk_add_trace_bio() #

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.

blk_add_trace_bio_remap() #

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.

blk_add_trace_rq_remap() #

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.

disk_release() #

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() 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() 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

bdev_count_inflight() #

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.

__register_blkdev() #

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.

add_disk_fwnode() #

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.

device_add_disk() #

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.

blk_mark_disk_dead() #

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.

del_gendisk() #

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() call.

The final removal of the struct gendisk happens when its refcount reaches 0 with put_disk(), which should be called after del_gendisk(), if 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

invalidate_disk() #

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

put_disk() #

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() 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.

set_disk_ro() #

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() is typically used by device drivers to indicate whether the underlying physical device is write-protected.

bdev_validate_blocksize() #

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.

bdev_freeze() #

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() and count down in bdev_thaw(). When it becomes 0, thaw_bdev() will unfreeze actually.

Return

On success zero is returned, negative error code on failure.

bdev_thaw() #

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().

Return

On success zero is returned, negative error code on failure.

bd_prepare_to_claim() #

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.

bd_abort_claiming() #

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.

bdev_fput() #

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.

lookup_bdev() #

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.

bdev_mark_dead() #

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.

Char devices #

register_chrdev_region() #

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.

alloc_chrdev_region() #

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.

__register_chrdev() #

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.

unregister_chrdev_region() #

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...

__unregister_chrdev() #

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() did.

cdev_add() #

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() adds the device represented by p to the system, making it live immediately. A negative error code is returned on failure.

cdev_set_parent() #

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() 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.

cdev_device_add() #

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() 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.

cdev_device_del() #

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() 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.

cdev_del() #

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() 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.

cdev_alloc() #

struct cdev * cdev_alloc(void)

allocate a cdev structure

Parameters

  • void: no arguments

Description

Allocates and returns a cdev structure, or NULL on failure.

cdev_init() #

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().

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.

struct clk_notifier #

associate a clk with a notifier

Definition

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.

struct clk_notifier_data #

rate data to pass to the notifier callback

Definition

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).

struct clk_bulk_data #

Data used for bulk clk operations.

Definition

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.

clk_notifier_register() #

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.

clk_notifier_unregister() #

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

devm_clk_notifier_register() #

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

clk_get_accuracy() #

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.

clk_set_phase() #

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.

clk_get_phase() #

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.

clk_set_duty_cycle() #

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.

clk_get_scaled_duty_cycle() #

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.

clk_is_match() #

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.

clk_rate_exclusive_get() #

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.

devm_clk_rate_exclusive_get() #

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() on clk and registers a devm cleanup handler on dev to call clk_rate_exclusive_put().

Must not be called from within atomic context.

clk_rate_exclusive_put() #

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()

The caller must balance the number of clk_rate_exclusive_get() and clk_rate_exclusive_put() calls.

Must not be called from within atomic context.

clk_save_context() #

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.

clk_restore_context() #

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.

clk_prepare() #

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.

clk_unprepare() #

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.

clk_is_enabled_when_prepared() #

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() implicitly enables the clock, effectively making clk_enable()/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() or clk_prepare_enable() and counterparts for usage counts to be right.

clk_get() #

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() 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.

clk_bulk_get() #

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() 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.

clk_bulk_get_all() #

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.

clk_bulk_get_optional() #

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() 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.

devm_clk_bulk_get() #

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.

devm_clk_bulk_get_optional() #

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() 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() 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.

devm_clk_bulk_get_optional_enable() #

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() 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() condition containing errno.

devm_clk_bulk_get_all() #

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.

devm_clk_bulk_get_all_enabled() #

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.

devm_clk_get() #

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() 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.

devm_clk_get_prepared() #

struct clk * devm_clk_get_prepared(struct device *dev, const char *id)

devm_clk_get() + 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() 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.

devm_clk_get_enabled() #

struct clk * devm_clk_get_enabled(struct device *dev, const char *id)

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() 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.

devm_clk_get_optional() #

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() 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().

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.

devm_clk_get_optional_prepared() #

struct clk * devm_clk_get_optional_prepared(struct device *dev, const char *id)

devm_clk_get_optional() + 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() 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().

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.

devm_clk_get_optional_enabled() #

struct clk * devm_clk_get_optional_enabled(struct device *dev, const char *id)

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() 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().

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.

devm_clk_get_optional_enabled_with_rate() #

struct clk * devm_clk_get_optional_enabled_with_rate(struct device *dev, const char *id, unsigned long rate)

devm_clk_get_optional() + 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() 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().

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.

devm_get_clk_from_child() #

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.

clk_enable() #

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.

clk_bulk_enable() #

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.

clk_disable() #

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() calls must be balanced by the same number of clk_disable() calls for the clock source to be disabled.

clk_bulk_disable() #

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() calls must be balanced by the same number of clk_bulk_disable() calls for the clock source to be disabled.

clk_get_rate() #

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

clk_put() #

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.

clk_bulk_put() #

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.

clk_bulk_put_all() #

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.

devm_clk_put() #

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()

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.

clk_round_rate() #

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(), 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.

clk_set_rate() #

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.

clk_set_rate_exclusive() #

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() and clk_rate_exclusite_get(). Caller must balance this call with a call to clk_rate_exclusive_put()

Returns success (0) or negative errno.

clk_has_parent() #

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.

clk_set_rate_range() #

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.

clk_set_min_rate() #

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.

clk_set_max_rate() #

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.

clk_set_parent() #

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.

clk_get_parent() #

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() condition containing errno.

clk_get_sys() #

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() 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() 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.

clk_drop_range() #

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.

clk_get_optional() #

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() except where there is no clock producer. In this case, instead of returning -ENOENT, the function returns NULL.

Synchronization Primitives #

Read-Copy Update (RCU) #

same_state_synchronize_rcu() #

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(), start_poll_synchronize_rcu(), or 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.

rcu_trace_implies_rcu_gp() #

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!

cond_resched_tasks_rcu_qs() #

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.

rcu_softirq_qs_periodic() #

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() 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.

RCU_LOCKDEP_WARN() #

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() false positives") for more detail.

lockdep_assert_in_rcu_read_lock() #

lockdep_assert_in_rcu_read_lock()

WARN if not protected by rcu_read_lock()

Description

Splats if lockdep is enabled and there is no rcu_read_lock() in effect.

lockdep_assert_in_rcu_read_lock_bh() #

lockdep_assert_in_rcu_read_lock_bh()

WARN if not protected by rcu_read_lock_bh()

Description

Splats if lockdep is enabled and there is no rcu_read_lock_bh() in effect. Note that local_bh_disable() and friends do not suffice here, instead an actual rcu_read_lock_bh() is required.

lockdep_assert_in_rcu_read_lock_sched() #

lockdep_assert_in_rcu_read_lock_sched()

WARN if not protected by rcu_read_lock_sched()

Description

Splats if lockdep is enabled and there is no rcu_read_lock_sched() in effect. Note that preempt_disable() and friends do not suffice here, instead an actual rcu_read_lock_sched() is required.

lockdep_assert_in_rcu_reader() #

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.

unrcu_pointer() #

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.

RCU_INITIALIZER() #

RCU_INITIALIZER(v)

statically initialize an RCU-protected global variable

Parameters

  • v: The value to statically initialize with.

rcu_assign_pointer() #

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() instead of rcu_assign_pointer(). 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() when you should have used 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() comment header for details.

Note that 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() and the other macros that it invokes.

rcu_replace_pointer() #

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() call used to read that pointer. The old value of rcu_ptr is returned, and rcu_ptr is set to ptr.

rcu_access_pointer() #

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() 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() for this use case. Within an RCU read-side critical section, there is little reason to use rcu_access_pointer().

It is usually best to test the 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() return value to a local variable results in an accident waiting to happen.

It is also permissible to use 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() returns. This can be useful when tearing down multi-linked structures after a grace period has elapsed. However, rcu_dereference_protected() is normally preferred for this use case.

rcu_dereference_check() #

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(), 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()) 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() 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.

rcu_dereference_bh_check() #

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(). 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() and rcu_read_unlock(). This means that synchronize_rcu(), call_rcu, and friends all take not only rcu_read_lock() but also rcu_read_lock_bh() into account.

rcu_dereference_sched_check() #

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(). 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() and rcu_read_unlock(). This means that synchronize_rcu(), call_rcu, and friends all take not only rcu_read_lock() but also rcu_read_lock_sched() into account.

rcu_dereference_all_check() #

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(), 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() semantics prior to that version.

rcu_dereference_protected() #

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() will result in infrequent but very ugly failures.

rcu_dereference() #

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().

rcu_dereference_bh() #

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() do the dirty work.

rcu_dereference_sched() #

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() do the dirty work.

rcu_dereference_all() #

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() do the dirty work.

rcu_pointer_handoff() #

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:

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();

rcu_read_lock() #

void rcu_read_lock(void)

mark the beginning of an RCU read-side critical section

Parameters

  • void: no arguments

Description

When synchronize_rcu() is invoked on one CPU while other CPUs are within RCU read-side critical sections, then the synchronize_rcu() is guaranteed to block until after all the other CPUs exit their critical sections. Similarly, if 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() and 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() 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() (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() 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.

rcu_read_unlock() #

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() 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() is invoked with interrupts disabled.

See rcu_read_lock() for more information.

rcu_read_lock_bh() #

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(), 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() and rcu_read_lock_bh() were unrelated.

Note that rcu_read_lock_bh() and the matching rcu_read_unlock_bh() must occur in the same context, for example, it is illegal to invoke rcu_read_unlock_bh() from one task if the matching rcu_read_lock_bh() was invoked from some other task.

rcu_read_unlock_bh() #

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() for more information.

rcu_read_lock_sched() #

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(), 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() applies only to v5.0 and later. Before v5.0, rcu_read_lock() and rcu_read_lock_sched() were unrelated.

Note that rcu_read_lock_sched() and the matching rcu_read_unlock_sched() must occur in the same context, for example, it is illegal to invoke rcu_read_unlock_sched() from process context if the matching rcu_read_lock_sched() was invoked from an NMI handler.

rcu_read_unlock_sched() #

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() for more information.

RCU_INIT_POINTER() #

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() 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() 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() 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()!!!

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() to initialize the internal RCU-protected pointers, but you must use 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(), RCU_INIT_POINTER() provides no ordering guarantees for either the CPU or the compiler.

RCU_POINTER_INITIALIZER() #

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.

kfree_rcu() #

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() 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() function at module-unload time.

The 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() 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(), kmalloc_nolock(), or 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.

kfree_rcu_mightsleep() #

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().

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.

rcu_head_init() #

void rcu_head_init(struct rcu_head *rhp)

Initialize rcu_head for 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() to test whether a given rcu_head structure has already been passed to call_rcu(), then you must also invoke this rcu_head_init() function on it just after allocating that structure. Calls to this function must not race with calls to call_rcu(), rcu_head_after_call_rcu(), or callback invocation.

rcu_head_after_call_rcu() #

bool rcu_head_after_call_rcu(struct rcu_head *rhp, rcu_callback_t f)

Has this rcu_head been passed to call_rcu()?

Parameters

  • struct rcu_head *rhp: The rcu_head structure to test.
  • rcu_callback_t f: The function passed to call_rcu() along with rhp.

Description

Returns true if the rhp has been passed to 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() in an RCU read-side critical section that includes a read-side fetch of the pointer to the structure containing rhp.

rcu_softirq_qs() #

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() is equivalent to momentarily completely enabling preemption. For example, given this code:

local_bh_disable();
do_something();
rcu_softirq_qs();  // A
do_something_else();
local_bh_enable();  // B

A call to 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(), that same synchronize_rcu() would instead be guaranteed to wait until execution reached statement B.

rcu_watching_snap_stopped_since() #

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.

rcu_is_cpu_rrupt_from_idle() #

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.

rcu_irq_exit_check_preempt() #

void rcu_irq_exit_check_preempt(void)

Validate that scheduling is possible

Parameters

  • void: no arguments

__rcu_irq_enter_check_tick() #

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.

rcu_is_watching() #

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() 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() will return false.

Make notrace because it can be called by the internal functions of ftrace, and making this notrace removes unnecessary recursion calls.

rcu_set_gpwrap_lag() #

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.

call_rcu_hurry() #

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() 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()'s logic. Refer to call_rcu() for more details about memory ordering and other functionality.

call_rcu() #

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().

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() 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() and 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(). 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() 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() 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() 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() (as opposed to the other call_rcu*() functions), in kernels built with CONFIG_RCU_LAZY=y, 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().

synchronize_rcu() #

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(), the caller might well be executing concurrently with new RCU read-side critical sections that began while synchronize_rcu() was waiting.

RCU read-side critical sections are delimited by rcu_read_lock() and 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() 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(). In addition, each CPU having an RCU read-side critical section that extends beyond the return from synchronize_rcu() is guaranteed to have executed a full memory barrier after the beginning of 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(), 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() -- 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.

get_completed_synchronize_rcu_full() #

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() as a cookie whose grace period has already completed.

get_state_synchronize_rcu() #

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() or poll_state_synchronize_rcu() to determine whether or not a full grace period has elapsed in the meantime.

get_state_synchronize_rcu_full() #

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() or 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.

start_poll_synchronize_rcu() #

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() or 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.

start_poll_synchronize_rcu_full() #

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() or 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() or 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.

poll_state_synchronize_rcu() #

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() or 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() or cond_synchronize_rcu_expedited() on the one hand or by directly invoking either synchronize_rcu() or 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() 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() runs concurrently with 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() that was invoked at the call to the function that provided oldstate, and that returned at the end of this function.

poll_state_synchronize_rcu_full() #

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() or 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() or by directly invoking 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() to get a guaranteed-completed grace-period state.

This function provides the same memory-ordering guarantees that would be provided by a 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() is to cause a subsequent poll_state_synchronize_rcu_full() to return true, then the root rcu_node structure is the one that needs to be polled.

cond_synchronize_rcu() #

void cond_synchronize_rcu(unsigned long oldstate)

Conditionally wait for an RCU grace period

Parameters

  • unsigned long oldstate: value from get_state_synchronize_rcu(), start_poll_synchronize_rcu(), or start_poll_synchronize_rcu_expedited()

Description

If a full RCU grace period has elapsed since the earlier call to get_state_synchronize_rcu() or start_poll_synchronize_rcu(), just return. Otherwise, invoke 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() that was invoked at the call to the function that provided oldstate and that returned at the end of this function.

cond_synchronize_rcu_full() #

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(), start_poll_synchronize_rcu_full(), or start_poll_synchronize_rcu_expedited_full()

Description

If a full RCU grace period has elapsed since the call to get_state_synchronize_rcu_full(), start_poll_synchronize_rcu_full(), or start_poll_synchronize_rcu_expedited_full() from which rgosp was obtained, just return. Otherwise, invoke 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() that was invoked at the call to the function that provided rgosp and that returned at the end of this function.

rcu_barrier() #

void rcu_barrier(void)

Wait until all in-flight 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() is within its rights to return immediately, without waiting for anything, much less an RCU grace period. In fact, 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.

rcu_barrier_throttled() #

void rcu_barrier_throttled(void)

Do rcu_barrier(), but limit to one per second

Parameters

  • void: no arguments

Description

This can be thought of as guard rails around 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() 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() 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!

synchronize_rcu_expedited() #

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() 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() in a loop, please restructure your code to batch your updates, and then use a single synchronize_rcu() instead.

This has the same semantics as (but is more brutal than) synchronize_rcu().

start_poll_synchronize_rcu_expedited() #

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(), cond_synchronize_rcu_expedited(), or 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.

start_poll_synchronize_rcu_expedited_full() #

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() or 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.

cond_synchronize_rcu_expedited() #

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(), start_poll_synchronize_rcu(), or 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(), start_poll_synchronize_rcu(), or start_poll_synchronize_rcu_expedited(), just return. Otherwise, invoke 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() that was invoked at the call to the function that provided oldstate and that returned at the end of this function.

cond_synchronize_rcu_expedited_full() #

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(), start_poll_synchronize_rcu_full(), or start_poll_synchronize_rcu_expedited_full()

Description

If a full RCU grace period has elapsed since the call to get_state_synchronize_rcu_full(), start_poll_synchronize_rcu_full(), or start_poll_synchronize_rcu_expedited_full() from which rgosp was obtained, just return. Otherwise, invoke 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() that was invoked at the call to the function that provided rgosp and that returned at the end of this function.

rcu_read_lock_held_common() #

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() sets *ret to false even if the CPU did an 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.

rcu_async_hurry() #

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() will be processed in a timely fashion.

rcu_async_relax() #

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() will be processed in a lazy fashion.

rcu_expedite_gp() #

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() and friends act as the corresponding synchronize_rcu_expedited() function had instead been called.

rcu_unexpedite_gp() #

void rcu_unexpedite_gp(void)

Cancel prior rcu_expedite_gp() invocation

Parameters

  • void: no arguments

Description

Undo a prior call to rcu_expedite_gp(). If all prior calls to rcu_expedite_gp() are undone by a subsequent call to rcu_unexpedite_gp(), and if the rcu_expedited sysfs/boot parameter is not set, then all subsequent calls to synchronize_rcu() and friends will return to their normal non-expedited behavior.

rcu_read_lock_held() #

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() and the matching rcu_read_unlock() must occur in the same context, for example, it is illegal to invoke rcu_read_unlock() in process context if the matching rcu_read_lock() was invoked from within an irq handler.

Note that rcu_read_lock() is disallowed if the CPU is either idle or offline from an RCU perspective, so check for those as well.

rcu_read_lock_bh_held() #

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(), 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() is disallowed if the CPU is either idle or offline from an RCU perspective, so check for those as well.

wakeme_after_rcu() #

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.

init_rcu_head_on_stack() #

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.

destroy_rcu_head_on_stack() #

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(), 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(), this function has no effect for !CONFIG_DEBUG_OBJECTS_RCU_HEAD kernel builds.

get_completed_synchronize_rcu() #

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() as a cookie whose grace period has already completed.

get_completed_synchronize_srcu() #

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() will always treat as a cookie whose grace period has already completed.

same_state_synchronize_srcu() #

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(), start_poll_synchronize_srcu(), or 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.

srcu_read_lock_held() #

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.

srcu_dereference_check() #

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.

srcu_dereference() #

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() 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.

srcu_dereference_notrace() #

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.

srcu_read_lock() #

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() or synchronize_srcu_expedited().

The return value from srcu_read_lock() is guaranteed to be non-negative. This value must be passed unaltered to the matching srcu_read_unlock(). Note that srcu_read_lock() and the matching srcu_read_unlock() must occur in the same context, for example, it is illegal to invoke srcu_read_unlock() in an irq handler if the matching srcu_read_lock() was invoked in process context. Or, for that matter to invoke srcu_read_unlock() from one task and the matching srcu_read_lock() from another.

srcu_read_lock_fast() #

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() for more information. This function is NMI-safe, in a manner similar to srcu_read_lock_nmisafe().

For 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() 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(), IPIs and all. If you need expedited SRCU-fast grace periods, use synchronize_srcu_expedited().

The 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(). Otherwise, lockdep will complain.

srcu_read_lock_fast_updown() #

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() for more information. This function is compatible with srcu_down_read_fast(), but is not NMI-safe.

For 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() 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(), IPIs and all. If you need expedited SRCU-fast-updown grace periods, use synchronize_srcu_expedited().

The 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(). Otherwise, lockdep will complain.

srcu_down_read_fast() #

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() and srcu_down_read() for more information.

The same srcu_struct may be used concurrently by srcu_down_read_fast() and srcu_read_lock_fast(). However, the same definition/initialization requirements called out for srcu_read_lock_safe() apply.

srcu_read_lock_nmisafe() #

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() for more information.

If 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.

srcu_down_read() #

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() or synchronize_srcu_expedited(). But if you want lockdep to help you keep this stuff straight, you should instead use srcu_read_lock().

The semaphore-like nature of srcu_down_read() means that the matching 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() nor srcu_up_read() may be invoked from an NMI handler.

Calls to 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() and srcu_read_lock().

srcu_read_unlock() #

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().

Description

Exit an SRCU read-side critical section.

srcu_read_unlock_fast() #

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().

Description

Exit a light-weight SRCU read-side critical section.

srcu_read_unlock_fast_updown() #

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().

Description

Exit an SRCU-fast-updown read-side critical section.

srcu_up_read_fast() #

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().

Description

Exit an SRCU read-side critical section, but not necessarily from the same context as the maching srcu_down_read_fast().

srcu_read_unlock_nmisafe() #

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().

Description

Exit an SRCU read-side critical section, but in an NMI-safe manner.

srcu_up_read() #

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().

Description

Exit an SRCU read-side critical section, but not necessarily from the same context as the maching srcu_down_read().

smp_mb__after_srcu_read_unlock() #

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.

smp_mb__after_srcu_read_lock() #

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.

init_srcu_struct() #

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(), 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.

init_srcu_struct_fast() #

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() 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.

init_srcu_struct_fast_updown() #

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(), 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.

srcu_readers_active() #

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.

cleanup_srcu_struct() #

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(), else you leak memory.

call_srcu() #

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() was invoked. SRCU read-side critical sections are delimited by srcu_read_lock() and 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() for more detailed information on memory ordering guarantees.

synchronize_srcu_expedited() #

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() has the same deadlock and memory-ordering properties as does synchronize_srcu().

synchronize_srcu() #

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(), 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() from the corresponding SRCU read-side critical section; doing so will result in deadlock. However, it is perfectly legal to call 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(). On systems with more than one CPU, when 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(). In addition, each CPU having an SRCU read-side critical section that extends beyond the return from synchronize_srcu() is guaranteed to have executed a full memory barrier after the beginning of 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(), 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(). 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(), srcu_read_lock(), and srcu_read_unlock() are passed the same srcu_struct structure.

Implementation of these memory-ordering guarantees is similar to that of 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.

get_state_synchronize_srcu() #

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(), 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() after return from get_state_synchronize_srcu().

start_poll_synchronize_srcu() #

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(), which will return true if a full grace period has elapsed in the meantime. Unlike 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.

poll_state_synchronize_srcu() #

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() or start_poll_synchronize_srcu().

Description

This function takes the cookie that was returned from either get_state_synchronize_srcu() or 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.

srcu_barrier() #

void srcu_barrier(struct srcu_struct *ssp)

Wait until all in-flight call_srcu() callbacks complete.

Parameters

  • struct srcu_struct *ssp: srcu_struct on which to wait for in-flight callbacks.

srcu_expedite_current() #

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.

srcu_batches_completed() #

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.

hlist_bl_del_rcu() #

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() or 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().

hlist_bl_add_head_rcu() #

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() or 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(), 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().

hlist_bl_for_each_entry_rcu() #

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.

list_for_each_rcu() #

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.

list_tail_rcu() #

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() and similar primitives are not also used on the list header.

list_add_rcu() #

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() or 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().

list_add_tail_rcu() #

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() or 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().

list_del_rcu() #

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() 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() or 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().

Note that the caller is not permitted to immediately free the newly deleted entry. Instead, either synchronize_rcu() or call_rcu() must be used to defer freeing until an RCU grace period has elapsed.

list_bidir_del_rcu() #

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() doesn't poison the prev pointer thus allowing backwards traversal via list_bidir_prev_rcu().

Note

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() or 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().

Note that list_del_rcu() and 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() or call_rcu() must be used to defer freeing until an RCU grace period has elapsed.

hlist_del_init_rcu() #

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() or 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().

list_replace_rcu() #

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.

__list_splice_init_rcu() #

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() could be created. But only if -really- needed -- there is no shortage of RCU API members.

list_splice_init_rcu() #

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, ...

list_splice_tail_init_rcu() #

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, ...

list_entry_rcu() #

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() as long as it's guarded by rcu_read_lock().

list_first_or_null_rcu() #

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() as long as it's guarded by rcu_read_lock().

list_next_or_null_rcu() #

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() as long as it's guarded by rcu_read_lock().

list_for_each_entry_rcu() #

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() as long as the traversal is guarded by rcu_read_lock().

list_for_each_entry_srcu() #

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() as long as the traversal is guarded by srcu_read_lock(). The lockdep expression srcu_read_lock_held() can be passed as the cond argument from read side.

list_entry_lockless() #

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(), 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.

list_for_each_entry_lockless() #

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(), 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.

list_for_each_entry_continue_rcu() #

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() except this starts after the given position and that one starts at the given position.

list_for_each_entry_from_rcu() #

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() except this starts from the given position and that one starts from the position after the given position.

hlist_del_rcu() #

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() or 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().

hlist_replace_rcu() #

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.

hlists_swap_heads_rcu() #

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 ... ]

hlist_add_head_rcu() #

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() or 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(), 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().

hlist_add_tail_rcu() #

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() or 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(), 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().

hlist_add_before_rcu() #

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() or 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(), used to prevent memory-consistency problems on Alpha CPUs.

hlist_add_behind_rcu() #

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() or 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(), used to prevent memory-consistency problems on Alpha CPUs.

hlist_for_each_entry_rcu() #

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() as long as the traversal is guarded by rcu_read_lock().

hlist_for_each_entry_srcu() #

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() as long as the traversal is guarded by srcu_read_lock(). The lockdep expression srcu_read_lock_held() can be passed as the cond argument from read side.

hlist_for_each_entry_rcu_notrace() #

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() as long as the traversal is guarded by rcu_read_lock().

This is the same as hlist_for_each_entry_rcu() except that it does not do any RCU debugging or tracing.

hlist_for_each_entry_rcu_bh() #

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() as long as the traversal is guarded by rcu_read_lock().

hlist_for_each_entry_continue_rcu() #

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.

hlist_for_each_entry_continue_rcu_bh() #

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.

hlist_for_each_entry_from_rcu() #

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.

hlist_nulls_del_init_rcu() #

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() or 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().

hlist_nulls_first_rcu() #

hlist_nulls_first_rcu(head)

returns the first element of the hash list.

Parameters

  • head: the head of the list.

hlist_nulls_next_rcu() #

hlist_nulls_next_rcu(node)

returns the element of the list after node.

Parameters

  • node: element of the list.

hlist_nulls_pprev_rcu() #

hlist_nulls_pprev_rcu(node)

returns the dereferenced pprev of node.

Parameters

  • node: element of the list.

hlist_nulls_del_rcu() #

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() or 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().

hlist_nulls_add_head_rcu() #

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() or 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(), 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().

hlist_nulls_add_tail_rcu() #

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() or 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(), 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().

hlist_nulls_replace_rcu() #

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() or 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().

hlist_nulls_replace_init_rcu() #

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() or 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().

hlist_nulls_for_each_entry_rcu() #

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

hlist_nulls_for_each_entry_safe() #

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.

rcu_sync_is_idle() #

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.

rcu_sync_init() #

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

rcu_sync_func() #

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() function by rcu_sync_enter() and 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() it signals that all the readers were switched onto slow path.

If it is called by rcu_sync_exit() it takes action based on events that have taken place in the meantime, so that closely spaced rcu_sync_enter() and rcu_sync_exit() pairs need not wait for a grace period.

If another rcu_sync_enter() is invoked before the grace period ended, reset state to allow the next rcu_sync_exit() to let the readers back onto their fastpaths (after a grace period). If both another rcu_sync_enter() and its matching rcu_sync_exit() are invoked before the grace period ended, re-invoke call_rcu() on behalf of that rcu_sync_exit(). Otherwise, set all state back to idle so that readers can again use their fastpaths.

rcu_sync_enter() #

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() will return false, which tells readers to stay off their fastpaths. A later call to rcu_sync_exit() re-enables reader fastpaths.

When called in isolation, rcu_sync_enter() must wait for a grace period, however, closely spaced calls to rcu_sync_enter() can optimize away the grace-period wait via a state machine implemented by rcu_sync_enter(), rcu_sync_exit(), and rcu_sync_func().

rcu_sync_exit() #

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() will return true, which tells readers that they can once again use their fastpaths.

rcu_sync_dtor() #

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

struct rcu_tasks_percpu #

Per-CPU component of definition for a Tasks-RCU-like mechanism.

Definition

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.

struct rcu_tasks #

Definition for a Tasks-RCU-like mechanism.

Definition

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()-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.

call_rcu_tasks() #

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() assumes that the read-side critical sections end at a voluntary context switch (not a preemption!), 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() and 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() for more detailed information on memory ordering guarantees.

synchronize_rcu_tasks() #

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(), idle execution, userspace execution, calls to 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() function is not (yet) intended for heavy use from multiple CPUs.

See the description of synchronize_rcu() for more detailed information on memory ordering guarantees.

rcu_barrier_tasks() #

void rcu_barrier_tasks(void)

Wait for in-flight 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.

synchronize_rcu_tasks_rude() #

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(), 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() function is not (yet) intended for heavy use from multiple CPUs.

See the description of synchronize_rcu() for more detailed information on memory ordering guarantees.

rcu_cpu_stall_reset() #

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.

rcu_stall_chain_notifier_register() #

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.

rcu_stall_chain_notifier_unregister() #

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.

rcu_read_lock_tasks_trace() #

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() 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(). 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.

rcu_read_unlock_tasks_trace() #

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().

Description

Pairs with the preceding call to rcu_read_lock_tasks_trace() that returned the value passed in via scp.

For more details, please see the documentation for rcu_read_unlock(). For memory-ordering information, please see the header comment for the rcu_read_lock_tasks_trace() function.

rcu_read_lock_trace() #

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() 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().

rcu_read_unlock_trace() #

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(), and nesting is allowed. Invoking a rcu_read_unlock_trace() when there is no matching rcu_read_lock_trace() is verboten, and will result in lockdep complaints.

For more details, please see the documentation for rcu_read_unlock().

call_rcu_tasks_trace() #

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() and rcu_read_unlock_trace().

See the description of call_rcu() for more detailed information on memory ordering guarantees.

synchronize_rcu_tasks_trace() #

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() and 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() function is not (yet) intended for heavy use from multiple CPUs.

See the description of synchronize_rcu() for more detailed information on memory ordering guarantees.

rcu_barrier_tasks_trace() #

void rcu_barrier_tasks_trace(void)

Wait for in-flight call_rcu_tasks_trace() callbacks.

Parameters

  • void: no arguments

Description

Note that rcu_barrier_tasks_trace() is not obligated to actually wait, for example, if there are no pending callbacks.

rcu_tasks_trace_expedite_current() #

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.

synchronize_rcu_mult() #

synchronize_rcu_mult(...)

Wait concurrently for multiple grace periods

Parameters

  • ...: List of 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() function, with this wrapper supplying the pointer to the corresponding srcu_struct.

Note that call_rcu_hurry() should be used instead of call_rcu() because in kernels built with CONFIG_RCU_LAZY=y the delay between the invocation of 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() can be called is automatically already a full grace period.

rcuref_init() #

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'

rcuref_read() #

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()) please use rcuread_is_dead().

rcuref_is_dead() #

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() returned true on this reference counter meaning the protected object can safely be scheduled for deconstruction. Otherwise, returns false.

rcuref_get() #

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() 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

rcuref_put_rcusafe() #

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()'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.

rcuref_put() #

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.

same_state_synchronize_rcu_full() #

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(), start_poll_synchronize_rcu_full(), or 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

Author: Greg Kroah-Hartman <gregkh@linuxfoundation.org>

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/

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.

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:

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>:

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:

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:

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:

struct uio_map *map = to_map(kobj);

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():

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:

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->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():

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():

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():

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.

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():

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.

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:

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 in the Linux kernel source tree.

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:

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:

int sysfs_create_file(struct kobject *kobj, const struct attribute *attr);

or:

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.

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:

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:

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.

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:

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:

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:

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.

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.

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

Author: Corey Minyard <minyard@acm.org>

Author: Thomas Hellström <thomas.hellstrom@linux.intel.com>

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_talk/

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:

struct my_data
{
    .
    .
    struct kref refcount;
    .
    .
};

The kref can occur anywhere within the data structure.

Initialization #

You must initialize the kref after you allocate it. To do this, call kref_init as so:

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.

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:

    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():

    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:

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:

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:

/* 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:

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:

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:

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:

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.

Krefs and RCU #

The function kref_get_unless_zero also makes it possible to use rcu locking for lookups in the above example:

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.

Functions and structures #

kref_init() #

void kref_init(struct kref *kref)

initialize object.

Parameters

  • struct kref *kref: object in question.

kref_get() #

void kref_get(struct kref *kref)

increment refcount for object.

Parameters

  • struct kref *kref: object.

kref_put() #

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() 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.

kref_put_mutex() #

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.

kref_put_lock() #

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.

kref_get_unless_zero() #

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

Author: Thomas Gleixner

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.

Known Bugs And Assumptions #

None.

Usage #

This chapter provides examples of how to use the library.

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.

/* 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);

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.

/* 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);

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.

Decoding with syndrome calculation, direct data correction #

/* 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);

Decoding with syndrome given by hardware decoder, direct data correction #

/* 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);

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.

/* 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]);
}

Cleanup #

The function free_rs frees the allocated resources, if the caller is the last user of the decoder.

/* Release resources */
free_rs(rs_decoder);

Structures #

This chapter contains the autogenerated documentation of the structures which are used in the Reed-Solomon Library and are relevant for a developer.

struct rs_codec #

rs codec data

Definition

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

struct rs_control #

rs control structure per instance

Definition

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()

init_rs() #

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.

Public Functions Provided #

This chapter contains the autogenerated documentation of the Reed-Solomon functions which are exported.

free_rs() #

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.

init_rs_gfp() #

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.

init_rs_non_canonical() #

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)

encode_rs8() #

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.

decode_rs8() #

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.

encode_rs16() #

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.

decode_rs16() #

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.

Credits #

The library code for encoding and decoding was written by Phil Karn.

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 Gleixnertglx@kernel.org

Linked Lists in Linux

Peios Kernel / Internals / Core APIs

Author: Nicolas Frattaroli <nicolas.frattaroli@collabora.com>

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.

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.

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:

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.

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:

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.

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:

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:

     .------.
     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:

     .--------------------.
     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:

     .------------------------------------.
     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:

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:

     .------------------------------------.
     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.

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:

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:

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.

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:

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:

     .--------------------.
     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:

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:

     .--------------------.           .-------.
     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.

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:

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.

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:

     .----------------------------------------------------------------.
     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:

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:

     .----------------------.
     v                      |
.--------.     .---------.  |
| clowns |---->| Alfredo |--'
'--------'     '---------'

Meanwhile, the retirement list is transformed to the following:

       .--------------------------------------------------.
       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:

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:

     .----------------------------------.
     v                                  |
.--------.     .-----.     .---------.  |
| clowns |---->| Pic |---->| Alfredo |--'
'--------'     '-----'     '---------'

Meanwhile, the retirement list is transformed to the following:

       .--------------------------------------.
       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.

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":

     .----------------------------------------------------------------.
     v                                                                |
.--------.     .-------.     .---------.     .-----.     .---------.  |
| clowns |---->| Grock |---->| Dimitri |---->| Pic |---->| Alfredo |--'
'--------'     '-------'     '---------'     '-----'     '---------'

      .-------------------.
      v                   |
.----------.     .-----.  |
| sidewalk |---->| Pio |--'
'----------'     '-----'

We apply the following example code to the two lists:

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:

    .-----------------------------------------------------.
    |                                                     |
    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:

    .-------------------------------------.
    |                                     |
    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.

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:

      .-----------------------------------------------.
      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.

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:

     .-----------------------------------------------------------------.
     v                                                                 |
.--------.   .-------.   .---------.   .-----.   .---------.   .-----. |
| clowns |-->| Grock |-->| Dimitri |-->| Pic |-->| Alfredo |-->| Pio |-'
'--------'   '-------'   '---------'   '-----'   '---------'   '-----'

The example code being used to demonstrate list rotations is the following:

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:

     .-----------------------------------------------------------------.
     v                                                                 |
.--------.   .---------.   .-----.   .---------.   .-----.   .-------. |
| clowns |-->| Dimitri |-->| Pic |-->| Alfredo |-->| Pio |-->| Grock |-'
'--------'   '---------'   '-----'   '---------'   '-----'   '-------'

Next, after the list_rotate_to_front() call, we arrive in the following State 2:

     .-----------------------------------------------------------------.
     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.

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":

     .-----------------------------------------.
     v                                         |
.--------.   .-------.   .---------.   .-----. |
| clowns |-->| Grock |-->| Dimitri |-->| Pic |-'
'--------'   '-------'   '---------'   '-----'
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:

     .-----------------------------------------.
     v                                         |
.--------.   .-------.   .-----.   .---------. |
| clowns |-->| Grock |-->| Pic |-->| Dimitri |-'
'--------'   '-------'   '-----'   '---------'

As is evident by comparing the diagrams, the "Pic" and "Dimitri" nodes have traded places.

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":

    .-----------------------------------------.
    |                                         |
    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:

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:

    .-----------------------------------------------------------------.
    |                                                                 |
    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.

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 for more details.

Further reading #

  • How does the kernel implements Linked Lists? - KernelNewbies

Full List API #

LIST_HEAD_INIT() #

LIST_HEAD_INIT(name)

initialize a struct list_head's links to point to itself

Parameters

  • name: name of the list_head

LIST_HEAD() #

LIST_HEAD(name)

definition of a struct list_head with initialization values

Parameters

  • name: name of the list_head

INIT_LIST_HEAD() #

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.

list_add() #

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.

list_add_tail() #

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.

list_del() #

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() on entry does not return true after this, the entry is in an undefined state.

list_replace() #

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.

list_replace_init() #

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.

list_swap() #

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

list_del_init() #

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.

list_move() #

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

list_move_tail() #

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

list_bulk_move_tail() #

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.

list_is_first() #

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

list_is_last() #

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

list_is_head() #

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

list_empty() #

int list_empty(const struct list_head *head)

tests whether a list is empty

Parameters

  • const struct list_head *head: the list to test.

list_del_init_careful() #

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(), except designed to be used together with list_empty_careful() in a way to guarantee ordering of other memory operations.

Any memory operations done before a list_del_init_careful() are guaranteed to be visible after a list_empty_careful() test.

list_empty_careful() #

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() without synchronization can only be safe if the only activity that can happen to the list entry is list_del_init(). Eg. it cannot be used if another CPU could re-list_add() it.

list_rotate_left() #

void list_rotate_left(struct list_head *head)

rotate the list to the left

Parameters

  • struct list_head *head: the head of the list

list_rotate_to_front() #

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.

list_is_singular() #

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.

list_cut_position() #

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.

list_cut_before() #

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.

list_splice() #

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.

list_splice_tail() #

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.

list_splice_init() #

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

list_splice_tail_init() #

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

list_entry() #

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.

list_first_entry() #

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.

list_last_entry() #

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.

list_first_entry_or_null() #

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.

list_last_entry_or_null() #

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.

list_next_entry() #

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.

list_next_entry_circular() #

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.

list_prev_entry() #

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.

list_prev_entry_circular() #

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.

list_for_each() #

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.

list_for_each_continue() #

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.

list_for_each_prev() #

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.

list_for_each_safe() #

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.

list_for_each_prev_safe() #

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.

list_count_nodes() #

size_t list_count_nodes(struct list_head *head)

count nodes in the list

Parameters

  • struct list_head *head: the head for your list.

list_entry_is_head() #

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.

list_for_each_entry() #

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.

list_for_each_entry_reverse() #

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.

list_prepare_entry() #

list_prepare_entry(pos, head, member)

prepare a pos entry for use in 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().

list_for_each_entry_continue() #

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.

list_for_each_entry_continue_reverse() #

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.

list_for_each_entry_from() #

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.

list_for_each_entry_from_reverse() #

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.

list_for_each_entry_safe() #

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.

list_for_each_entry_safe_continue() #

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.

list_for_each_entry_safe_from() #

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.

list_for_each_entry_safe_reverse() #

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.

list_safe_reset_next() #

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.

hlist_unhashed() #

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() does leave the node in unhashed state, but hlist_nulls_del() does not.

hlist_unhashed_lockless() #

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() 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.

hlist_empty() #

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.

hlist_del() #

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() or similar instead to unhash n.

hlist_del_init() #

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.

hlist_add_head() #

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.

hlist_add_before() #

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

hlist_add_behind() #

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

hlist_add_fake() #

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() to work correctly in cases where there is no list.

hlist_fake() #

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.

hlist_is_singular_node() #

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.

hlist_move_list() #

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.

hlist_splice_init() #

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.

hlist_for_each_entry() #

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.

hlist_for_each_entry_continue() #

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.

hlist_for_each_entry_from() #

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.

hlist_for_each_entry_safe() #

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.

hlist_count_nodes() #

size_t hlist_count_nodes(struct hlist_head *head)

count nodes in the hlist

Parameters

  • struct hlist_head *head: the head for your hlist.

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.

list_private_entry() #

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.

list_private_first_entry() #

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.

list_private_last_entry() #

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.

list_private_next_entry() #

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.

list_private_next_entry_circular() #

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.

list_private_prev_entry() #

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.

list_private_prev_entry_circular() #

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.

list_private_entry_is_head() #

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.

list_private_for_each_entry() #

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.

list_private_for_each_entry_reverse() #

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.

list_private_for_each_entry_continue() #

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.

list_private_for_each_entry_continue_reverse() #

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.

list_private_for_each_entry_from() #

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.

list_private_for_each_entry_from_reverse() #

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.

list_private_for_each_entry_safe() #

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.

list_private_for_each_entry_safe_continue() #

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.

list_private_for_each_entry_safe_from() #

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.

list_private_for_each_entry_safe_reverse() #

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.

list_private_safe_reset_next() #

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

Author: Pasha Tatashin <pasha.tatashin@soleen.com>

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.

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.

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. 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() finds a compatible handler, calls its .preserve() operation, and creates an internal struct luo_file to track the live state.

  2. Freeze (Pre-Reboot): Just before the kexec, 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() 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 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() 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() 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(). 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() 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.

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().

Callback Model: Each FLB is defined by a set of operations (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.

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:
/ {
    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

Public API #

struct liveupdate_file_op_args #

Arguments for file operation callbacks.

Definition

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.

struct liveupdate_file_ops #

Callbacks for live-updatable files.

Definition

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.

struct liveupdate_file_handler #

Represents a handler for a live-updatable file type.

Definition

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 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.

struct liveupdate_flb_op_args #

Arguments for FLB operation callbacks.

Definition

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.

struct liveupdate_flb_ops #

Callbacks for global File-Lifecycle-Bound data.

Definition

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.

struct liveupdate_flb #

A global definition for a shared data object.

Definition

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 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.

struct luo_file_ser #

Represents the serialized preserves files.

Definition

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.

struct luo_file_set_ser #

Represents the serialized metadata for file set

Definition

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.

struct luo_session_header_ser #

Header for the serialized session data block.

Definition

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.

struct luo_session_ser #

Represents the serialized metadata for a LUO session.

Definition

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.

struct luo_flb_header_ser #

Header for the serialized FLB data block.

Definition

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 entries.
  • count: The number of 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.

struct luo_flb_ser #

Represents the serialized state of a single FLB object.

Definition

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 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.

Internal API #

liveupdate_reboot() #

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.

liveupdate_enabled() #

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.

luo_flb_file_preserve() #

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()

Return

0 on success, or a negative errno on failure.

luo_flb_file_unpreserve() #

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()).

luo_flb_file_finish() #

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() for each file being finished.

liveupdate_register_flb() #

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.

liveupdate_unregister_flb() #

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().

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.

liveupdate_flb_get_incoming() #

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.

liveupdate_flb_get_outgoing() #

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.

luo_flb_serialize() #

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() just before kho_finalize().

struct luo_session_header #

Header struct for managing LUO sessions.

Definition

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.

struct luo_session_global #

Global container for managing LUO sessions.

Definition

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.

luo_session_quiesce() #

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.

luo_session_resume() #

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().

struct luo_file #

Represents a single preserved file instance.

Definition

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 that manages this type of file.
  • file: Pointer to the kernel's 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() 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() and are finally cleaned up by luo_file_finish().

luo_preserve_file() #

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().

luo_file_unpreserve_files() #

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() 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.

luo_file_freeze() #

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() path.

Return

0 on success, or a negative errno on failure.

luo_file_unfreeze() #

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().

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() has been called.

luo_retrieve_file() #

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.

luo_file_finish() #

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().
  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.

luo_file_deserialize() #

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() to restore the actual file descriptors.

Context

Called from session deserialization.

liveupdate_register_file_handler() #

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. 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.

liveupdate_unregister_file_handler() #

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().

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.

See Also #

  • Live Update uAPI

  • Kexec Handover Subsystem

Semantics and Behavior of Local Atomic Operations

Peios Kernel / Internals / Core APIs

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.

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.

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:

typedef struct { atomic_long_t a; } local_t;

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.

How to use local atomic operations #

#include <linux/percpu.h>
#include <asm/local.h>

static DEFINE_PER_CPU(local_t, counters) = LOCAL_INIT(0);

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:

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:

local_inc(this_cpu_ptr(&counters));

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:

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:

/* 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

Author: Liam R. Howlett

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 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, 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. 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.

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 section.

Sometimes it is necessary to ensure the next call to store to a maple tree does not allocate memory, please see 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.

Allocating Nodes #

The allocations are handled by the internal tree code. See Advanced Allocating Nodes for other options.

Locking #

You do not have to worry about locking. See Advanced Locking 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.

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 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. Please see above.

The maple state keeps track of the range start and end in mas->index and mas->last, respectively.

mas_walk() will walk the tree to the location of mas->index and set the mas->index and mas->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.

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.

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.

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

MTREE_INIT() #

MTREE_INIT(name, __flags)

Initialize a maple tree

Parameters

  • name: The maple tree name
  • __flags: The maple tree flags

MTREE_INIT_EXT() #

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

mtree_empty() #

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.

mas_reset() #

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.

mas_for_each() #

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.

mas_for_each_rev() #

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.

__mas_set_range() #

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() if you do not know where you are in the tree.

mas_set_range() #

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() to move to an adjacent index.

mas_set() #

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() to move to an adjacent index.

mt_init_flags() #

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.

mt_init() #

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.

mt_clear_in_rcu() #

void mt_clear_in_rcu(struct maple_tree *mt)

Switch the tree to non-RCU mode.

Parameters

  • struct maple_tree *mt: The Maple Tree

mt_set_in_rcu() #

void mt_set_in_rcu(struct maple_tree *mt)

Switch the tree to RCU safe mode.

Parameters

  • struct maple_tree *mt: The Maple Tree

mt_for_each() #

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.

mas_prealloc_calc() #

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.

mas_wr_preallocate() #

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

mas_insert() #

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.

mas_alloc_cyclic() #

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.

mas_walk() #

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.

mte_dead_walk() #

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.

mt_free_walk() #

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.

mas_store() #

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.

mas_store_gfp() #

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.

mas_store_prealloc() #

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.

mas_preallocate() #

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.

mas_next() #

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

mas_next_range() #

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

mt_next() #

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.

mas_prev() #

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.

mas_prev_range() #

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.

mt_prev() #

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.

mas_pause() #

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(), the mt_for_each() iterator may be more appropriate.

mas_find_setup() #

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.

mas_find() #

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.

mas_find_range() #

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.

mas_find_rev_setup() #

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.

mas_find_rev() #

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.

mas_find_range_rev() #

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.

mas_erase() #

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.

mas_nomem() #

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.

mtree_load() #

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

mtree_store_range() #

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.

mtree_store() #

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.

mtree_insert_range() #

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.

mtree_insert() #

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.

mtree_alloc_cyclic() #

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.

mtree_erase() #

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

__mt_dup() #

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() 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.

mtree_dup() #

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() 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.

__mt_destroy() #

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.

mtree_destroy() #

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.

mt_find() #

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

mt_find_after() #

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() 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 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

kzalloc(<size>, GFP_KERNEL);

Of course there are cases when other allocation APIs and different GFP flags must be used.

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 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.

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.

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.

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

Memory hotplug event notifier #

Hotplugging events are sent to a notification queue.

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:

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:

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:

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.

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:

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:

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:

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.

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

Author: Kuan-Wei Chiu <visitorckw@gmail.com>

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.

Data Structures #

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:

#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.

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:

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

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.

Heap Initialization #

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)

Accessing the Top Element #

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)

Heap Insertion #

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)

Heap Removal #

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)

Heap Maintenance #

You can use the following macros to maintain the heap's structure:

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)

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)

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)

Removing Specific Elements #

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)

Other Utilities #

  • min_heap_full(heap): Checks whether the heap is full. Complexity: O(1).
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).
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)

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.

#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

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 and the VFS callback reference for the Peios integration contracts.

User Space Memory Access #

get_user() #

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.

__get_user() #

__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.

put_user() #

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.

__put_user() #

__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.

clear_user() #

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.

__clear_user() #

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.

get_user_pages_fast() #

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.

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() 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.

The Slab Cache #

SLAB_HWCACHE_ALIGN #

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 field, the greater of both is alignments is applied.

SLAB_TYPESAFE_BY_RCU #

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() 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:

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() 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() 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() protection.

Note that SLAB_TYPESAFE_BY_RCU was originally named SLAB_DESTROY_BY_RCU.

SLAB_ACCOUNT #

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.

SLAB_RECLAIM_ACCOUNT #

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

struct kmem_cache_args #

Less common arguments for kmem_cache_create()

Definition

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 or ctor

    By default, 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, the caller must ensure that the free pointer does not overlay fields required to guard against object recycling (See 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 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() 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(), it is equivalent to all fields unused.

kmem_cache_create_usercopy() #

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() with the necessary parameters passed via the args parameter (see struct kmem_cache_args)

Return

a pointer to the cache on success, NULL on failure.

kmem_cache_create() #

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. 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() 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

Context

Cannot be called within a interrupt, but can be interrupted.

Return

a pointer to the cache on success, NULL on failure.

kmem_cache_alloc() #

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().

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

kmem_cache_charge() #

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() without __GFP_ACCOUNT
  4. Allocating internal metadata has failed

Return

true if charge was successful otherwise false.

kmalloc() #

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().

  • __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.

__alloc_objs() #

__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.

__alloc_flex() #

__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()).

kmalloc_obj() #

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.

kmalloc_objs() #

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.

kmalloc_flex() #

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.

kmalloc_array() #

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).

krealloc_array() #

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.

kcalloc() #

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).

kzalloc() #

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).

kmalloc_size_roundup() #

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() 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()-based allocations, and is not for the pre-sized kmem_cache_alloc()-based allocations.)

Use this to kmalloc() the full bucket size ahead of time instead of using ksize() to query the size after an allocation.

kmem_cache_alloc_node() #

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().
  • 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

kmalloc_nolock() #

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.

kmem_cache_free() #

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.

ksize() #

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(). 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

kfree() #

void kfree(const void *object)

free previously allocated memory

Parameters

  • const void *object: pointer returned by kmalloc(), kmalloc_nolock(), or kmem_cache_alloc()

Description

If object is NULL, no operation is performed.

krealloc_node_align() #

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(). 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() 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:

        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

__kvmalloc_node() #

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() 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

kvfree() #

void kvfree(const void *addr)

Free memory.

Parameters

  • const void *addr: Pointer to allocated memory.

Description

kvfree frees memory allocated by any of vmalloc(), kmalloc() or kvmalloc(). It is slightly more efficient to use kfree() or vfree() if you are certain that you know which one to use.

Context

Either preemptible task context or not-NMI interrupt.

kvfree_sensitive() #

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() 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.

kvrealloc_node_align() #

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() 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() for the same memory allocation.

Return

pointer to the allocated memory or NULL in case of error

__kmem_cache_create_args() #

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).
  • 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() wrapper with the same parameters.

Commonly used flags:

SLAB_ACCOUNT - Account allocations to memcg.

SLAB_HWCACHE_ALIGN - Align objects on cache line boundaries.

SLAB_RECLAIM_ACCOUNT - Objects are reclaimable.

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.

kmem_buckets_create() #

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() 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(). (i.e. callers only need to check for NULL on failure.)

kmem_cache_shrink() #

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

kmem_dump_obj() #

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(), 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() or kmem_cache_alloc(), either true or false if the pointer is to an already-freed object, and false otherwise.

kfree_sensitive() #

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() 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(). So be careful when using this function in performance sensitive code.

kvfree_rcu_barrier() #

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() 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() 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().

kvfree_rcu_barrier_on_cache() #

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() for details.

kfree_const() #

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.

Virtually Contiguous Mappings #

vm_unmap_aliases() #

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.

vm_unmap_ram() #

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)

vm_map_ram() #

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(), 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

vfree() #

void vfree(const void *addr)

Release memory allocated by 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() 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() arch-dependent would be a really bad idea).

vunmap() #

void vunmap(const void *addr)

release virtual mapping obtained by 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().

Must not be called in interrupt context.

vmap() #

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(), and will be freed / dropped when vfree() is called on the return value.

Return

the address of the area or NULL on failure

vmap_pfn() #

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.

__vmalloc_node() #

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

vmalloc() #

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

vmalloc_huge_node() #

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

vzalloc() #

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

vmalloc_user() #

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

vmalloc_node() #

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

vzalloc_node() #

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

vrealloc_node_align() #

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() for the same memory allocation.

Return

pointer to the allocated memory; NULL if size is zero or in case of failure

vmalloc_32() #

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

vmalloc_32_user() #

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

remap_vmalloc_range() #

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() (see mm/memory.c)

File Mapping and Page Cache #

Filemap #

filemap_fdatawrite_range() #

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.

filemap_flush_range() #

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.

filemap_flush() #

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.

filemap_range_has_page() #

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.

filemap_fdatawait_range() #

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.

filemap_fdatawait_range_keep_errors() #

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(), 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)

file_fdatawait_range() #

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.

filemap_fdatawait_keep_errors() #

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.

filemap_write_and_wait_range() #

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.

file_check_and_advance_wb_err() #

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.

file_write_and_wait_range() #

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.

replace_page_cache_folio() #

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.

folio_unlock() #

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.

folio_end_read() #

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.

folio_end_private_2() #

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.

folio_wait_private_2() #

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.

folio_wait_private_2_killable() #

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.

folio_end_writeback_no_dropbehind() #

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.

folio_end_writeback() #

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.

__folio_lock() #

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

page_cache_next_miss() #

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.

page_cache_prev_miss() #

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() 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.

__filemap_get_folio_mpol() #

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() otherwise.

filemap_get_folios() #

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.

filemap_get_folios_contig() #

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() works exactly like 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.

filemap_get_folios_tag() #

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.

filemap_read() #

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.

generic_file_read_iter() #

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

filemap_splice_read() #

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.

filemap_fault() #

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() 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.

read_cache_folio() #

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() on failure.

mapping_read_folio_gfp() #

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() on failure.

read_cache_page_gfp() #

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() on failure.

__generic_file_write_iter() #

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

generic_file_write_iter() #

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() 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() failed for a synchronous write
  • number of bytes written, even for truncated writes

filemap_release_folio() #

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.

filemap_invalidate_inode() #

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.

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() 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() repeatedly to get each folio from those prepared for readahead. It may fail to read a folio by:

  • not calling 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(). 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.

page_cache_ra_unbounded() #

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() or 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.

readahead_expand() #

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.

Writeback #

balance_dirty_pages_ratelimited_flags() #

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() 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.

balance_dirty_pages_ratelimited() #

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.

tag_pages_for_writeback() #

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).

writeback_iter() #

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() 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() until it returns NULL.

Return

the folio to write or NULL if the loop is done.

filemap_dirty_folio() #

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() 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.

folio_redirty_for_writepage() #

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.

folio_mark_dirty() #

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.

folio_wait_writeback() #

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.

folio_wait_writeback_killable() #

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.

folio_wait_stable() #

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.

Truncate #

folio_invalidate() #

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() is called when all or part of the folio has become invalidated by a truncate operation.

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.

truncate_inode_pages_range() #

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.

truncate_inode_pages() #

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.

truncate_inode_pages_final() #

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.

invalidate_mapping_pages() #

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().

Return

The number of indices that had their contents invalidated

invalidate_inode_pages2_range() #

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.

invalidate_inode_pages2() #

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.

truncate_pagecache() #

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.

truncate_setsize() #

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.

pagecache_isize_extended() #

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.

truncate_pagecache_range() #

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.

filemap_set_wb_err() #

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.

filemap_check_wb_err() #

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.

filemap_sample_wb_err() #

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.

file_sample_sb_err() #

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.

mapping_set_error() #

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).

mapping_set_large_folios() #

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.

mapping_align_index() #

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.

folio_flush_mapping() #

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() or folio_file_mapping().

folio_inode() #

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.

folio_attach_private() #

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.

folio_change_private() #

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.

folio_detach_private() #

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.

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() and 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.

fgf_set_order() #

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.

write_begin_get_folio() #

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.

filemap_get_folio() #

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.

filemap_lock_folio() #

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.

filemap_grab_folio() #

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.

find_get_page() #

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.

find_lock_page() #

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.

find_or_create_page() #

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() may sleep, even if gfp_flags specifies an atomic allocation!

grab_cache_page_nowait() #

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.

folio_next_index() #

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.

folio_next_pos() #

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.

folio_file_page() #

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.

folio_contains() #

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.

page_pgoff() #

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.

folio_pos() #

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.

folio_trylock() #

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() is the correct function to call.

Context

Any context.

Return

Whether the lock was successfully acquired.

folio_lock() #

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.

lock_page() #

void lock_page(struct page *page)

Lock the folio containing this page.

Parameters

  • struct page *page: The page to lock.

Description

See folio_lock() for a description of what the lock protects. This is a legacy function and new code should probably use 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.

folio_lock_killable() #

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(), except that the sleep to acquire the lock is interruptible by a fatal signal.

Context

May sleep; see folio_lock().

Return

0 if the lock was acquired; -EINTR if a fatal signal was received.

filemap_range_needs_writeback() #

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() before proceeding.

Return

true if the caller should do filemap_write_and_wait_range() before doing O_DIRECT to a page in this range, false otherwise.

struct readahead_control #

Describes a readahead request.

Definition

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() 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.

page_cache_sync_readahead() #

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() 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.

page_cache_async_readahead() #

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() 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.

readahead_folio() #

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.

readahead_pos() #

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.

readahead_length() #

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.

readahead_index() #

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.

readahead_count() #

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.

readahead_batch_length() #

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.

folio_mkwrite_check_truncate() #

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.

i_blocks_per_folio() #

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.

Memory pools #

mempool_exit() #

void mempool_exit(struct mempool *pool)

exit a mempool initialized with mempool_init()

Parameters

  • struct mempool *pool: pointer to the memory pool which was initialized with 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()).

mempool_destroy() #

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.

mempool_init() #

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.

mempool_create_node() #

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() and mempool_free() functions. This function might sleep. Both the alloc_fn() and the free_fn() functions might sleep - as long as the mempool_alloc() function is not called from IRQ contexts.

Return

pointer to the created memory pool object or NULL on error.

mempool_resize() #

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() 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() & mempool_free() might be called (eg. from IRQ contexts) while this function executes.

Return

0 on success, negative error code otherwise.

mempool_alloc_bulk() #

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.

mempool_alloc() #

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.

mempool_alloc_preallocated() #

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(), 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.

mempool_free_bulk() #

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.

mempool_free() #

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.

More Memory Management Functions #

zap_vma_ptes() #

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.

vm_insert_pages() #

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() 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().

vm_insert_page() #

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()" 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.

vm_map_pages() #

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.

vm_map_pages_zero() #

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(), 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.

vmf_insert_pfn_prot() #

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(), 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.

vmf_insert_pfn() #

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.

remap_pfn_range() #

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.

vm_iomap_memory() #

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.

unmap_mapping_pages() #

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.

unmap_mapping_range() #

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(), 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.

follow_pfnmap_start() #

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() 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.

follow_pfnmap_end() #

void follow_pfnmap_end(struct follow_pfnmap_args *args)

End a 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(). See the start() function above for more information.

generic_access_phys() #

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.

copy_remote_vm_str() #

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.

__get_pfnblock_flags_mask() #

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

get_pfnblock_bit() #

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

get_pfnblock_migratetype() #

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() if caller already has both page and pfn to save a call to page_to_pfn().

__set_pfnblock_flags_mask() #

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

set_pfnblock_bit() #

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

clear_pfnblock_bit() #

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

set_pageblock_migratetype() #

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

__move_freepages_block_isolate() #

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.

__putback_isolated_page() #

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.

__free_pages() #

void __free_pages(struct page *page, unsigned int order)

Free pages allocated with alloc_pages().

Parameters

  • struct page *page: The page pointer returned from 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().

Context

May be called in interrupt context or while holding a normal spinlock, but not in NMI context or while holding a raw spinlock.

free_pages() #

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(). Use this function to free pages when you only have a valid virtual address. If you have the page, call __free_pages() instead.

alloc_pages_exact() #

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(), except that it allocates the minimum number of pages to satisfy the request. 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().

Return

pointer to the allocated area or NULL in case of error.

alloc_pages_exact_nid() #

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(), but try to allocate on node nid first before falling back.

Return

pointer to the allocated area or NULL in case of error.

free_pages_exact() #

void free_pages_exact(void *virt, size_t size)

release memory allocated via 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().

Description

Release the memory allocated by a previous call to alloc_pages_exact.

nr_free_zone_pages() #

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() 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.

nr_free_buffer_pages() #

unsigned long nr_free_buffer_pages(void)

count number of pages beyond high watermark

Parameters

  • void: no arguments

Description

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.

find_next_best_node() #

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.

setup_per_zone_wmarks() #

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.

alloc_contig_frozen_range() #

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(), free_frozen_pages() also could be used to free compound frozen pages directly.

Return

zero on success or negative error code.

alloc_contig_range() #

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(), 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() or by manually calling __free_page() on each allocated page.

Return

zero on success or negative error code.

alloc_contig_frozen_pages() #

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(). 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(). 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(), 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.

alloc_contig_pages() #

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(), 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() or by manually calling __free_page() on each allocated page.

Return

pointer to contiguous pages on success, or NULL if not successful.

free_contig_frozen_range() #

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.

free_contig_range() #

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.

alloc_pages_nolock() #

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.

numa_nearest_node() #

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

nearest_node_nodemask() #

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.

folio_can_map_prot_numa() #

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.

alloc_pages_mpol() #

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()).
  • int nid: Preferred node (usually numa_node_id() but mpol may override it).

Return

The page on success or NULL if allocation fails.

vma_alloc_folio() #

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.

alloc_pages() #

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.

mpol_misplaced() #

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.

mpol_shared_policy_init() #

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.

mpol_parse_str() #

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

mpol_to_str() #

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.

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.

struct folio #

Represents a contiguous set of bytes.

Definition

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()).
  • swap: Used for swp_entry_t if folio_test_swapcache().
  • _mapcount: Do not access this member directly. Use 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() 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().
  • _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().
  • _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().
  • _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().
  • _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.

struct ptdesc #

Memory descriptor for page tables.

Definition

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.

typedef vm_fault_t #

Return type for page fault handlers.

Description

Page fault handlers return a bitmask of VM_FAULT values.

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

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.

folio_is_file_lru() #

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.

__folio_clear_lru_flags() #

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.

folio_lru_list() #

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.

num_pages_contiguous() #

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() will return a num smaller than ideal number. The caller should continue to check for pfn contiguity after each call to num_pages_contiguous().

Returns the number of contiguous pages.

page_folio() #

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.

folio_page() #

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.

folio_xor_flags_has_waiters() #

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.

folio_test_uptodate() #

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.

folio_test_large() #

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.

PageHuge() #

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.

page_has_movable_ops() #

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.

folio_has_private() #

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.

folio_page_idx() #

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.

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.

fault_flag_allow_retry_first() #

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.

folio_order() #

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.

folio_reset_order() #

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.

folio_mapcount() #

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.

folio_mapped() #

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.

thp_order() #

unsigned int thp_order(struct page *page)

Order of a transparent huge page.

Parameters

  • struct page *page: Head page of a transparent huge page.

thp_size() #

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.

folio_get() #

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() may be the right interface for you to use.

folio_put() #

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() 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.

folio_put_refs() #

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() 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.

folios_put() #

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(), 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.

folio_pfn() #

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.

folio_mk_pte() #

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.

folio_mk_pmd() #

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.

folio_mk_pud() #

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.

folio_maybe_dma_pinned() #

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.

is_zero_page() #

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.

is_zero_folio() #

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.

folio_nr_pages() #

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.

folio_next() #

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.

folio_shift() #

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() and 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.

folio_size() #

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.

folio_maybe_mapped_shared() #

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.
    2. 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).
    2. If the folio is mapped differently (VM_PFNMAP).
    3. 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.

folio_expected_ref_count() #

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() 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() -- 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()) it might be holding itself to the result.

Returns the expected folio refcount.

ptdesc_address() #

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.

ptdesc_set_kernel() #

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.

ptdesc_clear_kernel() #

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.

ptdesc_test_kernel() #

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.

pagetable_alloc() #

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.

pagetable_free() #

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.

vma_lookup() #

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.

mmap_action_remap() #

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.

mmap_action_remap_full() #

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.

mmap_action_ioremap() #

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.

mmap_action_ioremap_full() #

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.

clear_pages() #

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() 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() 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.

vma_is_special_huge() #

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.

folio_ref_count() #

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() and decremented by calls to 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.

folio_try_get() #

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.

is_highmem() #

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

for_each_online_pgdat() #

for_each_online_pgdat(pgdat)

helper macro to iterate over all online nodes

Parameters

  • pgdat: pointer to a pg_data_t variable

for_each_zone() #

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.

next_zones_zonelist() #

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

first_zones_zonelist() #

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

for_each_zone_zonelist_nodemask() #

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

for_each_zone_zonelist() #

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.

pfn_valid() #

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

folio_mapping() #

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.

__anon_vma_prepare() #

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.

anon_vma_clone() #

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.

unlink_anon_vmas() #

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.

page_address_in_vma() #

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.

folio_referenced() #

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.

mapping_wrprotect_range() #

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.

pfn_mkclean_range() #

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).

folio_move_anon_rmap() #

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.

__folio_set_anon() #

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.

__page_check_anon_rmap() #

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

folio_add_anon_rmap_ptes() #

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).

folio_add_anon_rmap_pmd() #

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.

folio_add_new_anon_rmap() #

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.

folio_add_file_rmap_ptes() #

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.

folio_add_file_rmap_pmd() #

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.

folio_add_file_rmap_pud() #

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.

folio_remove_rmap_ptes() #

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.

folio_remove_rmap_pmd() #

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.

folio_remove_rmap_pud() #

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.

try_to_unmap() #

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.

try_to_migrate() #

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.

make_device_exclusive() #

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.
  2. 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.
  3. 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.

__rmap_walk_file() #

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.

isolate_movable_ops_page() #

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.

putback_movable_ops_page() #

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.

migrate_movable_ops_page() #

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.

migrate_folio() #

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.

buffer_migrate_folio() #

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() may be more appropriate.

Return

0 on success or a negative errno on failure.

buffer_migrate_folio_norefs() #

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() 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.

do_mmap() #

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.

find_vma_intersection() #

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.

find_vma() #

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.

find_vma_prev() #

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.

kmemleak_alloc() #

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() 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.).

kmemleak_alloc_percpu() #

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).

kmemleak_vmalloc() #

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() kernel allocator when a new object (memory block) is allocated.

kmemleak_free() #

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.).

kmemleak_free_part() #

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).

kmemleak_free_percpu() #

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).

kmemleak_update_trace() #

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.

kmemleak_not_leak() #

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.

kmemleak_transient_leak() #

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.

kmemleak_ignore_percpu() #

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

kmemleak_ignore() #

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.

kmemleak_scan_area() #

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() 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.

kmemleak_no_scan() #

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.

kmemleak_alloc_phys() #

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() flags used for kmemleak internal memory allocations

kmemleak_free_part_phys() #

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

kmemleak_ignore_phys() #

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

devm_memremap_pages() #

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.

get_dev_pagemap() #

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

vma_kernel_pagesize() #

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.

huge_pmd_unshare() #

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.

folio_isolate_hugetlb() #

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() to undo the isolation.

Return

True if isolation worked, otherwise False.

folio_putback_hugetlb() #

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(): marking it non-isolated/migratable and putting it back onto the active list.

Will drop the additional folio reference obtained through folio_isolate_hugetlb().

folio_mark_accessed() #

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().

folio_add_lru() #

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() have the folio added to the active list using folio_mark_accessed().

folio_add_lru_vma() #

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().

deactivate_file_folio() #

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.

folio_mark_lazyfree() #

void folio_mark_lazyfree(struct folio *folio)

make an anon folio lazyfree

Parameters

  • struct folio *folio: folio to deactivate

Description

folio_mark_lazyfree() moves folio to the inactive file list. This is done to accelerate the reclaim of folio.

folios_put_refs() #

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(), 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.

release_pages() #

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.

folio_batch_remove_exceptionals() #

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.

mem_cgroup_css_from_folio() #

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.

page_cgroup_ino() #

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() returns, so it only should be used by callers that do not care (such as procfs interfaces).

mod_memcg_state() #

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

mod_lruvec_state() #

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.

count_memcg_events() #

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

get_mem_cgroup_from_mm() #

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.

get_mem_cgroup_from_current() #

struct mem_cgroup * get_mem_cgroup_from_current(void)

Obtain a reference on current task's memcg.

Parameters

  • void: no arguments

get_mem_cgroup_from_folio() #

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.

mem_cgroup_iter() #

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() 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.

mem_cgroup_iter_break() #

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()

mem_cgroup_scan_tasks() #

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.

folio_lruvec_lock() #

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.

folio_lruvec_lock_irq() #

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.

folio_lruvec_lock_irqsave() #

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.

mem_cgroup_update_lru_size() #

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.

mem_cgroup_margin() #

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.

mem_cgroup_print_oom_context() #

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

mem_cgroup_print_oom_meminfo() #

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

mem_cgroup_get_oom_group() #

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.

consume_stock() #

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.

__memcg_kmem_charge_page() #

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.

__memcg_kmem_uncharge_page() #

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

mem_cgroup_wb_stats() #

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.

mem_cgroup_from_private_id() #

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().

mem_cgroup_css_reset() #

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.

mem_cgroup_calculate_protection() #

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.

mem_cgroup_charge_hugetlb() #

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.

mem_cgroup_swapin_charge_folio() #

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.

mem_cgroup_replace_folio() #

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.

mem_cgroup_migrate() #

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.

mem_cgroup_sk_charge() #

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.

mem_cgroup_sk_uncharge() #

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

__mem_cgroup_try_charge_swap() #

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.

__mem_cgroup_uncharge_swap() #

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

obj_cgroup_may_zswap() #

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.

obj_cgroup_charge_zswap() #

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() allowed compression and storage in zswap for this cgroup to go ahead.

obj_cgroup_uncharge_zswap() #

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.

shmem_recalc_inode() #

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().

shmem_writeout() #

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.

shmem_get_folio() #

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() before unlocking the folio to ensure that the folio is not reclaimed. There is no need to reserve space before calling 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.

shmem_kernel_file_setup() #

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

shmem_file_setup() #

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

shmem_file_setup_with_mnt() #

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

shmem_zero_setup() #

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

shmem_zero_setup_desc() #

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

shmem_read_folio_gfp() #

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() 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.

migrate_vma_split_folio() #

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

migrate_vma_setup() #

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().

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(), just like for regular migration.

After that, the callers must call 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() 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() 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() 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() 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.

migrate_vma_insert_huge_pmd_page() #

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.

migrate_device_pages() #

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()
  • 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(). This is called to migrate struct page meta-data from source struct page to destination.

migrate_vma_pages() #

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.

migrate_vma_finalize() #

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.

migrate_device_range() #

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() is similar in concept to 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() 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().

migrate_device_pfns() #

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() but supports non-contiguous pre-populated array of device pages to migrate.

struct wp_walk #

Private struct for pagetable walk callbacks

Definition

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

wp_pte() #

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.

struct clean_walk #

Private struct for the clean_record_pte function.

Definition

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

clean_record_pte() #

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.

wp_shared_mapping_range() #

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.

clean_record_shared_mapping_range() #

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.

pcpu_addr_in_chunk() #

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.

pcpu_check_block_hint() #

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.

pcpu_next_md_free_region() #

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.

pcpu_next_fit_region() #

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.

pcpu_mem_zalloc() #

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() is used; otherwise, the equivalent of 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.

pcpu_mem_free() #

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().

pcpu_chunk_relocate() #

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.

pcpu_block_update() #

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.

pcpu_chunk_refresh_hint() #

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.

pcpu_block_refresh_hint() #

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.

pcpu_block_update_hint_alloc() #

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.

pcpu_block_update_hint_free() #

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.

pcpu_is_populated() #

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.

pcpu_find_block_fit() #

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.

pcpu_alloc_area() #

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.

pcpu_free_area() #

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.

pcpu_alloc_first_chunk() #

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.

pcpu_chunk_populated() #

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.

pcpu_chunk_depopulated() #

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.

pcpu_chunk_addr_search() #

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.

pcpu_alloc() #

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.

pcpu_balance_free() #

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)

pcpu_balance_populated() #

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)

pcpu_reclaim_populated() #

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)

pcpu_balance_workfn() #

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.

free_percpu() #

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.

is_kernel_percpu_address() #

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.

per_cpu_ptr_to_phys() #

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() callers. So we keep current code.

Return

The physical address for addr.

pcpu_alloc_alloc_info() #

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.

pcpu_free_alloc_info() #

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().

pcpu_dump_alloc_info() #

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.

pcpu_setup_first_chunk() #

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.

pcpu_build_alloc_info() #

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.

pcpu_embed_first_chunk() #

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() 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.

pcpu_page_first_chunk() #

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() 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.

copy_from_user_nofault() #

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.

copy_to_user_nofault() #

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.

strncpy_from_user_nofault() #

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.

strnlen_user_nofault() #

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.

writeback_throttling_sane() #

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.

lruvec_lru_size() #

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)

remove_mapping() #

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.

folio_putback_lru() #

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.

folio_isolate_lru() #

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.

check_move_unevictable_folios() #

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.

__remove_pages() #

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().

try_offline_node() #

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.

__remove_memory() #

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().

mmu_interval_read_begin() #

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().

mmu_notifier_register() #

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() 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().

mmu_notifier_get_locked() #

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(). 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().

mmu_notifier_put() #

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() 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() in their __exit functions to ensure the async work is completed.

mmu_interval_notifier_insert() #

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() to establish SPTEs for this range.

mmu_interval_notifier_remove() #

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(). 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.

mmu_notifier_synchronize() #

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() 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().

Modules using the mmu_notifier_put() API should call this in their __exit function to avoid module unloading races.

balloon_page_insert() #

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.

balloon_page_finalize() #

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.

balloon_page_list_enqueue() #

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.

balloon_page_list_dequeue() #

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.

balloon_page_alloc() #

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.

balloon_page_enqueue() #

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.

balloon_page_dequeue() #

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.

vmf_insert_pfn_pmd() #

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() for additional info.

Return

vm_fault_t value.

vmf_insert_pfn_pud() #

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() for additional info.

Return

vm_fault_t value.

vmf_insert_folio_pud() #

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.

touch_pmd() #

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

__split_unmapped_folio() #

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)

folio_check_splittable() #

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() 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.

__folio_split() #

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() 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().

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)

folio_split_unmapped() #

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).

folio_split() #

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)

min_order_for_split() #

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() 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

General guidance #

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.

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).

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).

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).

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.

Netlink specification #

Documentation of the Netlink specification parts which are only relevant to the kernel space.

Globals #

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.

checks #

Documentation for the checks sub-sections of attribute specs.

unterminated-ok #

Accept strings without the null-termination (for legacy families only). Switches from the NLA_NUL_STRING to NLA_STRING policy type.

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.

min-len #

Similar to max-len but defines minimum length.

Generic bitfield packing and unpacking functions

Peios Kernel / Internals / Core APIs

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.

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:
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.

  1. If QUIRK_MSB_ON_THE_RIGHT is set, we do it like this:
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.

  1. If QUIRK_LITTLE_ENDIAN is set, we do it like this:
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.

  1. If QUIRK_MSB_ON_THE_RIGHT and QUIRK_LITTLE_ENDIAN are both set, we do it like this:
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
  1. If just QUIRK_LSW32_IS_FIRST is set, we do it like this:
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.

  1. If QUIRK_LSW32_IS_FIRST and QUIRK_MSB_ON_THE_RIGHT are set, we do it like this:
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
  1. If QUIRK_LSW32_IS_FIRST and QUIRK_LITTLE_ENDIAN are set, it looks like this:
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
  1. If QUIRK_LSW32_IS_FIRST, QUIRK_LITTLE_ENDIAN and QUIRK_MSB_ON_THE_RIGHT are set, it looks like this:
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.

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:

           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:

 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:

           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:

 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)

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.

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.

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();
}

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).

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:

/* 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

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.

Running Serialized Jobs #

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:

#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:

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.

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:

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/<instance-name>. 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:

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.

Running A Job #

Actually submitting work to the padata instance requires the creation of a padata_priv structure, which represents one job:

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:

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.

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:

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.

Destroying #

Cleaning up a padata instance predictably involves calling the two free functions that correspond to the allocation in reverse:

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.

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.

Interface #

struct padata_priv #

Represents one job

Definition

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.

struct padata_list #

one per work type per CPU

Definition

struct padata_list {
    struct list_head        list;
    spinlock_t lock;
};

Members

  • list: List head.
  • lock: List lock.

struct padata_serial_queue #

The percpu padata serial queue

Definition

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.

struct padata_cpumask #

The cpumasks for the parallel/serial workers

Definition

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.

struct parallel_data #

Internal control structure, covers everything that depends on the cpumask in use.

Definition

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.

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

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.

struct padata_mt_job #

represents one multithreaded job

Definition

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.

struct padata_instance #

The overall control structure.

Definition

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.

padata_do_parallel() #

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.

padata_do_serial() #

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.

padata_do_multithreaded() #

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.

padata_set_cpumask() #

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

padata_alloc() #

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

padata_free() #

void padata_free(struct padata_instance *pinst)

free a padata instance

Parameters

  • struct padata_instance *pinst: padata instance to free

padata_alloc_shell() #

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

padata_free_shell() #

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

Overview #

The generic parser is a simple parser for parsing mount options, filesystem options, driver options, subsystem options, etc.

Parser API #

match_token() #

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.

match_int() #

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.

match_uint() #

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.

match_u64() #

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.

match_octal() #

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.

match_hex() #

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.

match_wildcard() #

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.

match_strlcpy() #

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.

match_strdup() #

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().

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 #

This document describes the following functions:

pin_user_pages()
pin_user_pages_fast()
pin_user_pages_remote()

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.

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.:

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.:

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.

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->_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->_refcount into bit fields, we simple add a medium- large value (GUP_PIN_COUNTING_BIAS, initially chosen to be 1024: 10 bits) to page->_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.

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:

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:

FOLL_PIN

...but rather than setting FOLL_PIN directly, call sites should use one of the pin_user_pages*() routines that set FOLL_PIN.

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:

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.

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.

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.

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()

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:

static inline bool folio_maybe_dma_pinned(struct folio *folio)

...is a prerequisite to solving the long-running gup+DMA problem.

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.

Unit testing #

This file:

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:

/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:

    pin_user_pages(huge_page);
    for (each page in huge_page)
        unpin_user_page(page);
    

...the following is expected:

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.)

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.

References #

  • Some slow progress on get_user_pages() (Apr 2, 2019)

  • DMA and get_user_pages() (LPC: Dec 12, 2018)

  • The trouble with get_user_pages() (Apr 30, 2018)

  • LWN kernel index: get_user_pages()

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() 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.

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:

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:

Name

String

Alias function

KERN_EMERG

"0"

pr_emerg()

KERN_ALERT

"1"

pr_alert()

KERN_CRIT

"2"

pr_crit()

KERN_ERR

"3"

pr_err()

KERN_WARNING

"4"

pr_warn()

KERN_NOTICE

"5"

pr_notice()

KERN_INFO

"6"

pr_info()

KERN_DEBUG

"7"

pr_debug() and pr_devel() if DEBUG is defined

KERN_DEFAULT

""

KERN_CONT

"c"

pr_cont()

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:

$ 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:

# echo 8 > /proc/sys/kernel/printk

Another way, using dmesg:

# 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:

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):

#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.

Function reference #

pr_fmt() #

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.

printk() #

printk(fmt, ...)

print a kernel message

Parameters

  • fmt: format string
  • ...: variable arguments

Description

This is 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(); and will send it to the consoles before releasing the lock.

One effect of this deferred printing is that code which calls 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() documentation for format string extensions over C99.

pr_emerg() #

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() to generate the format string.

pr_alert() #

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() to generate the format string.

pr_crit() #

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() to generate the format string.

pr_err() #

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() to generate the format string.

pr_warn() #

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() to generate the format string.

pr_notice() #

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() to generate the format string.

pr_info() #

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() to generate the format string.

pr_cont() #

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.

pr_devel() #

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() to generate the format string.

pr_debug() #

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() to generate the format string (dynamic_pr_debug() uses pr_fmt() internally).

How to get printk format specifiers right

Peios Kernel / Internals / Core APIs

Author: Randy Dunlap <rdunlap@infradead.org>

Author: Andrew Murray <amurray@mpc-data.co.uk>

Integer types #

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 <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.

Example:

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().

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:

(null)   data on plain NULL address
(efault) data on invalid address
(einval) invalid data on a valid address

Plain Pointers #

%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.

Error Pointers #

%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.

Symbols/Function Pointers #

%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.

%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]

Probed Pointers from BPF / tracing #

%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.

Kernel Pointers #

%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 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().

Unmodified Addresses #

%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.

Pointer Differences #

%td     2560
%tx     a00

For printing the pointer differences, use the %t modifier for ptrdiff_t.

Example:

printk("test: difference between pointers: %td\n", ptr2 - ptr1);

Struct Resources #

%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.

Physical address types phys_addr_t #

%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.

Struct Range #

%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.

DMA address types dma_addr_t #

%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.

Raw buffer as an escaped string #

%*pE[achnops]

For printing raw buffer as an escaped string. For the following buffer:

1b 62 20 5c 43 07 22 90 0d 5d

A few examples show how the conversion would be done (excluding surrounding quotes):

%*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.

Raw buffer as a hex string #

%*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().

MAC/FDDI addresses #

%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.

IPv4 addresses #

%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.

IPv6 addresses #

%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

Passed by reference.

IPv4/IPv6 addresses (generic, with port, flowinfo, scope) #

%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 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

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:

%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

UUID/GUID addresses #

%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.

dentry names #

%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->d_name.name we used to use, %pd<n> prints n last components. %pD does the same thing for struct file.

Passed by reference.

block_device names #

%pg     sda, sda1 or loop0p1

For printing name of block_device pointers.

struct va_format #

%pV

For printing struct va_format structures. These contain a format string and va_list as follows:

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.

Device tree nodes #

%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:

%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.

Fwnode handles #

%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):

%pfwf   \_SB.PCI0.CIO2.port@1.endpoint@0        - Full node name
%pfwP   endpoint@0                              - Node name

Examples (OF):

%pfwf   /ocp@68000000/i2c@48072000/camera@10/port/endpoint - Full name
%pfwP   endpoint                                - Node name

Time and date #

%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:

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.

struct clk #

%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.

bitmap and its derivatives such as cpumask and nodemask #

%*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.

Flags bitfields such as page flags and gfp_flags #

%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 <trace/events/mmflags.h>.

Passed by reference.

Network device features #

%pNF    0x000000000000c000

For printing netdev_features_t.

Passed by reference.

V4L2 and DRM FourCC code (pixel format) #

%p4cc

Print a FourCC code used by V4L2 or DRM, including format endianness and its numerical value as hexadecimal.

Passed by reference.

Examples:

%p4cc   BG12 little-endian (0x32314742)
%p4cc   Y10  little-endian (0x20303159)
%p4cc   NV12 big-endian (0xb231564e)

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 &(u32)0x67503030:

%p4ch   gP00 (0x67503030)
%p4chR  00Pg (0x30305067)
%p4cl   gP00 (0x67503030)
%p4cb   00Pg (0x30305067)

Examples for a big-endian machine, given &(u32)0x67503030:

%p4ch   gP00 (0x67503030)
%p4chR  00Pg (0x30305067)
%p4cl   00Pg (0x30305067)
%p4cb   gP00 (0x67503030)

Rust #

%pA

Only intended to be used from Rust code to format core::fmt::Arguments. Do not use it from C.

Thanks #

If you add other %p extensions, please extend <lib/tests/printf_kunit.c> 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.

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.

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:

/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:

$> 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.

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.

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.

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:

#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:

<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.

  • 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)

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.

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.

Syscalls #

There are 3 system calls which directly interact with pkeys:

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().

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:

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:

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

Behavior #

The kernel attempts to make protection keys consistent with the behavior of a plain mprotect(). For instance if you do this:

mprotect(ptr, size, PROT_NONE);
something(ptr);

you can expect the same effects with protection keys when doing this:

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:

*ptr = foo;

or when the kernel does the access on the application's behalf like with a read():

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

Date: January 18, 2007

Author: Rob Landley <rob@landley.net>

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/

  • Wikipedia entry on red-black trees

    https://en.wikipedia.org/wiki/Red-black_tree

Linux implementation of red-black trees #

Linux's rbtree implementation lives in the file "lib/rbtree.c". To use it, "#include <linux/rbtree.h>".

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.

Creating a new rbtree #

Data nodes in an rbtree tree are structures containing a struct rb_node member:

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;

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:

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;
}

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:

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;
}

Removing or replacing existing data in an rbtree #

To remove an existing node from a tree, call:

void rb_erase(struct rb_node *victim, struct rb_root *tree);

Example:

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:

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.

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):

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:

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);

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:

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:

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:

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 *);

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 <linux/rbtree_augmented.h> instead of <linux/rbtree.h>. 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 <linux/rbtree_augmented.h> 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.

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:

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:

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 #

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.

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 & 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.

Comparison of functions #

case 1) - non-"Read/Modify/Write" (RMW) ops #

Function changes:

  • atomic_set() --> refcount_set()

  • atomic_read() --> refcount_read()

Memory ordering guarantee changes:

  • none (both fully unordered)

case 2) - non-"Read/Modify/Write" (RMW) ops with release ordering #

Function changes:

  • atomic_set_release() --> refcount_set_release()

Memory ordering guarantee changes:

  • none (both provide RELEASE ordering)

case 3) - increment-based ops that return no value #

Function changes:

  • atomic_inc() --> refcount_inc()

  • atomic_add() --> refcount_add()

Memory ordering guarantee changes:

  • none (both fully unordered)

case 4) - decrement-based RMW ops that return no value #

Function changes:

  • atomic_dec() --> refcount_dec()

Memory ordering guarantee changes:

  • fully unordered --> RELEASE ordering

case 5) - increment-based RMW ops that return a value #

Function changes:

  • atomic_inc_not_zero() --> refcount_inc_not_zero()

  • no atomic counterpart --> refcount_add_not_zero()

Memory ordering guarantees changes:

  • fully ordered --> 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!

case 6) - increment-based RMW ops with acquire ordering that return a value #

Function changes:

  • atomic_inc_not_zero() --> refcount_inc_not_zero_acquire()

  • no atomic counterpart --> refcount_add_not_zero_acquire()

Memory ordering guarantees changes:

  • fully ordered --> ACQUIRE ordering on success

case 7) - generic dec/sub decrement-based RMW ops that return a value #

Function changes:

  • atomic_dec_and_test() --> refcount_dec_and_test()

  • atomic_sub_and_test() --> refcount_sub_and_test()

Memory ordering guarantees changes:

  • fully ordered --> RELEASE ordering + ACQUIRE ordering on success

case 8) other decrement-based RMW ops that return a value #

Function changes:

  • no atomic counterpart --> refcount_dec_if_one()

  • atomic_add_unless(&var, -1, 1) --> refcount_dec_not_one(&var)

Memory ordering guarantees changes:

  • fully ordered --> RELEASE ordering + control dependency

Note

atomic_add_unless() only provides full order on success.

case 9) - lock-based RMW #

Function changes:

  • atomic_dec_and_lock() --> refcount_dec_and_lock()

  • atomic_dec_and_mutex_lock() --> refcount_dec_and_mutex_lock()

Memory ordering guarantees changes:

  • fully ordered --> 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 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.

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.

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.

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/<device>/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.

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.

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.

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.

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.

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.

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.

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:

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.

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:

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:

#define DEFAULT_SYMBOL_NAMESPACE "USB_COMMON"

within the corresponding compilation unit before the #include for <linux/export.h>. Typically it's placed before the first #include statement.

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:

EXPORT_SYMBOL_FOR_MODULES(preempt_notifier_inc, "kvm,kvm-*")

will limit usage of this symbol to modules whose name matches the given patterns.

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:

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:

$ 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().

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.

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:

$ make nsdeps

A typical scenario for module authors would be:

- 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:

- 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:

$ 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

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:

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)

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:

DEFINE_PER_CPU(int, x);
int z;

z = this_cpu_read(x);

results in a single instruction:

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:

this_cpu_inc(x)

The above results in the following single instruction (no lock prefix!):

inc gs:[x]

instead of the following operations required if there is no segment register:

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.

Special operations #

y = this_cpu_ptr(&x)

Takes the offset of a per cpu variable (&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().

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 &x outside of the context of per cpu operations is invalid and will generally be treated like a NULL pointer dereference.

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.

int __percpu *p = &x;

&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.

Operations on a field of a per cpu structure #

Let's say we have a percpu structure:

struct s {
        int n,m;
};

DEFINE_PER_CPU(struct s, p);

Operations on these fields are straightforward:

this_cpu_inc(p.m)

z = this_cpu_cmpxchg(p.m, 0, 1);

If we have an offset to struct s:

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:

struct s *pp;

pp = this_cpu_ptr(&p);

pp->m--;

z = pp->n++;

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:

__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.

&this_cpu_ptr(pp)->n vs this_cpu_ptr(&pp->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.

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:

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:

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:

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 equally fit for a particular use case.

Basic ktime_t based interfaces #

The recommended simplest form returns an opaque ktime_t, with variants that return time for different clock references:

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.

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.

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.

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.

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.

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:

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.

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.

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.

Coarse and fast_ns access #

Some additional variants exist for more specialized cases:

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 )

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 )

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.

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.

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:

void ktime_get_ts( struct timespec * )

Use ktime_get() or ktime_get_ts64() instead.

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()).

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.

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

Author: Jason Baron

Author: William Cohen

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.

IRQ #

trace_irq_handler_entry() #

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.

trace_irq_handler_exit() #

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.

trace_softirq_entry() #

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.

trace_softirq_exit() #

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.

trace_softirq_raise() #

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.

trace_tasklet_entry() #

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

trace_tasklet_exit() #

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

SIGNAL #

trace_signal_generate() #

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.

trace_signal_deliver() #

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.

Block IO #

trace_block_touch_buffer() #

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().

trace_block_dirty_buffer() #

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().

trace_block_rq_requeue() #

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.

trace_block_rq_complete() #

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.

trace_block_rq_error() #

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.

trace_block_rq_insert() #

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.

trace_block_rq_issue() #

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.

trace_block_rq_merge() #

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.

trace_block_io_start() #

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

trace_block_io_done() #

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

trace_block_bio_complete() #

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.

trace_block_bio_backmerge() #

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.

trace_block_bio_frontmerge() #

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.

trace_block_bio_queue() #

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.

trace_block_getrq() #

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.

trace_blk_zone_append_update_request_bio() #

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.

trace_block_plug() #

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.

trace_block_unplug() #

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.

trace_block_split() #

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.

trace_block_bio_remap() #

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.

trace_block_rq_remap() #

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.

trace_blkdev_zone_mgmt() #

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.

Workqueue #

trace_workqueue_queue_work() #

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).

trace_workqueue_activate_work() #

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.

trace_workqueue_execute_start() #

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.

trace_workqueue_execute_end() #

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

Author: Daniel Drake <dsd@gentoo.org>,

Author: Johannes Berg <johannes@sipsolutions.net>

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!

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.

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.

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.

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:

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:

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.

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:

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:

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

Avoiding unaligned accesses #

The easiest way to avoid unaligned access is to use the get_unaligned() and put_unaligned() macros provided by the <linux/unaligned.h> header file.

Going back to an earlier example of code that potentially causes unaligned access:

void myfunc(u8 *data, u32 value)
{
        [...]
        *((u32 *) data) = cpu_to_le32(value);
        [...]
}

To avoid the unaligned memory access, you would rewrite it as follows:

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:

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.

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:

#ifdef CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS
        skb = original skb
#else
        skb = copy skb
#endif

Union-Find in Linux

Peios Kernel / Internals / Core APIs

Date: June 21, 2024

Author: Xavier <xavier_qy@163.com>

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

Linux implementation of union-find #

Linux's union-find implementation resides in the file "lib/union_find.c". To use it, "#include <linux/union_find.h>".

The union-find data structure is defined as follows:

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.

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:

struct uf_node my_node = UF_INIT_NODE(my_node);

or

uf_node_init(&my_node);

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:

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;

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:

uf_union(&node_1, &node_2);

General notification mechanism

Peios Kernel / Internals / Core APIs

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.

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:

* Key/keyring notifications

The notifications buffers can be enabled by:

"General setup"/"General notification queue" (CONFIG_WATCH_QUEUE)

This document has the following sections:

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.

Message Structure #

Notification messages begin with a short header:

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.

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:

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.

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().

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:

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.

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.

Notification Posting API #

To post a notification to watch list so that the subscribed watches can see it, the following function should be used:

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.

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 for more information.

Event Filtering #

Once a watch queue has been created, a set of filters can be applied to limit the events that are received using:

struct watch_notification_filter filter = {
        ...
};
ioctl(fd, IOC_WATCH_QUEUE_SET_FILTER, &filter)

The filter description is a variable of type:

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:

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:

    (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.

Userspace Code Example #

A buffer is created with something like the following:

pipe2(fds, O_TMPFILE);
ioctl(fds[1], IOC_WATCH_QUEUE_SET_SIZE, 256);

It can then be set to receive keyring change notifications:

keyctl(KEYCTL_WATCH_KEY, KEY_SPEC_SESSION_KEYRING, fds[1], 0x01);

The notifications can then be consumed by something like the following:

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

Date: September, 2010

Author: Tejun Heo <tj@kernel.org>

Author: Florian Mickler <florian@mickler.org>

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.

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.

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.

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.

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.

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.

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.

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 >= 3,

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,

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,

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

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.

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.

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.

Scenario 1: Enough issuers and work spread across the machine #

The command used:

$ 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.

Affinity

Bandwidth (MiBps)

CPU util (%)

system

1159.40 ±1.34

99.31 ±0.02

cache

1166.40 ±0.89

99.34 ±0.01

cache (strict)

1166.00 ±0.71

99.35 ±0.01

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.

Scenario 2: Fewer issuers, enough work for saturation #

The command used:

$ 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.

Affinity

Bandwidth (MiBps)

CPU util (%)

system

1155.40 ±0.89

97.41 ±0.05

cache

1154.40 ±1.14

96.15 ±0.09

cache (strict)

1112.00 ±4.64

93.26 ±0.35

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.

Scenario 3: Even fewer issuers, not enough work to saturate #

The command used:

$ 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.

Affinity

Bandwidth (MiBps)

CPU util (%)

system

993.60 ±1.82

75.49 ±0.06

cache

973.40 ±1.52

74.90 ±0.07

cache (strict)

828.20 ±4.49

66.84 ±0.29

Now, the tradeoff between locality and utilization is clearer. "cache" shows 2% bandwidth loss compared to "system" and "cache (struct)" whopping 20%.

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.

Examining Configuration #

Use tools/workqueue/wq_dump.py to examine unbound CPU affinity configuration, worker pools and how workqueues map to the pools:

$ 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.

Monitoring #

Use tools/workqueue/wq_monitor.py to monitor workqueue operations:

$ 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.

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:

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:

$ 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.

$ cat /proc/THE_OFFENDING_KWORKER/stack

The work item's function should be trivially visible in the stack trace.

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.

Kernel Inline Documentations Reference #

struct workqueue_attrs #

A struct for workqueue attributes.

Definition

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.

work_pending() #

work_pending(work)

Find out whether a work item is currently pending

Parameters

  • work: The work item in question

delayed_work_pending() #

delayed_work_pending(w)

Find out whether a delayable work item is currently pending

Parameters

  • w: The work item in question

alloc_workqueue() #

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.

alloc_workqueue_lockdep_map() #

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.

alloc_ordered_workqueue_lockdep_map() #

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.

alloc_ordered_workqueue() #

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.

queue_work() #

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() 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

queue_delayed_work() #

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() but tries to use the local CPU.

mod_delayed_work() #

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() on local CPU.

schedule_work_on() #

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

schedule_work() #

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(), cf. the DocBook header of queue_work().

enable_and_queue_work() #

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() and queue_work(), providing a convenient way to enable and queue a work item in a single call. It invokes 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().

schedule_delayed_work_on() #

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.

schedule_delayed_work() #

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.

for_each_pool() #

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.

for_each_pool_worker() #

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.

for_each_pwq() #

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.

worker_pool_assign_id() #

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.

unbound_effective_cpumask() #

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.

get_work_pool() #

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() 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.

worker_set_flags() #

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.

worker_clr_flags() #

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.

worker_enter_idle() #

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).

worker_leave_idle() #

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).

find_worker_executing_work() #

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.

move_linked_works() #

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() for details on nextp.

Context

raw_spin_lock_irq(pool->lock).

assign_work() #

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() to be nested inside 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.

kick_pool() #

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.

wq_worker_running() #

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()

wq_worker_sleeping() #

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.

wq_worker_tick() #

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.

wq_worker_last_func() #

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.

wq_node_nr_active() #

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].

wq_update_node_max_active() #

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.

get_pwq() #

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.

put_pwq() #

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.

put_pwq_unlocked() #

void put_pwq_unlocked(struct pool_workqueue *pwq)

put_pwq() with surrounding pool lock/unlock

Parameters

  • struct pool_workqueue *pwq: pool_workqueue to put (can be NULL)

Description

put_pwq() with locking. This function also allows NULL pwq.

pwq_tryinc_nr_active() #

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.

pwq_activate_first_inactive() #

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.

unplug_oldest_pwq() #

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:

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.

node_activate_pending_pwq() #

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.

pwq_dec_nr_active() #

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.

pwq_dec_nr_in_flight() #

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).

try_to_grab_pending() #

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.

========    ================================================================
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.

work_grab_pending() #

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.

insert_work() #

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).

queue_work_on() #

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.

select_numa_node_cpu() #

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.

queue_work_node() #

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.

queue_delayed_work_on() #

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.

mod_delayed_work_on() #

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(); 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() for details.

Return

false if dwork was idle and queued, true if dwork was pending and its timer was modified.

queue_rcu_work() #

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.

worker_attach_to_pool() #

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.

worker_detach_from_pool() #

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(). The caller worker shouldn't access to the pool after detached except it has other reference to the pool.

create_worker() #

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.

set_worker_dying() #

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).

idle_worker_timeout() #

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(). Note that it isn't disarmed in 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.

idle_cull_fn() #

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.

maybe_create_worker() #

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.

manage_workers() #

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.

process_one_work() #

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.

process_scheduled_works() #

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.

worker_thread() #

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().

Return

0

rescuer_thread() #

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

check_flush_dependency() #

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.

insert_wq_barrier() #

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() 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).

flush_workqueue_prep_pwqs() #

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.

__flush_workqueue() #

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.

drain_workqueue() #

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.

flush_work() #

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() waited for the work to finish execution, false if it was already idle.

flush_delayed_work() #

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(), this function only considers the last queueing instance of dwork.

Return

true if flush_work() waited for the work to finish execution, false if it was already idle.

flush_rcu_work() #

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() waited for the work to finish execution, false if it was already idle.

cancel_work_sync() #

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() 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.

cancel_delayed_work() #

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() to wait on it.

This function is safe to call from any context including IRQ handler.

cancel_delayed_work_sync() #

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() for delayed works.

Return

true if dwork was pending, false otherwise.

disable_work() #

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.

disable_work_sync() #

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() 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.

enable_work() #

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.

disable_delayed_work() #

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() for delayed work items.

disable_delayed_work_sync() #

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() for delayed work items.

enable_delayed_work() #

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() for delayed work items.

schedule_on_each_cpu() #

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() executes func on each online CPU using the system workqueue and blocks until all CPUs have completed. schedule_on_each_cpu() is very slow.

Return

0 on success, -errno on failure.

execute_in_process_context() #

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

free_workqueue_attrs() #

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().

alloc_workqueue_attrs() #

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.

init_worker_pool() #

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() can be called on pool safely to release it.

put_unbound_pool() #

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() 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().

Should be called with wq_pool_mutex held.

get_unbound_pool() #

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.

wq_calc_pod_cpumask() #

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.

apply_workqueue_attrs() #

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()

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.

unbound_wq_update_pwq() #

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.

wq_adjust_max_active() #

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.

destroy_workqueue() #

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() 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() would cleanly cancel all pending and non-pending delayed_work.

workqueue_set_max_active() #

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() function comment.

Context

Don't call from IRQ context.

workqueue_set_min_active() #

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.

current_work() #

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.

current_is_workqueue_rescuer() #

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.

workqueue_congested() #

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.

work_busy() #

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.

set_worker_desc() #

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'.

print_worker_info() #

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() 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.

show_one_workqueue() #

void show_one_workqueue(struct workqueue_struct *wq)

dump state of specified workqueue

Parameters

  • struct workqueue_struct *wq: workqueue whose state will be printed

show_one_worker_pool() #

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

show_all_workqueues() #

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.

show_freezable_workqueues() #

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.

rebind_workers() #

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.

restore_unbound_workers_cpumask() #

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.

work_on_cpu_key() #

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.

freeze_workqueues_begin() #

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.

freeze_workqueues_busy() #

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() and thaw_workqueues().

Context

Grabs and releases wq_pool_mutex.

Return

true if some freezable workqueues are still busy. false if freezing is complete.

thaw_workqueues() #

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.

workqueue_unbound_housekeeping_update() #

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.

workqueue_set_unbound_cpumask() #

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.

workqueue_sysfs_register() #

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() may race against userland updating the attributes.

Return

0 on success, -errno on failure.

workqueue_sysfs_unregister() #

void workqueue_sysfs_unregister(struct workqueue_struct *wq)

undo workqueue_sysfs_register()

Parameters

  • struct workqueue_struct *wq: the workqueue to unregister

Description

If wq is registered to sysfs by workqueue_sysfs_register(), unregister.

workqueue_init_early() #

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.

workqueue_init() #

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.

workqueue_init_topology() #

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

Author: Matthew Wilcox

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.

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.

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.

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.

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.

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:

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.

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.

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.

Name

Test

Usage

Node

xa_is_node()

An XArray node. May be visible when using a multi-index xa_state.

Sibling

xa_is_sibling()

A non-canonical entry for a multi-index entry. The value indicates which slot in this node has the canonical entry.

Retry

xa_is_retry()

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.

Zero

xa_is_zero()

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.

Other internal entries may be added in the future. As far as possible, they will be handled by xas_retry().

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.

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.

Functions and structures #

xa_mk_value() #

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.

xa_to_value() #

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.

xa_is_value() #

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.

xa_tag_pointer() #

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.

xa_untag_pointer() #

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.

xa_pointer_tag() #

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.

xa_is_zero() #

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.

xa_is_err() #

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() tells you which error occurred.

Context

Any context.

Return

true if the entry indicates an error.

xa_err() #

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.

struct xa_limit #

Represents a range of IDs.

Definition

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]

struct xarray #

The anchor of the XArray.

Definition

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.

DEFINE_XARRAY_FLAGS() #

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() on the array, but it does the initialisation at compiletime instead of runtime.

DEFINE_XARRAY() #

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() on the array, but it does the initialisation at compiletime instead of runtime.

DEFINE_XARRAY_ALLOC() #

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().

DEFINE_XARRAY_ALLOC1() #

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().

xa_init_flags() #

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().

Context

Any context.

xa_init() #

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.

xa_empty() #

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.

xa_marked() #

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.

xa_for_each_range() #

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() is O(n.log(n)) while xas_for_each() is O(n). You have to handle your own locking with 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() will spin if it hits a retry entry; if you intend to see retry entries, you should use the xas_for_each() iterator instead. The xas_for_each() iterator will expand into more inline code than xa_for_each_range().

Context

Any context. Takes and releases the RCU lock.

xa_for_each_start() #

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() is O(n.log(n)) while xas_for_each() is O(n). You have to handle your own locking with 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() will spin if it hits a retry entry; if you intend to see retry entries, you should use the xas_for_each() iterator instead. The xas_for_each() iterator will expand into more inline code than xa_for_each_start().

Context

Any context. Takes and releases the RCU lock.

xa_for_each() #

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() is O(n.log(n)) while xas_for_each() is O(n). You have to handle your own locking with 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() will spin if it hits a retry entry; if you intend to see retry entries, you should use the xas_for_each() iterator instead. The xas_for_each() iterator will expand into more inline code than xa_for_each().

Context

Any context. Takes and releases the RCU lock.

xa_for_each_marked() #

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() is O(n.log(n)) while xas_for_each_marked() is O(n). You have to handle your own locking with 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() will spin if it hits a retry entry; if you intend to see retry entries, you should use the xas_for_each_marked() iterator instead. The xas_for_each_marked() iterator will expand into more inline code than xa_for_each_marked().

Context

Any context. Takes and releases the RCU lock.

xa_store_bh() #

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() 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() if an error happened.

xa_store_irq() #

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() 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() if an error happened.

xa_erase_bh() #

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.

xa_erase_irq() #

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.

xa_cmpxchg() #

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() if an error happened.

xa_cmpxchg_bh() #

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() 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() if an error happened.

xa_cmpxchg_irq() #

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() 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() if an error happened.

xa_insert() #

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()) 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.

xa_insert_bh() #

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()) 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.

xa_insert_irq() #

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()) 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.

xa_alloc() #

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().

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.

xa_alloc_bh() #

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().

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.

xa_alloc_irq() #

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().

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.

xa_alloc_cyclic() #

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().

Note that callers interested in whether wrapping has occurred should use __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.

xa_alloc_cyclic_bh() #

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().

Note that callers interested in whether wrapping has occurred should use __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.

xa_alloc_cyclic_irq() #

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().

Note that callers interested in whether wrapping has occurred should use __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.

xa_reserve() #

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() or 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.

xa_reserve_bh() #

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().

Context

Any context. Takes and releases the xa_lock while disabling softirqs.

Return

0 if the reservation succeeded or -ENOMEM if it failed.

xa_reserve_irq() #

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().

Context

Process context. Takes and releases the xa_lock while disabling interrupts.

Return

0 if the reservation succeeded or -ENOMEM if it failed.

xa_release() #

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(), you can call this function to release the reservation. If the entry at index has been stored to, this function will do nothing.

xa_is_sibling() #

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.

xa_is_retry() #

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.

xa_is_advanced() #

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.

xa_update_node_t() #

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.

XA_STATE() #

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.

XA_STATE_ORDER() #

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() allows you to specify the 'order' of the element you want to operate on.`

xas_error() #

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.

xas_set_err() #

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().

xas_invalid() #

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.

xas_valid() #

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.

xas_is_node() #

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.

xas_reset() #

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.

xas_retry() #

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.

xas_reload() #

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() instead.

Return

The entry at this location in the xarray.

xas_set() #

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() to move to an adjacent index.

xas_advance() #

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() if you want to move to an index which is not part of this entry.

xas_set_order() #

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.

xas_set_update() #

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.

xas_next_entry() #

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() is an inline function to optimise xarray traversal for speed. It is equivalent to calling xas_find(), and will call xas_find() for all the hard cases.

Return

The next present entry after the one currently referred to by xas.

xas_next_marked() #

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() is an inline function to optimise xarray traversal for speed. It is equivalent to calling xas_find_marked(), and will call xas_find_marked() for all the hard cases.

Return

The next marked entry after the one currently referred to by xas.

xas_for_each() #

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() first.

xas_for_each_marked() #

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() first.

xas_for_each_conflict() #

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.

xas_prev() #

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(). 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.

xas_next() #

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(). 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.

xas_load() #

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() will never expand the tree.

If the xa_state is set up to operate on a multi-index entry, 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.

xas_nomem() #

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(). If 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.

xas_free_nodes() #

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.

xas_create_range() #

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.

xas_store() #

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.

xas_get_mark() #

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.

xas_set_mark() #

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.

xas_clear_mark() #

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.

xas_init_marks() #

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.

xas_split_alloc() #

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(). 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.

xas_split() #

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.

xas_try_split_min_order() #

unsigned int xas_try_split_min_order(unsigned int order)

Minimal split order xas_try_split() can accept

Parameters

  • unsigned int order: Current entry order.

Description

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() supports.

Return

the minimal order xas_try_split() supports

Context

Any context.

xas_try_split() #

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() to get next split order instead of order - 1 if you want to minmize xas_try_split() calls.

Context

Any context. The caller should hold the xa_lock.

xas_pause() #

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(), the xa_for_each() iterator may be more appropriate.

Note that xas_pause() only works for forward iteration. If a user needs to pause a reverse iteration, we will need a xas_pause_rev().

xas_find() #

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().

Return

The entry, if found, otherwise NULL.

xas_find_marked() #

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().

If no entry is found before max is reached, xas is set to the restart state.

Return

The entry, if found, otherwise NULL.

xas_find_conflict() #

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.

xa_load() #

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.

__xa_erase() #

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.

xa_erase() #

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.

__xa_store() #

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() if an error happened.

xa_store() #

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.

__xa_cmpxchg() #

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() if an error happened.

__xa_insert() #

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()) 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.

xa_store_range() #

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.

xas_get_order() #

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.

xa_get_order() #

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.

__xa_alloc() #

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().

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.

__xa_alloc_cyclic() #

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().

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.

__xa_set_mark() #

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.

__xa_clear_mark() #

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.

xa_get_mark() #

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.

xa_set_mark() #

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.

xa_clear_mark() #

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.

xa_find() #

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().

Context

Any context. Takes and releases the RCU lock.

Return

The entry, if found, otherwise NULL.

xa_find_after() #

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().

Context

Any context. Takes and releases the RCU lock.

Return

The pointer, if found, otherwise NULL.

xa_extract() #

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() 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.

xa_delete_node() #

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.

xa_destroy() #

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

  • What is an IRQ?
  • SMP IRQ affinity
  • The irq_domain Interrupt Number Mapping Library
  • IRQ-flags state tracing

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 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

  • ChangeLog:

    • Started by Ingo Molnar <mingo@redhat.com>

    • Update by Max Krasnyansky <maxk@qualcomm.com>

/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):

[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).

[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:

[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 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.

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.

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:

Linear #

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 (~ < 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.

Tree #

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.

No Map #

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.

Legacy #

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.

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:

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:

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.

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.

Debugging #

Most of the internals of the IRQ subsystem are exposed in debugfs by turning CONFIG_GENERIC_IRQ_DEBUGFS on.

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.

struct irq_fwspec #

generic IRQ specifier structure

Definition

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.

struct irq_fwspec_info #

firmware provided IRQ information structure

Definition

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.

struct irq_domain_ops #

Methods for irq_domain objects

Definition

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()).
  • 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().

struct irq_domain #

Hardware interrupt number translation object

Definition

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:

struct irq_domain_info #

Domain information structure

Definition

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.

irq_domain_create_linear() #

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

irq_create_mapping() #

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

irq_resolve_mapping() #

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

irq_find_mapping() #

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

irq_domain_create_hierarchy() #

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.

irq_domain_alloc_irqs() #

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()' documentation.

__irq_domain_alloc_fwnode() #

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.

irq_domain_free_fwnode() #

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.

irq_domain_instantiate() #

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.

irq_domain_remove() #

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.

irq_domain_create_simple() #

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.

irq_find_matching_fwspec() #

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

irq_set_default_domain() #

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(). 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.

irq_get_default_domain() #

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).

irq_create_direct_mapping() #

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.

irq_create_mapping_affinity() #

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.

irq_dispose_mapping() #

void irq_dispose_mapping(unsigned int virq)

Unmap an interrupt

Parameters

  • unsigned int virq: linux irq number of the interrupt to unmap

__irq_resolve_mapping() #

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.

irq_domain_xlate_onecell() #

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.

irq_domain_xlate_twocell() #

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.

irq_domain_xlate_twothreecell() #

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.

irq_domain_xlate_onetwocell() #

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.

irq_domain_translate_onecell() #

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

irq_domain_translate_twocell() #

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.

irq_domain_translate_twothreecell() #

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.

irq_domain_reset_irq_data() #

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

irq_domain_disconnect_hierarchy() #

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.

irq_domain_get_irq_data() #

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

irq_domain_set_hwirq_and_chip() #

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

irq_domain_set_info() #

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

irq_domain_free_irqs_common() #

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

irq_domain_free_irqs_top() #

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

__irq_domain_alloc_irqs() #

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(), is to allocate IRQ descriptor and required hardware resources. The second step, 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.

irq_domain_push_irq() #

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() has been called.

irq_domain_pop_irq() #

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(). Must be called either before request_irq() or after free_irq().

irq_domain_free_irqs() #

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

irq_domain_alloc_irqs_parent() #

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)

irq_domain_free_irqs_parent() #

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

Internal Functions Provided #

This chapter contains the autogenerated documentation of the internal functions.

irq_domain_activate_irq() #

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.

irq_domain_deactivate_irq() #

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

Author: started by Ingo Molnar <mingo@redhat.com>

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

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.

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) to pass information about the preserved state from pre-exec kernel to post-kexec kernel and scratch memory regions to ensure integrity of the preserved memory.

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

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.

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.

See Also #

  • Kexec Handover Usage

Kexec Handover ABI

Peios Kernel / Internals / Core APIs / kho

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.:
/ {
    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.

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.

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:
/ {
        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.

See Also #

  • Kexec Handover Usage

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.

  • Theory of operation
  • How realtime kernels differ
  • Considering hardware
  • Porting an architecture to support PREEMPT_RT

Porting an architecture to support PREEMPT_RT

Peios Kernel / Internals / Core APIs / real-time

Author: Sebastian Andrzej Siewior <bigeasy@linutronix.de>

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.

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.

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

Author: Sebastian Andrzej Siewior <bigeasy@linutronix.de>

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

Sequence locks #

Sequence counters and sequential locks are documented in Documentation/locking/seqlock.rst.

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

Author: Sebastian Andrzej Siewior <bigeasy@linutronix.de>

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.

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/) 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.

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.

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.

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.

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.

Another useful resource is the Linux Real-Time Communication 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

Author: Sebastian Andrzej Siewior <bigeasy@linutronix.de>

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.

Scheduling #

The core principles of Linux scheduling and the associated user-space API are documented in the man page sched(7) sched(7). 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.

Sleeping spin locks #

The various lock types and their behavior under real-time configurations are described in detail in Documentation/locking/locktypes.rst. 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.

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.

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.

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

=============
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.


Atomic types

Peios Kernel / Internals / Core APIs / wrappers


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.

Linux kernel memory barriers

Peios Kernel / Internals / Core APIs / wrappers

                         ============================
                         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

Peios Learn — documentation for Peios software.

Built with Trail.