14.1 Log Buffer Configuration
During the boot phase, the system has not yet completed its core initialization routines, nor has it loaded device drivers. Consequently, messages cannot be exported via standard subsystem drivers. To track the boot sequence, print fault diagnostics, and output debugging traces, the Linux kernel provides the printk() function to facilitate fundamental message logging capabilities during the system bootstrap phase.
Linux utilizes a circular queue topology to store tracking messages targeted for display during the boot sequence. The kernel implements diverse functions to orchestrate queue movement, read operations, write operations, and storage space allocation, all of which are leveraged by the printk() engine. The following sections outline the architecture and operations of this circular queue framework to clarify the log buffer initialization process.
14.1.1 Ring Buffer
The Linux kernel describes the ring structure utilized by the printk engine via the following structural abstraction:
struct printk_ringbuffer {
struct prb_desc_ring desc_ring;
struct prb_data_ring text_data_ring;
atomic_long_t fail;
};
This structure defines the primary header control block of the ring buffer queue. The desc_ring field describes the descriptor ring tracking metadata records, while the text_data_ring field represents the primary data ring buffer used to preserve the literal string text targeted for printing. The fail variable tracks the cumulative count of read or write anomalies encountered.
The layout of the ring buffer header control block is illustrated in Figure 14-1.
Figure 14-1 Structural Layout of the Ring Buffer Header
The collective blueprint of the entire ring buffer architecture is illustrated in Figure 14-2.
Figure 14-2 Monolithic Topology of the Ring Buffer
14.1.1.1 The Descriptor Ring Buffer
The concrete array elements composing the metadata descriptor ring are specified by the following data type:
struct prb_desc_ring {
unsigned int count_bits;
struct prb_desc *descs;
struct printk_info *infos;
atomic_long_t head_id;
atomic_long_t tail_id;
};
Within this tracking control block, count_bits establishes the exact magnitude of the descs array—defining the bit width utilized to index elements inside the descs repository. The literal size of the descs array evaluates to DESC_COUNT = 2^count_bits^. The descs member points to an array of type struct prb_desc, which Linux accesses via a modulo-based circular methodology. Each standalone entry in this array corresponds to a discrete tracking payload, mapping out the base boundary, tail boundary, and active state of the associated record. The infos array stores supplemental metadata descriptors associated with the log entries. Its indices correspond one-to-one with the elements of the descs array, meaning records sharing an identical index value track the exact same message payload. head_id represents the logical sequence index of the most recent descriptor record committed into the descs array, while tail_id tracks the logical index of the oldest valid record retained within the matrix.
The individual elements inside the descs array are formatted as:
struct prb_desc {
atomic_long_t state_var;
struct prb_data_blk_lpos text_blk_lpos;
};
The upper two bits of the state_var variable serve as explicit state bitmasks used to track the operational phase of the matching descriptor entry. This metadata state field accepts the discrete evaluation properties desc_reusable, desc_reserved, desc_committed, and desc_finalized. These represent free space available for reuse, storage space actively held by a writer context, data committed by a writer context but not yet fully visible, and data finalized and available for read consumption, respectively.
The programmatic definitions for these entry state parameters are structured as follows:
enum desc_state {
desc_miss = -1, /* ID mismatch (pseudo state) */
desc_reserved = 0x0, /* reserved, in use by writer */
desc_committed = 0x1, /* committed by writer, could get reopened */
desc_finalized = 0x2, /* committed, no further modification allowed */
desc_reusable = 0x3, /* free, not yet used by any writer */
};
The tracking symbol desc_miss is never preserved inside the literal state_var flag; it merely acts as a programmatic pseudo-state denoting that a matching descriptor entry cannot be located within the ring metadata table.
The remaining bits of state_var specify the logical identification sequence number of the descriptor, whose scale extends far beyond the physical array limits of the ring list. Computing the logical identifier modulo the total array dimension yields the physical array slot location: index = ((state_var << 2) >> 2) % DESC_COUNT. This logical sequence token is concurrently stored at the leading boundary of the corresponding text data block payload.
The structure type for text_blk_lpos is implemented as:
struct prb_data_blk_lpos {
unsigned long begin;
unsigned long next;
};
begin represents the absolute starting memory tracking position of the text payload corresponding to this descriptor block. next indicates the starting position of the subsequent data payload block. By analyzing the values of begin and next, the core subsystem can determine the location and size of the text data described by this entry.
The infos array tracks supplemental metadata records belonging to the matching entry data payload, and its structure is defined as follows:
struct printk_info {
u64 seq; /* sequence number */
u64 ts_nsec; /* timestamp in nanoseconds */
u16 text_len; /* length of text message */
u8 facility; /* syslog facility */
u8 flags:5; /* internal record flags */
u8 level:3; /* syslog level */
u32 caller_id; /* thread id or processor id */
struct dev_printk_info dev_info;
};
The most critical parameters inside this layout are the chronological sequence token seq and the message priority property level. The sequence number is utilized to index and interface with this ring list infrastructure, while users can leverage the log level to filter the specific content targeted for output display.
During initial execution, the element situated at index 0 of the infos repository initializes with a sequence value of 0, whereas all subsequent items possess sequence tokens that match their literal array index slots. Because this framework wraps as a circular loop sequence, each tracking slot is recycled and rewritten multiple times. When an individual slot is reallocated for a new log entry, its sequence number increments by adding DESC_COUNT onto the baseline sequence metric.
The structural arrangement of the descriptor ring queue is illustrated in the diagram below.
Figure 14-3 Structural Layout of the Descriptor Ring
4.1.1.2 The Data Ring Buffer
The data ring buffer is utilized to preserve the literal tracking text targeted for output display. The underlying elements composing this ring queue are described by the following structure:
struct prb_data_ring {
unsigned int size_bits;
char *data;
atomic_long_t head_lpos;
atomic_long_t tail_lpos;
};
Within this tracking structure, size_bits defines the total bit width required to represent the index values used to access elements within the data queue. The queue data container data is implemented as a character array whose absolute capacity evaluates to DATA_SIZE = 2^size_bits^, inside of which the actual string payload is saved. This tracking container is likewise processed using modulo-based circular access logic, where the physical array index is calculated as:
data_index = lpos%DATA_SIZE
Here, lpos represents the logical tracking address of the raw data block, and its boundary scale extends far beyond the physical constraints of DATA_SIZE.
14.1.2 Ring Buffer Operations
The Linux kernel implements a robust suite of functions dedicated to manipulating the core components of the printk ring buffer infrastructure. The function prb_init(struct printk_ringbuffer *rb, char *text_buf, unsigned int textbits, struct prb_desc *descs, unsigned int descbits, struct printk_info *infos) is responsible for initializing a target ring buffer instance rb. Within this interface, text_buf, descs, and infos represent externally allocated backing storage structures supplied to the ring subsystem, which act respectively as the raw text data ring buffer, the descriptor array, and the metadata info array. The parameter descbits configures the bit width utilized to index elements inside the descs tracking structure, while textbits defines the bit width utilized to index elements inside the data array within the data ring structure. This initialization routine hooks the pointers text_buf, descs, and infos onto the corresponding tracking fields of rb, establishes the initial operational bounds of the descriptor and info queues via descbits, and configures the initial limits of the text data ring via textbits.
Once the structural scaffolding of the ring buffer has been established, the subsystem can execute concurrent read and write operations against it. Prior to executing a write operation against an existing ring buffer instance rb, a tracking variable r of the following type must be declared:
struct printk_record {
struct printk_info *info;
char *text_buf;
unsigned int text_buf_size;
};
Following the declaration of r, the function prb_rec_init_wr(&r, len) is invoked to configure the text_buf_size field to match the explicit buffer size allocation requirements specified by len. The function prb_rec_init_wr() is implemented as follows:
void prb_rec_init_wr(struct printk_record *r, unsigned int text_buf_size)
{
r->info = NULL;
r->text_buf = NULL;
r->text_buf_size = text_buf_size;
}
As demonstrated by the implementation snippet, the role of this routine is to establish the dimensions of the write staging buffer by initializing the text_buf_size field of the printk_record structure tracking variable r.
After initializing the tracking variable r, the system invokes the function prb_reserve(struct prb_reserved_entry *e, struct printk_ringbuffer *rb, struct printk_record *r) to reserve the necessary structural storage space for both the metadata descriptor and raw text data entries inside the ring buffer rb for the calling thread context. It subsequently assigns the internal infos pointer of the newly carved descriptor element and the internal data pointer of the allocated text payload element directly onto the info and text_buf fields of the tracking variable r, respectively. The function prb_reserve() records the remaining operational metadata belonging to this reserved block within a separate context variable e of type struct prb_reserved_entry. This metadata tracking structure captures a pointer rb mapping back to the parent ring buffer, the logical tracking identification token id of the newly reserved descriptor, and the absolute size metrics of the memory space consumed by the data block. Upon completing these alignment and registration tasks, the calling context can execute its concrete write transaction against the ring buffer by streaming data directly into the memory buffer referenced by the text_buf field of variable r.
The kernel further exports a higher-level abstract write interface designated as add_to_rb(struct printk_ringbuffer *rb, struct printk_record *r). This utility automatically orchestrates the underlying calls to prb_rec_init_wr() and prb_reserve() to allocate descriptor and text data blocks, copies the diverse data streams referenced by r.info and r.text_buf directly into the corresponding storage blocks reserved inside the ring buffer infrastructure, and subsequently invokes the routine prb_final_commit() to transition the state bitmask of the data block to a readable phase. Finally, it returns the total memory footprint consumed by the archived record payload.
When executing a read transaction against a target ring buffer, a tracking variable of type struct printk_record must similarly be declared. In contrast to the write sequence, the subsystem must explicitly allocate two standalone staging memory zones prior to reading, which are leveraged to preserve the data payload streams retrieved from the text data queue and the metadata descriptor queue respectively. Before reading from the ring list, the printk_record tracking variable r must be initialized with the physical base memory addresses and size limits of these two independent staging zones. The function responsible for initializing this tracking context is implemented as follows:
void prb_rec_init_rd(struct printk_record *r, struct printk_info *info, char *text_buf, unsigned int text_buf_size)
{
r->info = info;
r->text_buf = text_buf;
r->text_buf_size = text_buf_size;
}
Within this initialization wrapper, the pointer info tracks the base address of the staging zone allocated to hold descriptor metadata records, text_buf points to the base address of the staging zone allocated to hold text data payloads, and text_buf_size specifies the absolute memory limit of the text data staging allocation.
Following the configuration of the tracking variable r, the core subsystem can read back the ring buffer data payloads and associated info records by evaluating the contents hosted at the target memory locations referenced by the distinct pointers inside r.
The Linux kernel additionally implements a variety of supplemental helper functions to handle display updates, scale the log buffer capacity dynamically for auxiliary secondary CPU cores, validate the structural integrity of the ring lists, read out record states, and execute mathematical transformations to map logical identifiers and locations (id and lpos tokens) into literal array indices. These specialized routines are defined across the source code trees located within the files git/kernel/printk/printk_ringbuffer.h and git/kernel/printk/printk_ringbuffer.c.
14.1.3 Data State Transition
As established in the preceding sections, the upper two bits of the state_var field within the descriptor ring describe the operational phase of its corresponding entry. The state can be read via the function desc_read() by providing a specific logical index. If the descriptor ring cannot locate an entry that matches the specified logical index, the function returns the desc_miss pseudo-state.
The active lifecycle of an entry comprises four core states: desc_reusable, desc_reserved, desc_committed, and desc_finalized. Upon system initialization, all entries default to the desc_reusable state. When a writer context triggers a log allocation, it invokes the function prb_reserve() to lock down the necessary storage space inside the ring buffer. The descriptor subsystem scans for available slots starting from head_id + 1. If the structural distance between head_id and tail_id reaches the maximum physical dimension of the descriptor array, prb_reserve() advances the tail position of the circular list, thereby evicting the stale record occupied at the old tail boundary. Once the writer context successfully claims a descriptor slot, it invalidates and frees up the physical space consumed by the oldest records inside the data ring. This data space allocation is executed by the internal routine data_alloc(). This routine scans for unallocated space starting from the begin_lpos boundary of the data ring. Upon claiming the necessary data blocks, data_alloc() marks the old associated descriptor entries as invalid and updates tail_lpos to guarantee that the active data bounds within the text array remain valid. After successfully reserving the memory blocks, the state bitmask of the matching entry transitions from desc_reusable to desc_reserved. The prb_reserve() routine can only claim memory from entries that reside in the desc_reusable state. Once the memory block is reserved, the writer context can stream data into the ring buffer. Upon completing the write transaction, calling the function prb_commit() transitions the entry status to desc_committed. Alternatively, if the write operation is concluded and no further modifications are required, calling the function prb_final_commit() transforms the state directly from desc_reserved to desc_finalized.
The structural state transition rules are governed by a strict unidirectional lifecycle: desc_reusable can only transition to desc_reserved; desc_reserved can transition to either desc_committed or desc_finalized; desc_committed can only transition to desc_finalized; and desc_finalized can only revert to desc_reusable. This means that storage allocation can only be carved out from elements residing in the desc_reusable pool. Before any data can be committed to the ring buffer, the memory must be explicitly reserved. Furthermore, only elements that have reached the desc_finalized state are eligible to be invalidated and recycled by the system.
14.1.4 Initialization of the Log Buffer
The printk subsystem utilizes two categories of ring buffers: a temporary early buffer and a standard dynamic ring buffer. During the initial booting phase, printk leverages a temporary staging queue that is programmatically set up at runtime. The standard persistent ring buffer is activated during later boot stages and post-boot execution, declared and instantiated via the macro definition _DEFINE_PRINTKRB(name, descbits, avgtextbits, text_buf). Within this macro blueprint, name specifies the identifier of the ring buffer instance, descbits configures the bit width utilized to index the elements of the descriptor array, avgtextbits dictates the bit width for the text data block sizing metrics, and text_buf points to the externally allocated static backing buffer designated to store the raw text data strings.
The macro responsible for instantiating this ring buffer architecture is defined as follows:
#define _DEFINE_PRINTKRB(name, descbits, avgtextbits, text_buf) \
static struct prb_desc _##name##_descs[_DESCS_COUNT(descbits)] = { \
[_DESCS_COUNT(descbits) - 1] = { \
.state_var = ATOMIC_INIT(DESC0_SV(descbits)), \
.text_blk_lpos = FAILED_BLK_LPOS, \
}, \
}; \
static struct printk_info _##name##_infos[_DESCS_COUNT(descbits)] = { \
[0] = { \
.seq = -(u64)_DESCS_COUNT(descbits), \
}, \
[_DESCS_COUNT(descbits) - 1] = { \
.seq = 0, \
}, \
}; \
static struct printk_ringbuffer name = { \
.desc_ring = { \
.count_bits = descbits, \
.descs = &_##name##_descs[0], \
.infos = &_##name##_infos[0], \
.head_id = ATOMIC_INIT(DESC0_ID(descbits)), \
.tail_id = ATOMIC_INIT(DESC0_ID(descbits)), \
}, \
.text_data_ring = { \
.size_bits = (avgtextbits) + (descbits), \
.data = text_buf, \
.head_lpos = ATOMIC_LONG_INIT(BLK0_LPOS((avgtextbits) + (descbits))),\
.tail_lpos = ATOMIC_LONG_INIT(BLK0_LPOS((avgtextbits) + (descbits))), \
}, \
.fail = ATOMIC_LONG_INIT(0), \
}
This macro instantiates a monolithic ring buffer structural instance under the designated name name (where name represents the literal string sequence supplied by the caller). Concurrently, it allocates static tracking matrices name_descs and name_infos with a capacity scaling to 2^descbit^ to serve respectively as the backing descs descriptor array and the infos metadata array. The text storage component of the data ring utilizes the externally supplied text_buf memory container. The internal trackers head_id, tail_id, and seq belonging to the descriptor infrastructure are initialized to predefined architectural defaults, while the tracking fields head_lpos and tail_lpos within the text data ring are similarly anchored to default base indices (typically resolving to 0 or -1).
The specific ring buffer instance leveraged by the printk engine is designated as printk_rb_static, which is instantiated via the statement _DEFINE_PRINTKRB(printk_rb_static, CONFIG_LOG_BUF_SHIFT - PRB_AVGBITS, PRB_AVGBITS, &__log_buf[0]). The data ring container specified in this declaration utilizes the core log buffer memory asset __log_buf, which is implemented as a global character array.
The _DEFINE_PRINTKRB() macro merely executes the initial compile-time structural initialization for the printk_rb_static ring buffer topology. Before the printk() function can reliably stream logs into this queue, supplemental initialization settings must be orchestrated at runtime. The start_kernel() process handles this requirement by invoking the function setup_log_buf(0) to finalize the log buffer configuration. The function setup_log_buf(int early) is defined across the source files git/include/linux/printk.h and git/kernel/printk/printk.c, and its definition is implemented as:
void __init setup_log_buf(int early)
{
struct printk_info *new_infos;
unsigned int new_descs_count;
struct prb_desc *new_descs;
struct printk_info info;
struct printk_record r;
size_t new_descs_size;
size_t new_infos_size;
unsigned long flags;
char *new_log_buf;
unsigned int free;
u64 seq;
if (!early)
set_percpu_data_ready();
if (log_buf != __log_buf)
return;
if (!early && !new_log_buf_len)
log_buf_add_cpu();
if (!new_log_buf_len)
return;
new_descs_count = new_log_buf_len >> PRB_AVGBITS;
if (new_descs_count == 0) {
pr_err("new_log_buf_len: %lu too small\n", new_log_buf_len);
return;
}
new_log_buf = memblock_alloc(new_log_buf_len, LOG_ALIGN);
if (unlikely(!new_log_buf)) {
pr_err("log_buf_len: %lu text bytes not available\n", new_log_buf_len);
return;
}
new_descs_size = new_descs_count * sizeof(struct prb_desc);
new_descs = memblock_alloc(new_descs_size, LOG_ALIGN);
if (unlikely(!new_descs)) {
pr_err("log_buf_len: %zu desc bytes not available\n", new_descs_size);
goto err_free_log_buf;
}
new_infos_size = new_descs_count * sizeof(struct printk_info);
new_infos = memblock_alloc(new_infos_size, LOG_ALIGN);
if (unlikely(!new_infos)) {
pr_err("log_buf_len: %zu info bytes not available\n", new_infos_size);
goto err_free_descs;
}
prb_rec_init_rd(&r, &info, &setup_text_buf[0], sizeof(setup_text_buf));
prb_init(&printk_rb_dynamic, new_log_buf, ilog2(new_log_buf_len), new_descs,
ilog2(new_descs_count), new_infos);
logbuf_lock_irqsave(flags);
log_buf_len = new_log_buf_len;
log_buf = new_log_buf;
new_log_buf_len = 0;
free = __LOG_BUF_LEN;
prb_for_each_record(0, &printk_rb_static, seq, &r)
free -= add_to_rb(&printk_rb_dynamic, &r);
prb = &printk_rb_dynamic;
logbuf_unlock_irqrestore(flags);
if (seq != prb_next_seq(&printk_rb_static)) {
pr_err("dropped %llu messages\n", prb_next_seq(&printk_rb_static) - seq);
}
pr_info("log_buf_len: %u bytes\n", log_buf_len);
pr_info("early log buf free: %u(%u%%)\n", free, (free * 100) / __LOG_BUF_LEN);
return;
err_free_descs:
memblock_free(__pa(new_descs), new_descs_size);
err_free_log_buf:
memblock_free(__pa(new_log_buf), new_log_buf_len);
}
During execution, the printk() function needs to acquire the console_lock. If this lock is successfully acquired, printk() invokes the console drivers to output messages to the console hardware. If the console_lock cannot be obtained, printk() preserves the messages inside the __log_buf staging area. Prior to writing into the __log_buf area, printk() must acquire the logbuf_lock.
Under Non-Maskable Interrupt (NMI) conditions, it is impossible for printk() to safely acquire the logbuf_lock. To prevent message loss in multi-CPU hardware architectures, the Linux kernel allocates a dedicated private buffer for each individual CPU core. When a CPU fails to acquire the logbuf_lock, it streams the data into its own private staging buffer. Subsequently, an interrupt service routine drains the data from these per-CPU private staging buffers back into the main ring buffer used by printk() at an appropriate time. The function set_percpu_data_ready() calls printk_safe_init() to establish these private buffers for each CPU. It registers the function __printk_safe_flush() as the deferred interrupt handling task responsible for flushing data from the private buffers into the main ring buffer, and sets the per-CPU flag __printk_percpu_data_ready to indicate that this mechanism is fully operational. __printk_safe_flush() is defined in the source file git/kernel/printk/printk_safe.c.
The ring buffer instantiated via the macro definition _DEFINE_PRINTKRB() can initially only be utilized by a single CPU. When the system incorporates multiple CPU cores, an equivalent volume of storage space must be allocated for the other CPUs to handle log messages. The function setup_log_buf() first evaluates the aggregate log buffer capacity demanded across all active CPUs via new_log_buf_len(). Following this evaluation, it leverages the memblock_alloc() memory allocation function to independently carve out chunks of memory for the text data area, the descs descriptor array, and the infos metadata array.
As established previously, performing a read operation against the ring buffer requires an external staging area. The Linux kernel declares a global character array designated as setup_text_buf[LOG_LINE_MAX]. The setup_log_buf() function utilizes the address and size of this array to initialize the read staging record r via prb_rec_init_rd(). Upon completing these preparatory tasks, setup_log_buf() creates a new ring buffer instance named printk_rb_dynamic by binding the newly allocated memory zones and their respective capacities, which serves as the log queue during the early phase of the system bootstrap.
After establishing the printk_rb_dynamic ring buffer infrastructure, setup_log_buf() invokes the function add_to_rb() to copy the archived log payload out of the static ring buffer printk_rb_static over into the new printk_rb_dynamic repository, while simultaneously computing the absolute residual free space remaining within the log buffer.
Inside the setup_log_buf() routine, prb is a static pointer variable declared outside the function scope of type struct printk_ringbuffer *, whose default target address references printk_rb_static. By executing the assignment statement prb = &printk_rb_dynamic, the setup_log_buf() function hot-swaps the underlying queue utilized by the printk() engine over to printk_rb_dynamic. Consequently, it can be stated that during the early system boot phase, the kernel switches to this dynamic ring buffer architecture to manage and display system diagnostics.