RAS daemon internal API

Environment and common types

static void ras_trim(char *s, bool remove_commas)

trim leading and trailing whitespace in-place

Parameters

char *s

string to trim

bool remove_commas

remove a pair of surrounding double quotes when true

int ras_set_env(const char *fname)

parse a configuration file and set environment variables

Parameters

const char *fname

path to the configuration file

Description

The accepted format is KEY=value. Empty lines and lines starting with # or ; are ignored. Spaces and tabs are allowed around keys and values. Existing environment variables are left unchanged.

Return

  • 0 - the configuration file was processed

  • -1 - the file could not be opened or a line had an empty key

ARRAY_SIZE

ARRAY_SIZE (arr)

get the number of elements in array arr

Parameters

arr

array to be sized

static inline size_t strscpy(char *dst, const char *src, size_t dsize)

safe implementation of strcpy, with a buffer size

Parameters

char *dst

destination buffer

const char *src

source buffer

size_t dsize

size of the destination buffer

Description

Copy string up to dsize-1 characters. String will end with a ‘0’ character at the end.

Return

  • number of copied non-null characters - src and its null byte fit in dst

  • (size_t)-E2BIG - src did not fit in dsize bytes

static inline size_t strscat(char *dst, const char *src, size_t dsize)

safe implementation of strcat, with a buffer size

Parameters

char *dst

destination buffer

const char *src

source buffer

size_t dsize

size of the destination buffer

Description

Append string until dst is up to dsize-1 characters. String will end with a ‘0’ character at the end.

Return

  • resulting string length - src, including its null byte, fit in dst

  • (size_t)-E2BIG - the concatenated string did not fit in dsize bytes

container_of

container_of (ptr, type, member)

cast a member of a structure out to the containing structure

Parameters

ptr

the pointer to the member.

type

the type of the container struct this is embedded in.

member

the name of the member within the struct.

Description

WARNING: any const qualifier of ptr is lost.

const char *ras_uuid_str(const char *uuid, enum ras_uuid_byte_order order)

format a binary UUID

Parameters

const char *uuid

16-byte UUID

enum ras_uuid_byte_order order

byte order of the UUID fields

Return

a pointer to a static 36-character UUID string. The returned buffer is overwritten by the next call.

loglevel_str

const char *loglevel_str[] = { [LOGLEVEL_EMERG]        = "[EMERG]", [LOGLEVEL_ALERT]        = "[ALERT]", [LOGLEVEL_CRIT]         = "[CRIT]", [LOGLEVEL_ERR]          = "[ERROR]", [LOGLEVEL_WARNING]      = "[WARNING]", [LOGLEVEL_NOTICE]       = "[NOTICE]", [LOGLEVEL_INFO]         = "[INFO]", [LOGLEVEL_DEBUG]        = "[DEBUG]", };

display labels indexed by rasdaemon log severity

Initialization

default: { [LOGLEVEL_EMERG]        = "[EMERG]", [LOGLEVEL_ALERT]        = "[ALERT]", [LOGLEVEL_CRIT]         = "[CRIT]", [LOGLEVEL_ERR]          = "[ERROR]", [LOGLEVEL_WARNING]      = "[WARNING]", [LOGLEVEL_NOTICE]       = "[NOTICE]", [LOGLEVEL_INFO]         = "[INFO]", [LOGLEVEL_DEBUG]        = "[DEBUG]", };

Module and event registries

enum init_level

module initialization and cleanup order

Constants

DB_MODULE

database backends

BASE_EVENT_MODULE

base event decoders and table owners

SUB_EVENT_MODULE

decoders which depend on base event modules

ACTIONS_MODULE

consumers of decoded events

ACTIONS_SUB_MODULE

consumer modules that depend on a base consumer

MAX_LEVELS

number of initialization levels

Description

Initialization proceeds from DB_MODULE to ACTIONS_MODULE. Process-wide cleanup visits the levels in reverse order.

struct ras_module_entry

immutable module registration descriptor

Definition:

struct ras_module_entry {
      const char *name;
      enum init_level level;
      int (*init)(struct ras_module_ctx *ctx);
      void (*cleanup)(struct ras_module_ctx *ctx);
};

Members

name

unique module name

level

initialization level

init

optional initialization callback

cleanup

optional cleanup callback

Description

The descriptor must have static lifetime. On a successful init, cleanup receives the same context and must release all module-owned resources.

struct ras_module_ctx

runtime context owned by the module registry

Definition:

struct ras_module_ctx {
      const struct ras_module_entry *entry;
      struct ras_events *ras;
      void *priv;
};

Members

entry

static module descriptor

ras

event-loop context supplied during initialization

priv

module-private state managed by the callbacks

enum test_group

independently selectable unit-test families

Constants

TEST_GROUP_CORE

generic core tests

TEST_GROUP_EVENTS

architecture-independent event tests

TEST_GROUP_X86_EVENTS

x86 event tests

TEST_GROUP_ARM_EVENTS

Arm event tests

TEST_GROUP_RISCV_EVENTS

RISC-V event tests

TEST_GROUP_ACTIONS

event-consumer tests

TEST_GROUP_DATABASE

generic database tests

TEST_GROUP_DB_SQLITE3

SQLite tests

TEST_GROUP_DB_MYSQL

MySQL/MariaDB tests

TEST_GROUP_DB_POSTGRESQL

PostgreSQL tests

TEST_GROUP_MODULES

module-registry tests

TEST_GROUP_MAX

number of test groups

struct ras_module_entry_runtime

mutable state for a registered module

Definition:

struct ras_module_entry_runtime {
      struct ras_module_ctx ctx;
      bool is_enabled;
      LIST_ENTRY(ras_module_entry_runtime) node;
};

Members

ctx

callback context

is_enabled

whether initialization completed successfully

node

link in ras_modules

ras_modules

static struct module_list ras_modules = LIST_HEAD_INITIALIZER(ras_modules);

registered modules sorted by name

Initialization

default: LIST_HEAD_INITIALIZER(ras_modules);

struct module_test_runtime

one registered unit-test callback

Definition:

struct module_test_runtime {
      enum test_group group;
      int (*run)(void);
      unsigned int priority;
      LIST_ENTRY(module_test_runtime) node;
};

Members

group

selectable test family

run

callback returning zero on success

priority

ascending execution order

node

link in module_tests

module_tests

static struct module_test_list module_tests = LIST_HEAD_INITIALIZER(module_tests);

registered unit tests sorted by priority

Initialization

default: LIST_HEAD_INITIALIZER(module_tests);

static void module_tests_unregister(void)

release unit-test registry wrappers at exit

Parameters

void

no arguments

int module_register(const struct ras_module_entry *entry)

register a static module descriptor

Parameters

const struct ras_module_entry *entry

descriptor which remains valid for the process lifetime

Description

Registration is constructor-safe but not thread-safe. Entries are kept in name order, and duplicate names are rejected.

Return

  • 0 - the module was registered

  • -EINVAL - entry or its name is NULL

  • -EEXIST - the module name is already registered

  • -ENOMEM - wrapper allocation or exit-handler registration failed

bool modules_have_sql_backend(void)

test whether a database module is active

Parameters

void

no arguments

Return

true if an enabled module has level DB_MODULE.

void modules_cleanup_type(enum init_level level)

clean all active modules at one level

Parameters

enum init_level level

level to clean

Description

Cleanup callbacks run in module-name order. Context pointers are cleared after each callback, allowing the module to be initialized again.

static void cleanup_modules(void)

clean all module levels in reverse order

Parameters

void

no arguments

int module_init(struct ras_events *ras, const char *name)

initialize one named module

Parameters

struct ras_events *ras

event-loop context, possibly NULL in isolated tests

const char *name

registered module name

Return

  • 0 - the module initialized successfully or was already active

  • -EINVAL - name is NULL

  • -ENOENT - name is not registered

  • otherwise - the module initialization callback’s error

int module_cleanup(const char *name)

clean one active named module

Parameters

const char *name

registered module name

Return

  • 0 - the active module was cleaned

  • -EINVAL - name is NULL

  • -ENOENT - no active module has name

int modules_init(struct ras_events *ras)

initialize every registered module in level order

Parameters

struct ras_events *ras

event-loop context shared with module callbacks

Description

A failing module is left disabled while initialization continues. Already active modules are skipped.

Return

always 0; individual module failures are logged.

bool module_is_enabled(const char *name)

query a module’s runtime state

Parameters

const char *name

module name

Return

true if the named module is registered and active.

bool module_is_registered(const char *name)

query whether a module name exists

Parameters

const char *name

module name

Return

true if registered; false for NULL or an unknown name.

void modules_unregister(void)

clean modules and release registry wrappers

Parameters

void

no arguments

Description

Called automatically at process exit. Static descriptors are not freed.

int module_test_register(enum test_group group, int (*run)(void), unsigned int priority)

add a unit-test callback

Parameters

enum test_group group

test family

int (*run)(void)

callback returning zero on success

unsigned int priority

ascending order within the registry

Return

  • 0 - the callback was registered

  • -EINVAL - group or run is invalid

  • -EEXIST - run is already registered

  • -ENOMEM - exit-handler registration or wrapper allocation failed

bool module_test_group_is_registered(enum test_group group)

test whether a group has callbacks

Parameters

enum test_group group

group to query

Return

true when at least one callback belongs to group.

int module_test_group_run(enum test_group group)

execute all callbacks in a test group

Parameters

enum test_group group

group to run

Return

number of callbacks which reported failure.

struct ras_module_ctx *module_test_context(const char *name)

expose a module context to unit tests

Parameters

const char *name

registered module name

Return

registry-owned context, or NULL for NULL/unknown names.

enum ras_event_id

decoded event payload types

Constants

MC_EVENT

memory-controller event

MCE_EVENT

x86 machine-check event

AER_EVENT

PCIe AER event

NON_STANDARD_EVENT

non-standard CPER event

ARM_EVENT

Arm processor error event

EXTLOG_EVENT

extended machine-check log event

DEVLINK_EVENT

devlink health event

DISKERROR_EVENT

block I/O error event

MF_EVENT

memory-failure event

SIGNAL_EVENT

fatal-signal event

CXL_POISON_EVENT

CXL poison-list event

CXL_AER_UE_EVENT

CXL uncorrectable AER event

CXL_AER_CE_EVENT

CXL correctable AER event

CXL_OVERFLOW_EVENT

CXL overflow event

CXL_GENERIC_EVENT

generic CXL event

CXL_GENERAL_MEDIA_EVENT

CXL general-media event

CXL_DRAM_EVENT

CXL DRAM event

CXL_MEMORY_MODULE_EVENT

CXL memory-module event

CXL_MEMORY_SPARING_EVENT

CXL memory-sparing event

RERI_EVENT

RISC-V RERI event

NR_EVENTS

number of event identifiers

record_function

Typedef: persist one decoded event

Syntax

int record_function (struct ras_events *ras, void *event)

Parameters

struct ras_events *ras

event-loop and database context

void *event

concrete payload selected by the event descriptor

Return

0 on success or the recorder/backend-specific nonzero error on failure.

enum ras_event_consumer_priority

event-consumer delivery order

Constants

PRI_CPU_ISOLATION

CPU offlining/isolation actions

PRI_MEM_ISOLATION

page and row isolation actions

PRI_POISON_PAGE

poison-page accounting

PRI_PLATFORM_ACTION

platform-specific actions

PRI_REPORTING

external reporting

PRI_DB_RECORD

database persistence

PRI_NORMAL

consumers without ordering constraints

struct ras_event_consumer

immutable decoded-event consumer

Definition:

struct ras_event_consumer {
      const char *name;
      enum ras_event_consumer_priority priority;
      uint64_t events;
      int (*consume)(struct ras_events *ras, int event, void *data);
};

Members

name

unique diagnostic name and equal-priority ordering key

priority

delivery priority

events

bitmap of accepted enum ras_event_id values

consume

synchronous callback; the publisher retains payload ownership

struct ras_event_entry

immutable trace-event registration descriptor

Definition:

struct ras_event_entry {
      const char *group;
      const char *event;
      tep_event_handler_func handler;
      const char *filter;
      const char *(*filter_cb)(struct ras_events *ras);
      int (*prepare)(struct ras_events *ras);
      void (*enabled)(struct ras_events *ras);
      void (*trigger_setup)(void);
      int id;
      int order;
      record_function record;
#ifdef HAVE_UNITTEST;
      enum test_group test_group;
      int (*test)(void);
      unsigned int test_priority;
#endif;
};

Members

group

trace-event subsystem name

event

trace-event name

handler

libtraceevent callback

filter

fixed kernel filter string, or NULL

filter_cb

optional callback producing a kernel filter string

prepare

optional per-event preparation callback

enabled

optional callback after successful event enablement

trigger_setup

optional trace-trigger configuration callback

id

decoded enum ras_event_id

order

ascending handler registration order

record

optional database recorder

test_group

unit-test family when unit tests are enabled

test

optional unit-test callback

test_priority

ascending test execution order

Description

Descriptors have static lifetime. Callback resources are owned by their module and must remain valid until ras_events_cleanup().

struct ras_events

process-wide tracing and database state

Definition:

struct ras_events {
      char tracing[MAX_PATH + 1];
      struct tep_handle       *pevent;
      int page_size;
      unsigned use_uptime: 1;
      unsigned record_events: 1;
      time_t uptime_diff;
      struct ras_db           *db;
      void *db_priv;
      int db_ref_count;
      unsigned int            num_events;
      pthread_mutex_t db_lock;
      struct mce_priv         *mce_priv;
      int socketfd;
      int daemon_active_fd;
      struct tep_event_filter *filters[NR_EVENTS];
};

Members

tracing

mounted tracefs/debugfs tracing directory

pevent

shared trace-event parser

page_size

kernel tracing page size

use_uptime

timestamps use uptime rather than wall clock

record_events

database recording is requested

uptime_diff

wall-clock offset from monotonic uptime

db

active backend connection

db_priv

backend-private per-session data

db_ref_count

number of matching db_open() references

num_events

number of decoded events

db_lock

serializes legacy per-CPU database recorder access

mce_priv

x86 MCE decoder state

socketfd

ABRT reporting socket

daemon_active_fd

lock file descriptor proving daemon ownership

filters

installed filters indexed by enum ras_event_id

struct pthread_data

state for one legacy per-CPU reader thread

Definition:

struct pthread_data {
      pthread_t thread;
      struct tep_handle       *pevent;
      struct ras_events       *ras;
      int cpu;
};

Members

thread

POSIX thread identifier

pevent

thread-local event parser

ras

shared process context

cpu

logical CPU read by this thread

enum hw_event_mc_err_type

memory-controller error classifications

Constants

HW_EVENT_ERR_CORRECTED

corrected error

HW_EVENT_ERR_UNCORRECTED

uncorrected non-fatal error

HW_EVENT_ERR_DEFERRED

deferred error

HW_EVENT_ERR_FATAL

fatal error

HW_EVENT_ERR_INFO

informational event

enum hw_event_aer_err_type

PCIe AER classifications

Constants

HW_EVENT_AER_UNCORRECTED_NON_FATAL

uncorrectable non-fatal event

HW_EVENT_AER_UNCORRECTED_FATAL

uncorrectable fatal event

HW_EVENT_AER_CORRECTED

corrected event

enum ghes_severity

ACPI GHES severity values

Constants

GHES_SEV_NO

no severity

GHES_SEV_CORRECTED

corrected error

GHES_SEV_RECOVERABLE

recoverable error

GHES_SEV_PANIC

fatal error

struct ras_event_consumer_runtime

registry wrapper for a consumer

Definition:

struct ras_event_consumer_runtime {
      const struct ras_event_consumer *consumer;
      LIST_ENTRY(ras_event_consumer_runtime) node;
};

Members

consumer

static consumer descriptor

node

link in event_consumers

event_consumers

static struct ras_event_consumer_list event_consumers = LIST_HEAD_INITIALIZER(event_consumers);

consumers ordered by priority and name

Initialization

default: LIST_HEAD_INITIALIZER(event_consumers);

static void ras_event_consumers_unregister(void)

free registry wrappers at process exit

Parameters

void

no arguments

int ras_event_consumer_register(const struct ras_event_consumer *consumer)

register an immutable event consumer

Parameters

const struct ras_event_consumer *consumer

static descriptor

Description

Registration occurs during constructors and is not thread-safe. Consumers are ordered by ascending priority and then name.

Return

  • 0 - the consumer was registered

  • -EINVAL - consumer or one of its required fields is invalid

  • -EEXIST - its descriptor or name is already registered

  • -ENOMEM - wrapper allocation or exit-handler registration failed

int ras_event_consumer_unregister(const struct ras_event_consumer *consumer)

remove a registered consumer

Parameters

const struct ras_event_consumer *consumer

descriptor previously passed to ras_event_consumer_register()

Return

  • 0 - the consumer was unregistered

  • -EINVAL - consumer is NULL

  • -ENOENT - consumer is not registered

int ras_event_publish(struct ras_events *ras, int event, void *data)

synchronously deliver a decoded event

Parameters

struct ras_events *ras

event-loop context

int event

event identifier from enum ras_event_id

void *data

publisher-owned event payload

Description

Every interested consumer runs even if an earlier consumer fails. data is valid only for the duration of this call. Callers must serialize publishing if a consumer requires it.

Return

  • 0 - every interested consumer succeeded

  • -EINVAL - ras, data, or event is invalid

  • otherwise - the first consumer error in delivery order

choices_disable

char *choices_disable;

comma/space-separated events disabled by config

user_hz

long user_hz;

userspace clock ticks per second

struct ras_event_runtime

registry wrapper for an event descriptor

Definition:

struct ras_event_runtime {
      const struct ras_event_entry *entry;
      LIST_ENTRY(ras_event_runtime) node;
};

Members

entry

static event descriptor

node

link in ras_event_handlers

ras_event_handlers

static struct ras_event_list ras_event_handlers = LIST_HEAD_INITIALIZER(ras_event_handlers);

event descriptors in preparation order

Initialization

default: LIST_HEAD_INITIALIZER(ras_event_handlers);

static int get_mountdir_by_type(char *mount_type, char *tracing_dir, size_t len)

find a mounted filesystem by type

Parameters

char *mount_type

filesystem type from /proc/mounts

char *tracing_dir

destination for the mount path

size_t len

size of tracing_dir

Return

  • 0 - a matching mount was found and copied to tracing_dir

  • -ENOENT - no mount has mount_type

  • otherwise - a negative errno value from opening /proc/mounts

static int get_debugfs_dir(char *tracing_dir, size_t len)

locate the debugfs mount

Parameters

char *tracing_dir

destination path

size_t len

destination size

Return

0 on success or a negative errno value from get_mountdir_by_type().

static int get_tracefs_dir(char *tracing_dir, size_t len)

locate the tracefs mount

Parameters

char *tracing_dir

destination path

size_t len

destination size

Return

0 on success or a negative errno value from get_mountdir_by_type().

static int wait_access(char *path, int ms)

wait for a tracefs node to appear

Parameters

char *path

node path

int ms

maximum wait in milliseconds

Return

  • 0 - path became accessible

  • -1 - the timeout expired

static int open_trace(struct ras_events *ras, char *name, int flags)

open a node relative to the tracing directory

Parameters

struct ras_events *ras

initialized tracing context

char *name

relative tracefs path

int flags

open(2) flags

Return

  • nonnegative - an open file descriptor

  • -E2BIG - the constructed path did not fit

  • -1 - the trace node did not appear before the timeout

  • otherwise - a negative errno value from open(2)

static int get_tracing_dir(struct ras_events *ras)

locate or create rasdaemon’s tracing instance

Parameters

struct ras_events *ras

context receiving the path

Description

Prefers tracefs and falls back to debugfs/tracing. When trace instances are supported, creates or reuses the rasdaemon instance.

Return

  • 0 - ras->tracing contains the usable tracing directory

  • -E2BIG - the constructed path did not fit

  • -EINVAL - the directory could not be opened or the instance created

  • otherwise - a negative mount-discovery error

static bool is_disabled_event(const char *group, const char *event)

check the configured trace-event deny list

Parameters

const char *group

trace subsystem

const char *event

trace event name

Return

true if the exact group:event name is disabled.

bool ras_events_test_is_disabled(const char *group, const char *event)

unit-test access to is_disabled_event()

Parameters

const char *group

trace subsystem

const char *event

trace event name

Return

true if disabled by choices_disable.

static int __toggle_ras_mc_event(struct ras_events *ras, const char *group, const char *event, int enable)

enable or disable one kernel trace event

Parameters

struct ras_events *ras

tracing context

const char *group

trace subsystem

const char *event

trace event name

int enable

nonzero to enable unless configured disabled

Return

  • 0 - the event state was written successfully

  • -EIO - write(2) reported that no bytes were written

  • otherwise - a negative/open failure or the write(2) failure value

int toggle_ras_mc_event(int enable)

toggle every registered RAS trace event

Parameters

int enable

nonzero to enable events, zero to disable them

Return

  • 0 - every registered event was toggled

  • -EINVAL - tracing setup or at least one event toggle failed

  • otherwise - the negative allocation errno from calloc(3)

static int filter_ras_mc_event(struct ras_events *ras, const char *group, const char *event, const char *filter_str)

install a kernel-side trace-event filter

Parameters

struct ras_events *ras

tracing context

const char *group

trace subsystem

const char *event

trace event name

const char *filter_str

kernel filter expression

Return

  • 0 - the filter was written successfully

  • -EIO - write(2) reported that no bytes were written

  • otherwise - a negative/open failure or the write(2) failure value

int ras_event_filter(struct ras_events *ras, const char *group, const char *event, const char *filter)

install a kernel filter for a registered event

Parameters

struct ras_events *ras

tracing context

const char *group

trace subsystem

const char *event

trace event name

const char *filter

kernel filter expression

Return

the result of installing filter through filter_ras_mc_event().

static int get_pagesize(struct ras_events *ras, struct tep_handle *pevent)

parse the trace ring-buffer page header

Parameters

struct ras_events *ras

tracing context

struct tep_handle *pevent

event parser receiving header metadata

Return

4096, after parsing the page header when it is available.

static void parse_ras_data(struct pthread_data *pdata, struct kbuffer *kbuf, void *data, unsigned long long time_stamp)

dispatch one raw ring-buffer record

Parameters

struct pthread_data *pdata

reader state

struct kbuffer *kbuf

loaded kernel ring buffer

void *data

current record payload

unsigned long long time_stamp

record timestamp

static int get_num_cpus(struct ras_events *ras)

obtain the number of online logical CPUs

Parameters

struct ras_events *ras

tracing context (unused)

Return

the positive number of online logical CPUs. Failure triggers an assertion.

static int set_buffer_percent(struct ras_events *ras, int percent)

configure the trace-buffer poll wake threshold

Parameters

struct ras_events *ras

tracing context

int percent

percentage written to tracefs

Return

  • 0 - the percentage was written

  • -EINVAL - the node could not be opened or written

static int read_ras_event_all_cpus(struct pthread_data *pdata, unsigned int n_cpus)

poll all per-CPU trace pipes in one thread

Parameters

struct pthread_data *pdata

array containing at least n_cpus reader contexts

unsigned int n_cpus

number of CPU pipes

Description

SIGINT, SIGTERM, SIGHUP, and SIGQUIT are blocked while polling and restored before return. All file descriptors and buffers are released on every path.

Return

  • 0 - an expected shutdown signal was received

  • LEGACY_KERNEL - polling appears unsupported and callers should fall back

  • -ENOMEM - a page or kernel-buffer decoder could not be allocated

  • -EINVAL - a polling, read, or setup failure occurred

static int read_ras_event(int fd, struct pthread_data *pdata, struct kbuffer *kbuf, void *page)

read one legacy per-CPU trace pipe indefinitely

Parameters

int fd

trace_pipe_raw descriptor

struct pthread_data *pdata

CPU reader state

struct kbuffer *kbuf

reusable kernel-buffer decoder

void *page

reusable page-sized input buffer

Description

Cancellation is disabled while the shared database lock is held.

Return

-EINVAL on read failure; otherwise the loop does not return.

struct reader_cleanup

cancellation-owned per-CPU reader resources

Definition:

struct reader_cleanup {
      struct pthread_data *pdata;
      struct kbuffer *kbuf;
      void *page;
      int fd;
};

Members

pdata

reader state

kbuf

kernel-buffer decoder

page

raw input allocation

fd

trace pipe descriptor

static void cleanup_ras_events_cpu(void *arg)

pthread cleanup handler for a CPU reader

Parameters

void *arg

struct reader_cleanup pointer

static void *handle_ras_events_cpu(void *priv)

legacy reader thread entry point

Parameters

void *priv

struct pthread_data pointer

Return

always NULL after its cleanup handler releases reader resources.

static int select_tracing_timestamp(struct ras_events *ras)

prefer the trace uptime clock

Parameters

struct ras_events *ras

context receiving clock-selection state

Description

Unsupported or unwritable uptime clocks are nonfatal and retain the kernel default. /proc/uptime is used to compute the wall-clock offset.

Return

  • 0 - uptime was selected or the kernel clock was retained as a fallback

  • -EINVAL - trace_clock could not be opened/read or clock data was malformed

static bool check_event_exist(struct ras_events *ras, const char *group, const char *event)

test for an event directory in tracefs

Parameters

struct ras_events *ras

tracing context

const char *group

trace subsystem

const char *event

trace event name

Return

true when the directory exists.

static void ras_events_unregister(void)

release event-registry wrappers at process exit

Parameters

void

no arguments

int ras_event_record(struct ras_events *ras, int event_id, void *data)

invoke the recorder registered for an event type

Parameters

struct ras_events *ras

event/database context

int event_id

enum ras_event_id

void *data

concrete event payload

Return

  • 0 - a matching event has no recorder or its recorder succeeded

  • -EINVAL - ras, data, or event_id is invalid

  • -ENOENT - no registered descriptor has event_id

  • otherwise - the matching recorder’s error

static const struct ras_event_entry *ras_event_test_find(const char *group, const char *name)

locate an event descriptor for unit tests

Parameters

const char *group

trace subsystem

const char *name

trace event name

Return

registry-owned descriptor or NULL.

tep_event_handler_func ras_event_test_handler(const char *group, const char *event)

resolve a registered trace callback for tests

Parameters

const char *group

trace subsystem

const char *event

trace event name

Return

handler callback or NULL when not registered.

int ras_event_register(const struct ras_event_entry *entry)

register a static trace-event descriptor

Parameters

const struct ras_event_entry *entry

descriptor with process lifetime

Description

Entries are sorted by ras_event_entry.order, group, and event. Registration is constructor-safe but not thread-safe. Associated tests are registered as part of the same operation.

Return

  • 0 - the event and any associated test were registered

  • -EINVAL - entry or one of its required fields is invalid

  • -EEXIST - its trace pair or associated test callback is already registered

  • -ENOMEM - wrapper allocation or exit-handler registration failed

  • otherwise - the associated test-registration error

static int add_event_handler(struct ras_events *ras, struct tep_handle *pevent, unsigned int page_size, const char *group, const char *event, tep_event_handler_func func, const char *filter_str, int id)

parse, register, filter, and enable one trace event

Parameters

struct ras_events *ras

tracing context

struct tep_handle *pevent

event parser

unsigned int page_size

initial format-read allocation size

const char *group

trace subsystem

const char *event

trace event name

tep_event_handler_func func

libtraceevent callback

const char *filter_str

optional userspace filter expression

int id

enum ras_event_id used to store the allocated filter

Return

  • 0 - the handler was registered and its trace event enabled

  • EVENT_DISABLED - its format node is absent or it is configured off

  • -EOVERFLOW - the dynamically grown format buffer would overflow

  • otherwise - a negative discovery, I/O, parsing, filter, or enable error

Description

A filter stored in ras is freed by ras_events_cleanup().

int ras_events_prepare(struct ras_events *ras, int record_events)

initialize tracing and all registered event handlers

Parameters

struct ras_events *ras

zero-initialized process context

int record_events

enable database recording consumers

Description

The caller owns ras and must call ras_events_cleanup() after a successful call, including if a later database/module initialization step fails. Individual unsupported events are logged and skipped.

Return

  • 0 - basic preparation completed; unsupported individual events were skipped

  • otherwise - a negative tracing-setup or parser-allocation error

void ras_events_cleanup(struct ras_events *ras)

release resources allocated during event preparation

Parameters

struct ras_events *ras

process context, or NULL

Description

The operation is idempotent after initialization and clears owned pointers. It does not free ras or clean module-owned resources.

int handle_ras_events(struct ras_events *ras)

run the trace reader until shutdown or failure

Parameters

struct ras_events *ras

successfully prepared event context

Description

Modern kernels use a single polling reader. Kernels without working poll support fall back to one cancellable thread per CPU; handler/database access is serialized in that mode. This function always calls ras_events_cleanup() before returning.

Return

  • 0 - polling stopped due to an expected shutdown signal

  • -EINVAL - ras is invalid, no events were enabled, or polling failed

  • -ENOMEM - per-CPU reader state could not be allocated

  • LEGACY_KERNEL - all fallback reader threads exited without setup failure

  • otherwise - a negated pthread initialization or creation error

Core utilities

struct field

decode an indexed bit field

Definition:

struct field {
      unsigned int start_bit;
      char **str;
      unsigned int stringlen;
};

Members

start_bit

least-significant bit of the field

str

strings indexed by the decoded value

stringlen

number of entries in str

struct numfield

decode a numeric bit field

Definition:

struct numfield {
      unsigned int start, end;
      char *name;
      char *fmt;
      int force;
};

Members

start

least-significant bit of the field

end

most-significant bit of the field

name

label written before the value

fmt

printf format for the value

force

emit the field even when its value is zero

static inline int test_prefix(int nr, uint32_t value)

test whether a value has a unary prefix

Parameters

int nr

number of low-order bits below the prefix

uint32_t value

value to inspect

Return

nonzero when shifting value by nr produces one.

unsigned int bitfield_msg(char *buf, size_t len, const char *const *bitarray, unsigned int array_len, unsigned int bit_offset, unsigned int ignore_bits, uint64_t status)

format the names of set bits

Parameters

char *buf

destination buffer

size_t len

size of buf

const char * const *bitarray

array mapping bit positions to names

unsigned int array_len

number of entries in bitarray

unsigned int bit_offset

position of the first described bit in status

unsigned int ignore_bits

mask which suppresses output when any masked bit is set

uint64_t status

value to decode

Description

Unknown set bits are formatted as BITn. Output is truncated before a name which does not fit, and buf is always terminated when len is nonzero.

Return

number of bytes written, excluding the terminating null byte.

static uint64_t bitmask(uint64_t i)

produce a mask covering a zero-based maximum value

Parameters

uint64_t i

maximum value to represent

Return

the smallest all-ones mask greater than or equal to i.

void decode_bitfield(struct mce_event *e, uint64_t status, struct field *fields)

append decoded symbolic fields to an MCE event

Parameters

struct mce_event *e

event receiving decoded messages

uint64_t status

machine-check status value

struct field *fields

null-terminated field description array

void decode_numfield(struct mce_event *e, uint64_t status, struct numfield *fields)

append decoded numeric fields to an MCE event

Parameters

struct mce_event *e

event receiving decoded messages

uint64_t status

machine-check status value

struct numfield *fields

null-terminated numeric field description array

struct queue_node

one time-stamped queue entry

Definition:

struct queue_node {
      time_t time;
      unsigned int value;
      struct queue_node *next;
};

Members

time

entry timestamp

value

caller-owned numeric value

next

next entry, or NULL at the tail

FIFO queue of struct queue_node objects

Definition:

struct link_queue {
      struct queue_node *head;
      struct queue_node *tail;
      int size;
};

Members

head

first entry, or NULL when empty

tail

last entry, or NULL when empty

size

current number of entries

int is_empty(struct link_queue *queue)

test whether a queue has no entries

Parameters

struct link_queue *queue

queue to inspect, or NULL

Return

nonzero when queue is NULL or empty.

struct link_queue *init_queue(void)

allocate an empty queue

Parameters

void

no arguments

Return

a queue owned by the caller, or NULL on allocation failure.

void clear_queue(struct link_queue *queue)

free every node in a queue

Parameters

struct link_queue *queue

queue to empty, or NULL

Description

The queue object remains valid and can be reused.

void free_queue(struct link_queue *queue)

destroy a queue and all its nodes

Parameters

struct link_queue *queue

queue to destroy, or NULL

void push(struct link_queue *queue, struct queue_node *node)

append a node to a queue

Parameters

struct link_queue *queue

valid queue

struct queue_node *node

detached node whose ownership transfers to queue

Description

Both arguments must be non-NULL.

int pop(struct link_queue *queue)

remove and free the first queue node

Parameters

struct link_queue *queue

queue to modify

Return

  • 0 - the first node was removed and freed

  • -1 - queue is NULL or empty

struct queue_node *front(struct link_queue *queue)

obtain the first queue node without removing it

Parameters

struct link_queue *queue

queue to inspect

Return

a queue-owned node, or NULL if queue is NULL or empty.

struct queue_node *node_create(time_t time, unsigned int value)

allocate a detached queue node

Parameters

time_t time

timestamp stored in the node

unsigned int value

numeric value stored in the node

Return

a caller-owned node, or NULL on allocation failure.

struct rb_node

intrusive red-black tree node

Definition:

struct rb_node {
      unsigned long  rb_parent_color;
#define RB_RED          0;
#define RB_BLACK        1;
      struct rb_node *rb_right;
      struct rb_node *rb_left;
};

Members

rb_parent_color

packed parent pointer and color bits

rb_right

right child

rb_left

left child

struct rb_root

red-black tree root

Definition:

struct rb_root {
      struct rb_node *rb_node;
};

Members

rb_node

root node, or NULL for an empty tree

static inline void rb_set_parent(struct rb_node *rb, struct rb_node *p)

update a node’s parent without changing its color

Parameters

struct rb_node *rb

node to update

struct rb_node *p

new parent, or NULL

static inline void rb_set_color(struct rb_node *rb, int color)

update a node’s color without changing its parent

Parameters

struct rb_node *rb

node to update

int color

RB_RED or RB_BLACK

attach an unbalanced red-black tree leaf

Parameters

struct rb_node *node

detached node to initialize

struct rb_node *parent

parent selected by the caller’s ordered search

struct rb_node **rb_link

child link in parent, or root link, receiving node

Description

Call rb_insert_color() after linking to restore tree invariants.

static void __rb_rotate_left(struct rb_node *node, struct rb_root *root)

rotate a subtree left during rebalancing

Parameters

struct rb_node *node

subtree root

struct rb_root *root

tree root

static void __rb_rotate_right(struct rb_node *node, struct rb_root *root)

rotate a subtree right during rebalancing

Parameters

struct rb_node *node

subtree root

struct rb_root *root

tree root

void rb_insert_color(struct rb_node *node, struct rb_root *root)

rebalance a tree after insertion

Parameters

struct rb_node *node

node previously attached with rb_link_node()

struct rb_root *root

tree root

static void __rb_erase_color(struct rb_node *node, struct rb_node *parent, struct rb_root *root)

restore red-black invariants after deletion

Parameters

struct rb_node *node

replacement child, possibly NULL

struct rb_node *parent

parent of node

struct rb_root *root

tree root

void rb_erase(struct rb_node *node, struct rb_root *root)

remove a node from a red-black tree

Parameters

struct rb_node *node

linked node to remove

struct rb_root *root

tree root

Description

The caller retains ownership of node.

struct rb_node *rb_first(const struct rb_root *root)

find the first node in sort order

Parameters

const struct rb_root *root

tree root

Return

first node, or NULL when empty.

struct rb_node *rb_last(const struct rb_root *root)

find the last node in sort order

Parameters

const struct rb_root *root

tree root

Return

last node, or NULL when empty.

struct rb_node *rb_next(const struct rb_node *node)

find a node’s in-order successor

Parameters

const struct rb_node *node

linked tree node

Return

next node, or NULL at the end/detached marker.

struct rb_node *rb_prev(const struct rb_node *node)

find a node’s in-order predecessor

Parameters

const struct rb_node *node

linked tree node

Return

previous node, or NULL at the beginning/detached marker.

void rb_replace_node(struct rb_node *victim, struct rb_node *new, struct rb_root *root)

replace a node without rebalancing

Parameters

struct rb_node *victim

linked node to replace

struct rb_node *new

detached replacement node

struct rb_root *root

tree root

Description

The replacement inherits all links and color. The caller retains victim.

stdout_is_vt

static bool stdout_is_vt = false;

whether standard output is attached to a terminal

Initialization

default: false;

mock_output

bool mock_output = false;

redirect log output to the in-memory test buffer

Initialization

default: false;

mock_log_buf

char *mock_log_buf = NULL;

dynamically allocated test log buffer

Initialization

default: NULL;

mock_log_len

size_t mock_log_len = 0;

number of bytes stored in mock_log_buf

Initialization

default: 0;

reset_color

const char *reset_color = "";

terminal escape used to reset log colors

Initialization

default: "";

void ras_logger_clean(void)

release the in-memory test log buffer

Parameters

void

no arguments

void ras_logger_flush(void)

write and release the in-memory test log buffer

Parameters

void

no arguments

enum ansi_color

symbolic terminal colors

Constants

GREEN

green text

RED

red text

YELLOW

yellow text

RESET

terminal default

ANSI_MAX_COLORS

number of symbolic colors

codes

codes is the static table of terminal escapes indexed by syslog severity.

const char *log_color(int color)

obtain the terminal escape for a log severity

Parameters

int color

syslog severity

Return

an escape sequence when standard output is a terminal and color is a valid syslog severity up to LOG_DEBUG; otherwise an empty string.

ras_logger_init

ras_logger_init() is the static constructor which initializes terminal color state before main().

struct event_trigger

event-specific external trigger setup

Definition:

struct event_trigger {
      const char *name;
      void (*setup)(void);
};

Members

name

event name

setup

callback which configures the trigger

void run_trigger(const char *trigger, char *argv[], char **env, const char *reporter)

synchronously execute an external event reporter

Parameters

const char *trigger

executable path

char *argv[]

null-terminated argument vector

char **env

null-terminated environment vector

const char *reporter

reporter name used in diagnostics

Description

The parent waits for the child. Fork and child-status failures are logged; they are not returned to the caller.

const char *trigger_check(const char *s)

resolve and validate a trigger executable

Parameters

const char *s

trigger name or path

Description

When TRIGGER_DIR is set, the returned path is newly allocated and lives for the remainder of the process. Otherwise the return value aliases s.

Return

an executable, readable path, or NULL if validation fails.

Process entry point

rasdaemon_conf

rasdaemon_conf is the static default configuration file path.

argp_program_version

const char *argp_program_version = PROG_NAME " " VERSION;

version string exposed by argp

Initialization

default: PROG_NAME " " VERSION;

argp_program_bug_address

const char *argp_program_bug_address = "Mauro Carvalho Chehab <mchehab@kernel.org>";

maintainer address exposed by argp

Initialization

default: "Mauro Carvalho Chehab <mchehab**kernel.org**>";

struct arguments

parsed command-line state

Definition:

struct arguments {
      int record_events;
      int enable_ras;
      int foreground;
      int offline;
      char *cfg_file;
};

Members

record_events

database recording request count

enable_ras

positive to enable or negative to disable tracing

foreground

nonzero to avoid daemonizing

offline

nonzero to decode a supplied offline MCE

cfg_file

explicit environment configuration path

enum OFFLINE_ARG_KEYS

argp keys for offline MCE fields

Constants

SMCA

enable AMD SMCA decoding

MODEL

CPU model

FAMILY

CPU family

BANK_NUM

machine-check bank

IPID_REG

SMCA IPID register

STATUS_REG

machine-check status register

SYNDROME_REG

SMCA syndrome register

event

struct ras_mc_offline_event event;

command-line offline MCE payload

static error_t parse_opt(int k, char *arg, struct argp_state *state)

parse top-level rasdaemon options

Parameters

int k

argp option key

char *arg

optional argument text

struct argp_state *state

argp parser state containing struct arguments

Return

  • 0 - the option was handled

  • ARGP_ERR_UNKNOWN - k is not a top-level option

static error_t parse_opt_offline(int key, char *arg, struct argp_state *state)

parse offline MCE register options

Parameters

int key

argp option key

char *arg

register value text

struct argp_state *state

argp parser state (unused)

Return

  • 0 - the option was handled

  • ARGP_ERR_UNKNOWN - key is not an offline-MCE option

int main(int argc, char *argv[])

rasdaemon process entry point

Parameters

int argc

argument count

char *argv[]

argument vector

Description

Initializes modules, tracing, and the optional database session in ownership order. Cleanup reverses that order after event handling ends.

Return

  • EXIT_SUCCESS - the requested operation completed

  • EXIT_FAILURE - initialization or database setup/cleanup failed

  • -1 - argp did not produce a valid post-parse argument index

  • -errno - the main RAS context could not be allocated

Database API

enum db_field_type

Supported database column types

Constants

DB_TYPE_SERIAL

Auto-increment integer

DB_TYPE_INT32

32-bit signed integer

DB_TYPE_INT64

64-bit signed integer

DB_TYPE_TIMESTAMP

ISO timestamp (string or numeric value)

DB_TYPE_TEXT

Variable-length string

DB_TYPE_BLOB

Binary data

static inline const char *env_or(const char *name, const char *def)

ancillary routine to get an environment with a default value

Parameters

const char *name

name of the variable

const char *def

default value

Return

a nonempty environment value, otherwise def. The environment owns a value returned from getenv(3).

static inline int env_or_bool(const char *name, int def)

get a boolean from an environment variable

Parameters

const char *name

name of the variable

int def

default value (0 or 1)

Return

  • def - the environment variable is unset or empty

  • false - its value is 0, false, or no

  • true - it has any other nonempty value

static inline int env_or_int(const char *name, int def)

get an integer from an environment variable

Parameters

const char *name

name of the variable

int def

default value

Return

the parsed nonzero integer, or def when unset, empty, nonnumeric, or parsed as zero.

struct db_fields

Definition of a single column in a table descriptor

Definition:

struct db_fields {
      const char              *name;
      enum db_field_type      type;
      bool is_pk;
      bool create_index;
};

Members

name

Column name identifier

type

Data type enumeration for binding logic

is_pk

True if this field is the primary key (affects SQL generation)

create_index

True if an index should be created for this field

struct db_table_descriptor

Metadata describing a database table schema

Definition:

struct db_table_descriptor {
      const char                      *name;
      const struct db_fields          *fields;
      size_t num_fields;
};

Members

name

Name of the table in the database

fields

Array of column definitions

num_fields

Total count of columns in the array

struct db_desc_and_stmt

A table descriptor and its prepared statement

Definition:

struct db_desc_and_stmt {
      const struct db_table_descriptor *desc;
      struct ras_stmt *stmt;
};

Members

desc

Database table schema

stmt

Storage for the prepared insert statement

struct db_backend

Specify what DB backend will be used

Definition:

struct db_backend {
      const char *name;
      void *conn_parms;
};

Members

name

Name of backend driver

conn_parms

Backend-specific connection parameters

int db_backend_enable(const char *name)

select backend to use

Parameters

const char *name

name of the backend. NULL to allow selecting via env vars

Return

  • 0 - database support is disabled or the backend was selected

  • -1 - the requested backend is unavailable

const char *db_list_available_backends(void)

list registered database backends

Parameters

void

no arguments

Description

The returned process-global buffer is overwritten by later calls and is not safe for concurrent use.

Return

a comma-separated list of backend names, or an empty string when none are registered or database support is disabled.

int ras_db_table_register(struct ras_module_ctx *ctx, struct db_desc_and_stmt *entry)

Register one module-owned table pair

Parameters

struct ras_module_ctx *ctx

Owning module context

struct db_desc_and_stmt *entry

Descriptor and statement pair that remains valid until unregistered

Description

Registration does not open the table. The owner must keep entry and its descriptor alive until ras_db_table_unregister().

Return

  • 0 - database support is disabled or the table was registered

  • -EINVAL - ctx, entry, or entry->desc is NULL

  • -EEXIST - the entry or its descriptor is already registered

  • -ENOMEM - registry-wrapper allocation failed

void ras_db_table_unregister(struct ras_module_ctx *ctx)

Remove every table pair owned by a module

Parameters

struct ras_module_ctx *ctx

Owning module context

Description

The owner must finalize its statements before calling this function.

ras_db_table_test_callback

Typedef: visit a registered table descriptor

Syntax

int ras_db_table_test_callback (const struct db_table_descriptor *desc, void *data)

Parameters

const struct db_table_descriptor *desc

registry-owned persistent descriptor

void *data

caller context

Return

  • 0 - continue iteration

  • nonzero - stop iteration and return this value to the caller

int ras_db_table_test_foreach(ras_db_table_test_callback callback, void *data)

visit each registered table in order

Parameters

ras_db_table_test_callback callback

visitor callback

void *data

opaque caller context

Description

Available only to unit-test builds. The registry remains owner of every descriptor and must not be modified from the callback.

Return

  • 0 - database support is disabled or every callback invocation succeeded

  • -EINVAL - callback is NULL while database support is enabled

  • otherwise - the first nonzero callback result

int db_bind(const struct db_table_descriptor *db_tab, struct ras_stmt *stmt, int pos, uint64_t value, int len)

Bind one field value to a prepared statement

Parameters

const struct db_table_descriptor *db_tab

Database table descriptor

struct ras_stmt *stmt

Statement handle provided by the backend

int pos

Starting position index placeholder (starts with 1)

uint64_t value

Pointer to raw data buffer containing all field values

int len

Length of the buffer (optional, depends on implementation)

Return

  • 0 - database support/backend is disabled or the value was bound

  • -1 - pos does not identify a non-serial field

  • -EINVAL - stmt is NULL while a backend is active

  • otherwise - the backend binding error

const char *db_get_sql_type(enum db_field_type type, bool is_pk)

Return SQL column type string for a given field type

Parameters

enum db_field_type type

Field type descriptor from the enum db_field_type

bool is_pk

True if the column is declared as primary key in SQL

Return

a backend-owned SQL type string, such as TEXT or BLOB; an empty string when database support or an active backend is absent.

int db_eval_stmt(struct ras_stmt *stmt, const char *tab_name)

Execute a prepared SQL statement

Parameters

struct ras_stmt *stmt

Prepared statement handle to execute

const char *tab_name

Name of the table whose data should be read/written

Return

  • 0 - database support/backend is disabled or execution succeeded

  • -EINVAL - stmt is NULL while a backend is active

  • otherwise - the backend execution error

int db_create_table(struct ras_db *db, const struct db_table_descriptor *db_tab)

Create a new database table from its descriptor

Parameters

struct ras_db *db

Database connection handle (opaque)

const struct db_table_descriptor *db_tab

Table descriptor containing the schema to create

Return

0 when database support/backend is disabled or on success; otherwise the backend table-creation error.

int db_alter_table(struct ras_db *db, struct ras_stmt **stmt, const struct db_table_descriptor *db_tab)

Modify an existing database table structure

Parameters

struct ras_db *db

Database connection handle (opaque)

struct ras_stmt **stmt

Output pointer for a prepared statement describing the change

const struct db_table_descriptor *db_tab

Table descriptor containing the new schema to apply

Return

0 when database support/backend is disabled or on success; otherwise the backend table-alteration error.

int db_prepare_insert_stmt(struct ras_db *db, struct ras_stmt **stmt, const struct db_table_descriptor *db_tab)

Prepare a generic SQL statement for execution

Parameters

struct ras_db *db

Database connection handle (opaque)

struct ras_stmt **stmt

Output pointer for the prepared statement handle

const struct db_table_descriptor *db_tab

Table descriptor providing context for the query

Return

0 when database support/backend is disabled or on success; otherwise the backend statement-preparation error.

int db_exec_sql(struct ras_db *db, const char *sql)

Execute a SQL statement

Parameters

struct ras_db *db

Database connection handle

const char *sql

SQL command to execute

Return

0 when database support/backend is disabled or on success; otherwise the backend execution error.

int db_finalize(struct ras_stmt *stmt)

Finalize and release resources for a prepared statement

Parameters

struct ras_stmt *stmt

Prepared statement handle to finalize

Return

0 when database support/backend is disabled, stmt is NULL, or finalization succeeds; otherwise the backend finalization error.

int db_cpu_finalize(unsigned int cpu, struct ras_stmt *stmt, const char *name)

CPU-local cleanup of a prepared statement resource

Parameters

unsigned int cpu

Logical CPU number for per-CPU bookkeeping (opaque)

struct ras_stmt *stmt

Prepared statement handle to finalize

const char *name

Name string for the resource being cleaned up

Return

0 when database support/backend is disabled or on success; otherwise the backend finalization error.

int db_open(struct db_backend *backend, unsigned int cpu, struct ras_events *ras, size_t size_priv)

Open and initialize a database connection

Parameters

struct db_backend *backend

Explicit backend for tests, or NULL for the selected backend

unsigned int cpu

Logical CPU number for per-CPU bookkeeping (opaque)

struct ras_events *ras

RAS events context (opaque)

size_t size_priv

Optional private allocation size; zero allocates no private data

Description

Opens the process-wide backend on the first reference. Further matching calls increment a reference count; the final db_close() releases it.

Return

  • 0 - database support is disabled, the session opened, or its reference count was incremented

  • -EINVAL - ras is NULL or no backend was explicitly/implicitly selected

  • -ENOMEM - size_priv bytes could not be allocated

  • -1 - the selected backend is unavailable or its open callback failed

  • otherwise - the table-opening error after the backend connection opened

int db_close(unsigned int cpu, struct ras_events *ras)

Close and release resources of an open database connection

Parameters

unsigned int cpu

Logical CPU number for per-CPU bookkeeping (opaque)

struct ras_events *ras

RAS events context (opaque)

Return

  • 0 - database support/backend is disabled, a reference remains, or the final close succeeded

  • -EINVAL - db_close() has no matching open reference

  • -1 - table finalization failed and the backend close succeeded

  • otherwise - the backend close error

selected_backend

static const char *selected_backend = NULL;

name selected for the next implicit db_open()

Initialization

default: NULL;

ras_db_ops

static const struct ras_db_backend_ops *ras_db_ops = NULL;

operations for the currently open process-wide backend

Initialization

default: NULL;

struct ras_db_backend_runtime

registry wrapper for a database backend

Definition:

struct ras_db_backend_runtime {
      const struct ras_db_backend_entry *entry;
      LIST_ENTRY(ras_db_backend_runtime) node;
};

Members

entry

static backend descriptor

node

link in ras_db_backends

ras_db_backends

static struct ras_db_backend_list ras_db_backends = LIST_HEAD_INITIALIZER(ras_db_backends);

registered database backends sorted by name

Initialization

default: LIST_HEAD_INITIALIZER(ras_db_backends);

rasdaemon_hostname

const char *rasdaemon_hostname = "";

hostname attached to remote database records

Initialization

default: "";

rasdaemon_hostname_buf

static char rasdaemon_hostname_buf[256];

storage for the system hostname

add_hostname

static bool add_hostname = false;

whether the active backend needs a hostname column

Initialization

default: false;

int db_backend_register(struct ras_db_backend_entry *entry)

register a static database backend descriptor

Parameters

struct ras_db_backend_entry *entry

complete descriptor which remains valid until unregistered

Description

Registration is performed by module initialization and is not thread-safe. Backends are sorted by name and duplicate names are rejected.

Return

  • 0 - the backend was registered

  • -EINVAL - entry or its required operations are incomplete

  • -EEXIST - its name is already registered

  • -ENOMEM - registry-wrapper allocation failed

int db_backend_unregister(struct ras_db_backend_entry *entry)

remove a database backend descriptor

Parameters

struct ras_db_backend_entry *entry

descriptor previously registered

Return

  • 0 - the backend was unregistered

  • -EINVAL - entry is NULL

  • -EBUSY - entry is the active backend

  • -ENOENT - entry is not registered

bool db_backend_is_registered(const char *name)

query a database backend name

Parameters

const char *name

backend name

Return

true when registered; false for NULL or an unknown name.

static void db_get_rasdaemon_hostname(void)

initialize the remote-record hostname

Parameters

void

no arguments

Description

RASDAEMON_HOSTNAME takes precedence over gethostname(). The resulting process-lifetime string is stored in rasdaemon_hostname.

static int db_bind_type(struct ras_stmt *stmt, const enum db_field_type type, int pos, uint64_t value, int len)

bind a value with an explicit portable field type

Parameters

struct ras_stmt *stmt

active prepared statement

const enum db_field_type type

portable field type

int pos

one-based placeholder position

uint64_t value

scalar value or pointer encoded as uint64_t

int len

byte length for variable-sized data

Return

  • 0 - no backend is active or the value was bound

  • -EINVAL - stmt is NULL while a backend is active

  • otherwise - the backend binding error

struct db_mysql_conn_params

MySQL/MariaDB connection parameters

Definition:

struct db_mysql_conn_params {
      const char *host;
      unsigned int port;
      const char *user;
      const char *password;
      const char *database;
      const char *socket;
      unsigned int connect_timeout;
      bool use_ssl;
};

Members

host

Hostname or IP. NULL or empty for a local Unix socket.

port

TCP port (default 3306). Ignored for local socket.

user

Username (default “rasdaemon”).

password

Password (default NULL / empty).

database

Database name (default “rasdaemon”).

socket

Unix socket path for local connections (default “/var/lib/mysql/mysql.sock”).

connect_timeout

Connection timeout in seconds.

use_ssl

Whether TLS is enabled for the connection.

struct db_postgresql_conn_params

PostgreSQL connection parameters

Definition:

struct db_postgresql_conn_params {
      const char *host;
      unsigned int port;
      const char *user;
      const char *password;
      const char *schema;
      const char *database;
      unsigned int connect_timeout;
      bool use_ssl;
      const char *sslmode;
};

Members

host

Hostname or IP. NULL or empty for a local Unix socket.

port

TCP port (default 5432). Ignored for local socket.

user

Username (default “rasdaemon”).

password

Password (default NULL / empty).

schema

Schema to be used (default “rasdaemon”).

database

Database name (default “rasdaemon”).

connect_timeout

Connection timeout in seconds.

use_ssl

Whether TLS is enabled for the connection.

sslmode

libpq TLS policy string.