xref: /linux/kernel/printk/printk_ringbuffer.c (revision f16d85cd3de9d0c761b74155b4cbe2f20d3dcf80)
1 // SPDX-License-Identifier: GPL-2.0
2 
3 #include <kunit/visibility.h>
4 #include <linux/kernel.h>
5 #include <linux/irqflags.h>
6 #include <linux/string.h>
7 #include <linux/errno.h>
8 #include <linux/bug.h>
9 #include "printk_ringbuffer.h"
10 #include "internal.h"
11 
12 /**
13  * DOC: printk_ringbuffer overview
14  *
15  * Data Structure
16  * --------------
17  * The printk_ringbuffer is made up of 2 internal ringbuffers:
18  *
19  *   desc_ring
20  *     A ring of descriptors and their meta data (such as sequence number,
21  *     timestamp, loglevel, etc.) as well as internal state information about
22  *     the record and logical positions specifying where in the other
23  *     ringbuffer the text strings are located.
24  *
25  *   text_data_ring
26  *     A ring of data blocks. A data block consists of an unsigned long
27  *     integer (ID) that maps to a desc_ring index followed by the text
28  *     string of the record.
29  *
30  * The internal state information of a descriptor is the key element to allow
31  * readers and writers to locklessly synchronize access to the data.
32  *
33  * Implementation
34  * --------------
35  *
36  * Descriptor Ring
37  * ~~~~~~~~~~~~~~~
38  * The descriptor ring is an array of descriptors. A descriptor contains
39  * essential meta data to track the data of a printk record using
40  * blk_lpos structs pointing to associated text data blocks (see
41  * "Data Rings" below). Each descriptor is assigned an ID that maps
42  * directly to index values of the descriptor array and has a state. The ID
43  * and the state are bitwise combined into a single descriptor field named
44  * @state_var, allowing ID and state to be synchronously and atomically
45  * updated.
46  *
47  * Descriptors have four states:
48  *
49  *   reserved
50  *     A writer is modifying the record.
51  *
52  *   committed
53  *     The record and all its data are written. A writer can reopen the
54  *     descriptor (transitioning it back to reserved), but in the committed
55  *     state the data is consistent.
56  *
57  *   finalized
58  *     The record and all its data are complete and available for reading. A
59  *     writer cannot reopen the descriptor.
60  *
61  *   reusable
62  *     The record exists, but its text and/or meta data may no longer be
63  *     available.
64  *
65  * Querying the @state_var of a record requires providing the ID of the
66  * descriptor to query. This can yield a possible fifth (pseudo) state:
67  *
68  *   miss
69  *     The descriptor being queried has an unexpected ID.
70  *
71  * The descriptor ring has a @tail_id that contains the ID of the oldest
72  * descriptor and @head_id that contains the ID of the newest descriptor.
73  *
74  * When a new descriptor should be created (and the ring is full), the tail
75  * descriptor is invalidated by first transitioning to the reusable state and
76  * then invalidating all tail data blocks up to and including the data blocks
77  * associated with the tail descriptor (for the text ring). Then
78  * @tail_id is advanced, followed by advancing @head_id. And finally the
79  * @state_var of the new descriptor is initialized to the new ID and reserved
80  * state.
81  *
82  * The @tail_id can only be advanced if the new @tail_id would be in the
83  * committed or reusable queried state. This makes it possible that a valid
84  * sequence number of the tail is always available.
85  *
86  * Descriptor Finalization
87  * ~~~~~~~~~~~~~~~~~~~~~~~
88  * When a writer calls the commit function prb_commit(), record data is
89  * fully stored and is consistent within the ringbuffer. However, a writer can
90  * reopen that record, claiming exclusive access (as with prb_reserve()), and
91  * modify that record. When finished, the writer must again commit the record.
92  *
93  * In order for a record to be made available to readers (and also become
94  * recyclable for writers), it must be finalized. A finalized record cannot be
95  * reopened and can never become "unfinalized". Record finalization can occur
96  * in three different scenarios:
97  *
98  *   1) A writer can simultaneously commit and finalize its record by calling
99  *      prb_final_commit() instead of prb_commit().
100  *
101  *   2) When a new record is reserved and the previous record has been
102  *      committed via prb_commit(), that previous record is automatically
103  *      finalized.
104  *
105  *   3) When a record is committed via prb_commit() and a newer record
106  *      already exists, the record being committed is automatically finalized.
107  *
108  * Data Ring
109  * ~~~~~~~~~
110  * The text data ring is a byte array composed of data blocks. Data blocks are
111  * referenced by blk_lpos structs that point to the logical position of the
112  * beginning of a data block and the beginning of the next adjacent data
113  * block. Logical positions are mapped directly to index values of the byte
114  * array ringbuffer.
115  *
116  * Each data block consists of an ID followed by the writer data. The ID is
117  * the identifier of a descriptor that is associated with the data block. A
118  * given data block is considered valid if all of the following conditions
119  * are met:
120  *
121  *   1) The descriptor associated with the data block is in the committed
122  *      or finalized queried state.
123  *
124  *   2) The blk_lpos struct within the descriptor associated with the data
125  *      block references back to the same data block.
126  *
127  *   3) The data block is within the head/tail logical position range.
128  *
129  * If the writer data of a data block would extend beyond the end of the
130  * byte array, only the ID of the data block is stored at the logical
131  * position and the full data block (ID and writer data) is stored at the
132  * beginning of the byte array. The referencing blk_lpos will point to the
133  * ID before the wrap and the next data block will be at the logical
134  * position adjacent the full data block after the wrap.
135  *
136  * Data rings have a @tail_lpos that points to the beginning of the oldest
137  * data block and a @head_lpos that points to the logical position of the
138  * next (not yet existing) data block.
139  *
140  * When a new data block should be created (and the ring is full), tail data
141  * blocks will first be invalidated by putting their associated descriptors
142  * into the reusable state and then pushing the @tail_lpos forward beyond
143  * them. Then the @head_lpos is pushed forward and is associated with a new
144  * descriptor. If a data block is not valid, the @tail_lpos cannot be
145  * advanced beyond it.
146  *
147  * Info Array
148  * ~~~~~~~~~~
149  * The general meta data of printk records are stored in printk_info structs,
150  * stored in an array with the same number of elements as the descriptor ring.
151  * Each info corresponds to the descriptor of the same index in the
152  * descriptor ring. Info validity is confirmed by evaluating the corresponding
153  * descriptor before and after loading the info.
154  *
155  * Usage
156  * -----
157  * Here are some simple examples demonstrating writers and readers. For the
158  * examples a global ringbuffer (test_rb) is available (which is not the
159  * actual ringbuffer used by printk)::
160  *
161  *	DEFINE_PRINTKRB(test_rb, 15, 5);
162  *
163  * This ringbuffer allows up to 32768 records (2 ^ 15) and has a size of
164  * 1 MiB (2 ^ (15 + 5)) for text data.
165  *
166  * Sample writer code::
167  *
168  *	const char *textstr = "message text";
169  *	struct prb_reserved_entry e;
170  *	struct printk_record r;
171  *
172  *	// specify how much to allocate
173  *	prb_rec_init_wr(&r, strlen(textstr) + 1);
174  *
175  *	if (prb_reserve(&e, &test_rb, &r)) {
176  *		snprintf(r.text_buf, r.text_buf_size, "%s", textstr);
177  *
178  *		r.info->text_len = strlen(textstr);
179  *		r.info->ts_nsec = local_clock();
180  *		r.info->caller_id = printk_caller_id();
181  *
182  *		// commit and finalize the record
183  *		prb_final_commit(&e);
184  *	}
185  *
186  * Note that additional writer functions are available to extend a record
187  * after it has been committed but not yet finalized. This can be done as
188  * long as no new records have been reserved and the caller is the same.
189  *
190  * Sample writer code (record extending)::
191  *
192  *		// alternate rest of previous example
193  *
194  *		r.info->text_len = strlen(textstr);
195  *		r.info->ts_nsec = local_clock();
196  *		r.info->caller_id = printk_caller_id();
197  *
198  *		// commit the record (but do not finalize yet)
199  *		prb_commit(&e);
200  *	}
201  *
202  *	...
203  *
204  *	// specify additional 5 bytes text space to extend
205  *	prb_rec_init_wr(&r, 5);
206  *
207  *	// try to extend, but only if it does not exceed 32 bytes
208  *	if (prb_reserve_in_last(&e, &test_rb, &r, printk_caller_id(), 32)) {
209  *		snprintf(&r.text_buf[r.info->text_len],
210  *			 r.text_buf_size - r.info->text_len, "hello");
211  *
212  *		r.info->text_len += 5;
213  *
214  *		// commit and finalize the record
215  *		prb_final_commit(&e);
216  *	}
217  *
218  * Sample reader code::
219  *
220  *	struct printk_info info;
221  *	struct printk_record r;
222  *	char text_buf[32];
223  *	u64 seq;
224  *
225  *	prb_rec_init_rd(&r, &info, &text_buf[0], sizeof(text_buf));
226  *
227  *	prb_for_each_record(0, &test_rb, seq, &r) {
228  *		if (info.seq != seq)
229  *			pr_warn("lost %llu records\n", info.seq - seq);
230  *
231  *		if (info.text_len > r.text_buf_size) {
232  *			pr_warn("record %llu text truncated\n", info.seq);
233  *			text_buf[r.text_buf_size - 1] = 0;
234  *		}
235  *
236  *		pr_info("%llu: %llu: %s\n", info.seq, info.ts_nsec,
237  *			&text_buf[0]);
238  *	}
239  *
240  * Note that additional less convenient reader functions are available to
241  * allow complex record access.
242  *
243  * ABA Issues
244  * ~~~~~~~~~~
245  * To help avoid ABA issues, descriptors are referenced by IDs (array index
246  * values combined with tagged bits counting array wraps) and data blocks are
247  * referenced by logical positions (array index values combined with tagged
248  * bits counting array wraps). However, on 32-bit systems the number of
249  * tagged bits is relatively small such that an ABA incident is (at least
250  * theoretically) possible. For example, if 4 million maximally sized (1KiB)
251  * printk messages were to occur in NMI context on a 32-bit system, the
252  * interrupted context would not be able to recognize that the 32-bit integer
253  * completely wrapped and thus represents a different data block than the one
254  * the interrupted context expects.
255  *
256  * To help combat this possibility, additional state checking is performed
257  * (such as using cmpxchg() even though set() would suffice). These extra
258  * checks are commented as such and will hopefully catch any ABA issue that
259  * a 32-bit system might experience.
260  *
261  * Memory Barriers
262  * ~~~~~~~~~~~~~~~
263  * Multiple memory barriers are used. To simplify proving correctness and
264  * generating litmus tests, lines of code related to memory barriers
265  * (loads, stores, and the associated memory barriers) are labeled::
266  *
267  *	LMM(function:letter)
268  *
269  * Comments reference the labels using only the "function:letter" part.
270  *
271  * The memory barrier pairs and their ordering are:
272  *
273  *   desc_reserve:D / desc_reserve:B
274  *     push descriptor tail (id), then push descriptor head (id)
275  *
276  *   desc_reserve:D / data_push_tail:B
277  *     push data tail (lpos), then set new descriptor reserved (state)
278  *
279  *   desc_reserve:D / desc_push_tail:C
280  *     push descriptor tail (id), then set new descriptor reserved (state)
281  *
282  *   desc_reserve:D / prb_first_seq:C
283  *     push descriptor tail (id), then set new descriptor reserved (state)
284  *
285  *   desc_reserve:F / desc_read:D
286  *     set new descriptor id and reserved (state), then allow writer changes
287  *
288  *   data_alloc:A (or data_realloc:A) / desc_read:D
289  *     set old descriptor reusable (state), then modify new data block area
290  *
291  *   data_alloc:A (or data_realloc:A) / data_push_tail:B
292  *     push data tail (lpos), then modify new data block area
293  *
294  *   _prb_commit:B / desc_read:B
295  *     store writer changes, then set new descriptor committed (state)
296  *
297  *   desc_reopen_last:A / _prb_commit:B
298  *     set descriptor reserved (state), then read descriptor data
299  *
300  *   _prb_commit:B / desc_reserve:D
301  *     set new descriptor committed (state), then check descriptor head (id)
302  *
303  *   data_push_tail:D / data_push_tail:A
304  *     set descriptor reusable (state), then push data tail (lpos)
305  *
306  *   desc_push_tail:B / desc_reserve:D
307  *     set descriptor reusable (state), then push descriptor tail (id)
308  *
309  *   desc_update_last_finalized:A / desc_last_finalized_seq:A
310  *     store finalized record, then set new highest finalized sequence number
311  */
312 
313 #define DATA_SIZE(data_ring)		_DATA_SIZE((data_ring)->size_bits)
314 #define DATA_SIZE_MASK(data_ring)	(DATA_SIZE(data_ring) - 1)
315 
316 #define DESCS_COUNT(desc_ring)		_DESCS_COUNT((desc_ring)->count_bits)
317 #define DESCS_COUNT_MASK(desc_ring)	(DESCS_COUNT(desc_ring) - 1)
318 
319 /* Determine the data array index from a logical position. */
320 #define DATA_INDEX(data_ring, lpos)	((lpos) & DATA_SIZE_MASK(data_ring))
321 
322 /* Determine the desc array index from an ID or sequence number. */
323 #define DESC_INDEX(desc_ring, n)	((n) & DESCS_COUNT_MASK(desc_ring))
324 
325 /* Determine how many times the data array has wrapped. */
326 #define DATA_WRAPS(data_ring, lpos)	((lpos) >> (data_ring)->size_bits)
327 
328 /* Determine if a logical position refers to a data-less block. */
329 #define LPOS_DATALESS(lpos)		((lpos) & 1UL)
330 #define BLK_DATALESS(blk)		(LPOS_DATALESS((blk)->begin) && \
331 					 LPOS_DATALESS((blk)->next))
332 
333 /* Get the logical position at index 0 of the current wrap. */
334 #define DATA_THIS_WRAP_START_LPOS(data_ring, lpos) \
335 ((lpos) & ~DATA_SIZE_MASK(data_ring))
336 
337 /* Get the ID for the same index of the previous wrap as the given ID. */
338 #define DESC_ID_PREV_WRAP(desc_ring, id) \
339 DESC_ID((id) - DESCS_COUNT(desc_ring))
340 
341 /*
342  * A data block: mapped directly to the beginning of the data block area
343  * specified as a logical position within the data ring.
344  *
345  * @id:   the ID of the associated descriptor
346  * @data: the writer data
347  *
348  * Note that the size of a data block is only known by its associated
349  * descriptor.
350  */
351 struct prb_data_block {
352 	unsigned long	id;
353 	char		data[];
354 };
355 
356 /*
357  * Return the descriptor associated with @n. @n can be either a
358  * descriptor ID or a sequence number.
359  */
360 static struct prb_desc *to_desc(struct prb_desc_ring *desc_ring, u64 n)
361 {
362 	return &desc_ring->descs[DESC_INDEX(desc_ring, n)];
363 }
364 
365 /*
366  * Return the printk_info associated with @n. @n can be either a
367  * descriptor ID or a sequence number.
368  */
369 static struct printk_info *to_info(struct prb_desc_ring *desc_ring, u64 n)
370 {
371 	return &desc_ring->infos[DESC_INDEX(desc_ring, n)];
372 }
373 
374 static struct prb_data_block *to_block(struct prb_data_ring *data_ring,
375 				       unsigned long begin_lpos)
376 {
377 	return (void *)&data_ring->data[DATA_INDEX(data_ring, begin_lpos)];
378 }
379 
380 /*
381  * Increase the data size to account for data block meta data plus any
382  * padding so that the adjacent data block is aligned on the ID size.
383  */
384 static unsigned int to_blk_size(unsigned int size)
385 {
386 	struct prb_data_block *db = NULL;
387 
388 	size += sizeof(*db);
389 	size = ALIGN(size, sizeof(db->id));
390 	return size;
391 }
392 
393 /*
394  * Sanity checker for reserve size. The ringbuffer code assumes that a data
395  * block does not exceed the maximum possible size that could fit within the
396  * ringbuffer. This function provides that basic size check so that the
397  * assumption is safe. In particular, it guarantees that data_push_tail() will
398  * never attempt to push the tail beyond the head.
399  */
400 static bool data_check_size(struct prb_data_ring *data_ring, unsigned int size)
401 {
402 	/* Data-less blocks take no space. */
403 	if (size == 0)
404 		return true;
405 
406 	/*
407 	 * If data blocks were allowed to be larger than half the data ring
408 	 * size, a wrapping data block could require more space than the full
409 	 * ringbuffer.
410 	 */
411 	return to_blk_size(size) <= DATA_SIZE(data_ring) / 2;
412 }
413 
414 /*
415  * Compare the current and requested logical position and decide
416  * whether more space is needed.
417  *
418  * Return false when @lpos_current is already at or beyond @lpos_target.
419  *
420  * Also return false when the difference between the positions is bigger
421  * than the size of the data buffer. It might happen only when the caller
422  * raced with another CPU(s) which already made and used the space.
423  */
424 static bool need_more_space(struct prb_data_ring *data_ring,
425 			    unsigned long lpos_current,
426 			    unsigned long lpos_target)
427 {
428 	return lpos_target - lpos_current - 1 < DATA_SIZE(data_ring);
429 }
430 
431 /* Query the state of a descriptor. */
432 static enum desc_state get_desc_state(unsigned long id,
433 				      unsigned long state_val)
434 {
435 	if (id != DESC_ID(state_val))
436 		return desc_miss;
437 
438 	return DESC_STATE(state_val);
439 }
440 
441 /*
442  * Get the state of a specified descriptor.
443  *
444  * Optionally, a copy of the descriptor, sequence number and/or caller ID can
445  * be retrieved. However, (with the exception of @desc_out->state_var) all
446  * retrieved values are invalid if the descriptor is in an inconsistent state
447  * (miss or reserved).
448  */
449 static enum desc_state desc_read(struct prb_desc_ring *desc_ring,
450 				 unsigned long id, struct prb_desc *desc_out,
451 				 u64 *seq_out, u32 *caller_id_out)
452 {
453 	struct printk_info *info = to_info(desc_ring, id);
454 	struct prb_desc *desc = to_desc(desc_ring, id);
455 	atomic_long_t *state_var = &desc->state_var;
456 	enum desc_state d_state;
457 	unsigned long state_val;
458 
459 	/* Check the descriptor state. */
460 	state_val = atomic_long_read(state_var); /* LMM(desc_read:A) */
461 	d_state = get_desc_state(id, state_val);
462 	if (d_state == desc_miss || d_state == desc_reserved) {
463 		/*
464 		 * The descriptor is in an inconsistent state. Set at least
465 		 * @state_var so that the caller can see the details of
466 		 * the inconsistent state.
467 		 */
468 		goto out;
469 	}
470 
471 	/*
472 	 * Guarantee the state is loaded before copying the descriptor
473 	 * content. This avoids copying obsolete descriptor content that might
474 	 * not apply to the descriptor state. This pairs with _prb_commit:B.
475 	 *
476 	 * Memory barrier involvement:
477 	 *
478 	 * If desc_read:A reads from _prb_commit:B, then desc_read:C reads
479 	 * from _prb_commit:A.
480 	 *
481 	 * Relies on:
482 	 *
483 	 * WMB from _prb_commit:A to _prb_commit:B
484 	 *    matching
485 	 * RMB from desc_read:A to desc_read:C
486 	 */
487 	smp_rmb(); /* LMM(desc_read:B) */
488 
489 	/*
490 	 * Copy the descriptor data. The data is not valid until the
491 	 * state has been re-checked. A memcpy() for all of @desc
492 	 * cannot be used because of the atomic_t @state_var field.
493 	 */
494 	if (desc_out) {
495 		memcpy(&desc_out->text_blk_lpos, &desc->text_blk_lpos,
496 		       sizeof(desc_out->text_blk_lpos)); /* LMM(desc_read:C) */
497 	}
498 	if (seq_out)
499 		*seq_out = info->seq; /* also part of desc_read:C */
500 	if (caller_id_out)
501 		*caller_id_out = info->caller_id; /* also part of desc_read:C */
502 
503 	/*
504 	 * 1. Guarantee the descriptor content is loaded before re-checking
505 	 *    the state. This avoids reading an obsolete descriptor state
506 	 *    that may not apply to the copied content. This pairs with
507 	 *    desc_reserve:F.
508 	 *
509 	 *    Memory barrier involvement:
510 	 *
511 	 *    If desc_read:C reads from desc_reserve:G, then desc_read:E
512 	 *    reads from desc_reserve:F.
513 	 *
514 	 *    Relies on:
515 	 *
516 	 *    WMB from desc_reserve:F to desc_reserve:G
517 	 *       matching
518 	 *    RMB from desc_read:C to desc_read:E
519 	 *
520 	 * 2. Guarantee the record data is loaded before re-checking the
521 	 *    state. This avoids reading an obsolete descriptor state that may
522 	 *    not apply to the copied data. This pairs with data_alloc:A and
523 	 *    data_realloc:A.
524 	 *
525 	 *    Memory barrier involvement:
526 	 *
527 	 *    If copy_data:A reads from data_alloc:B, then desc_read:E
528 	 *    reads from desc_make_reusable:A.
529 	 *
530 	 *    Relies on:
531 	 *
532 	 *    MB from desc_make_reusable:A to data_alloc:B
533 	 *       matching
534 	 *    RMB from desc_read:C to desc_read:E
535 	 *
536 	 *    Note: desc_make_reusable:A and data_alloc:B can be different
537 	 *          CPUs. However, the data_alloc:B CPU (which performs the
538 	 *          full memory barrier) must have previously seen
539 	 *          desc_make_reusable:A.
540 	 */
541 	smp_rmb(); /* LMM(desc_read:D) */
542 
543 	/*
544 	 * The data has been copied. Return the current descriptor state,
545 	 * which may have changed since the load above.
546 	 */
547 	state_val = atomic_long_read(state_var); /* LMM(desc_read:E) */
548 	d_state = get_desc_state(id, state_val);
549 out:
550 	if (desc_out)
551 		atomic_long_set(&desc_out->state_var, state_val);
552 	return d_state;
553 }
554 
555 /*
556  * Take a specified descriptor out of the finalized state by attempting
557  * the transition from finalized to reusable. Either this context or some
558  * other context will have been successful.
559  */
560 static void desc_make_reusable(struct prb_desc_ring *desc_ring,
561 			       unsigned long id)
562 {
563 	unsigned long val_finalized = DESC_SV(id, desc_finalized);
564 	unsigned long val_reusable = DESC_SV(id, desc_reusable);
565 	struct prb_desc *desc = to_desc(desc_ring, id);
566 	atomic_long_t *state_var = &desc->state_var;
567 
568 	atomic_long_cmpxchg_relaxed(state_var, val_finalized,
569 				    val_reusable); /* LMM(desc_make_reusable:A) */
570 }
571 
572 /*
573  * Given the text data ring, put the associated descriptor of each
574  * data block from @lpos_begin until @lpos_end into the reusable state.
575  *
576  * If there is any problem making the associated descriptor reusable, either
577  * the descriptor has not yet been finalized or another writer context has
578  * already pushed the tail lpos past the problematic data block. Regardless,
579  * on error the caller can re-load the tail lpos to determine the situation.
580  */
581 static bool data_make_reusable(struct printk_ringbuffer *rb,
582 			       unsigned long lpos_begin,
583 			       unsigned long lpos_end,
584 			       unsigned long *lpos_out)
585 {
586 
587 	struct prb_data_ring *data_ring = &rb->text_data_ring;
588 	struct prb_desc_ring *desc_ring = &rb->desc_ring;
589 	struct prb_data_block *blk;
590 	enum desc_state d_state;
591 	struct prb_desc desc;
592 	struct prb_data_blk_lpos *blk_lpos = &desc.text_blk_lpos;
593 	unsigned long id;
594 
595 	/* Loop until @lpos_begin has advanced to or beyond @lpos_end. */
596 	while (need_more_space(data_ring, lpos_begin, lpos_end)) {
597 		blk = to_block(data_ring, lpos_begin);
598 
599 		/*
600 		 * Load the block ID from the data block. This is a data race
601 		 * against a writer that may have newly reserved this data
602 		 * area. If the loaded value matches a valid descriptor ID,
603 		 * the blk_lpos of that descriptor will be checked to make
604 		 * sure it points back to this data block. If the check fails,
605 		 * the data area has been recycled by another writer.
606 		 */
607 		id = blk->id; /* LMM(data_make_reusable:A) */
608 
609 		d_state = desc_read(desc_ring, id, &desc,
610 				    NULL, NULL); /* LMM(data_make_reusable:B) */
611 
612 		switch (d_state) {
613 		case desc_miss:
614 		case desc_reserved:
615 		case desc_committed:
616 			return false;
617 		case desc_finalized:
618 			/*
619 			 * This data block is invalid if the descriptor
620 			 * does not point back to it.
621 			 */
622 			if (blk_lpos->begin != lpos_begin)
623 				return false;
624 			desc_make_reusable(desc_ring, id);
625 			break;
626 		case desc_reusable:
627 			/*
628 			 * This data block is invalid if the descriptor
629 			 * does not point back to it.
630 			 */
631 			if (blk_lpos->begin != lpos_begin)
632 				return false;
633 			break;
634 		}
635 
636 		/* Advance @lpos_begin to the next data block. */
637 		lpos_begin = blk_lpos->next;
638 	}
639 
640 	*lpos_out = lpos_begin;
641 	return true;
642 }
643 
644 /*
645  * Advance the data ring tail to at least @lpos. This function puts
646  * descriptors into the reusable state if the tail is pushed beyond
647  * their associated data block.
648  */
649 static bool data_push_tail(struct printk_ringbuffer *rb, unsigned long lpos)
650 {
651 	struct prb_data_ring *data_ring = &rb->text_data_ring;
652 	unsigned long tail_lpos_new;
653 	unsigned long tail_lpos;
654 	unsigned long next_lpos;
655 
656 	/* If @lpos is from a data-less block, there is nothing to do. */
657 	if (LPOS_DATALESS(lpos))
658 		return true;
659 
660 	/*
661 	 * Any descriptor states that have transitioned to reusable due to the
662 	 * data tail being pushed to this loaded value will be visible to this
663 	 * CPU. This pairs with data_push_tail:D.
664 	 *
665 	 * Memory barrier involvement:
666 	 *
667 	 * If data_push_tail:A reads from data_push_tail:D, then this CPU can
668 	 * see desc_make_reusable:A.
669 	 *
670 	 * Relies on:
671 	 *
672 	 * MB from desc_make_reusable:A to data_push_tail:D
673 	 *    matches
674 	 * READFROM from data_push_tail:D to data_push_tail:A
675 	 *    thus
676 	 * READFROM from desc_make_reusable:A to this CPU
677 	 */
678 	tail_lpos = atomic_long_read(&data_ring->tail_lpos); /* LMM(data_push_tail:A) */
679 
680 	/*
681 	 * Loop until the tail lpos is at or beyond @lpos. This condition
682 	 * may already be satisfied, resulting in no full memory barrier
683 	 * from data_push_tail:D being performed. However, since this CPU
684 	 * sees the new tail lpos, any descriptor states that transitioned to
685 	 * the reusable state must already be visible.
686 	 */
687 	while (need_more_space(data_ring, tail_lpos, lpos)) {
688 		/*
689 		 * Make all descriptors reusable that are associated with
690 		 * data blocks before @lpos.
691 		 */
692 		if (!data_make_reusable(rb, tail_lpos, lpos, &next_lpos)) {
693 			/*
694 			 * 1. Guarantee the block ID loaded in
695 			 *    data_make_reusable() is performed before
696 			 *    reloading the tail lpos. The failed
697 			 *    data_make_reusable() may be due to a newly
698 			 *    recycled data area causing the tail lpos to
699 			 *    have been previously pushed. This pairs with
700 			 *    data_alloc:A and data_realloc:A.
701 			 *
702 			 *    Memory barrier involvement:
703 			 *
704 			 *    If data_make_reusable:A reads from data_alloc:B,
705 			 *    then data_push_tail:C reads from
706 			 *    data_push_tail:D.
707 			 *
708 			 *    Relies on:
709 			 *
710 			 *    MB from data_push_tail:D to data_alloc:B
711 			 *       matching
712 			 *    RMB from data_make_reusable:A to
713 			 *    data_push_tail:C
714 			 *
715 			 *    Note: data_push_tail:D and data_alloc:B can be
716 			 *          different CPUs. However, the data_alloc:B
717 			 *          CPU (which performs the full memory
718 			 *          barrier) must have previously seen
719 			 *          data_push_tail:D.
720 			 *
721 			 * 2. Guarantee the descriptor state loaded in
722 			 *    data_make_reusable() is performed before
723 			 *    reloading the tail lpos. The failed
724 			 *    data_make_reusable() may be due to a newly
725 			 *    recycled descriptor causing the tail lpos to
726 			 *    have been previously pushed. This pairs with
727 			 *    desc_reserve:D.
728 			 *
729 			 *    Memory barrier involvement:
730 			 *
731 			 *    If data_make_reusable:B reads from
732 			 *    desc_reserve:F, then data_push_tail:C reads
733 			 *    from data_push_tail:D.
734 			 *
735 			 *    Relies on:
736 			 *
737 			 *    MB from data_push_tail:D to desc_reserve:F
738 			 *       matching
739 			 *    RMB from data_make_reusable:B to
740 			 *    data_push_tail:C
741 			 *
742 			 *    Note: data_push_tail:D and desc_reserve:F can
743 			 *          be different CPUs. However, the
744 			 *          desc_reserve:F CPU (which performs the
745 			 *          full memory barrier) must have previously
746 			 *          seen data_push_tail:D.
747 			 */
748 			smp_rmb(); /* LMM(data_push_tail:B) */
749 
750 			tail_lpos_new = atomic_long_read(&data_ring->tail_lpos
751 							); /* LMM(data_push_tail:C) */
752 			if (tail_lpos_new == tail_lpos)
753 				return false;
754 
755 			/* Another CPU pushed the tail. Try again. */
756 			tail_lpos = tail_lpos_new;
757 			continue;
758 		}
759 
760 		/*
761 		 * Guarantee any descriptor states that have transitioned to
762 		 * reusable are stored before pushing the tail lpos. A full
763 		 * memory barrier is needed since other CPUs may have made
764 		 * the descriptor states reusable. This pairs with
765 		 * data_push_tail:A.
766 		 */
767 		if (atomic_long_try_cmpxchg(&data_ring->tail_lpos, &tail_lpos,
768 					    next_lpos)) { /* LMM(data_push_tail:D) */
769 			break;
770 		}
771 	}
772 
773 	return true;
774 }
775 
776 /*
777  * Advance the desc ring tail. This function advances the tail by one
778  * descriptor, thus invalidating the oldest descriptor. Before advancing
779  * the tail, the tail descriptor is made reusable and all data blocks up to
780  * and including the descriptor's data block are invalidated (i.e. the data
781  * ring tail is pushed past the data block of the descriptor being made
782  * reusable).
783  */
784 static bool desc_push_tail(struct printk_ringbuffer *rb,
785 			   unsigned long tail_id)
786 {
787 	struct prb_desc_ring *desc_ring = &rb->desc_ring;
788 	enum desc_state d_state;
789 	struct prb_desc desc;
790 
791 	d_state = desc_read(desc_ring, tail_id, &desc, NULL, NULL);
792 
793 	switch (d_state) {
794 	case desc_miss:
795 		/*
796 		 * If the ID is exactly 1 wrap behind the expected, it is
797 		 * in the process of being reserved by another writer and
798 		 * must be considered reserved.
799 		 */
800 		if (DESC_ID(atomic_long_read(&desc.state_var)) ==
801 		    DESC_ID_PREV_WRAP(desc_ring, tail_id)) {
802 			return false;
803 		}
804 
805 		/*
806 		 * The ID has changed. Another writer must have pushed the
807 		 * tail and recycled the descriptor already. Success is
808 		 * returned because the caller is only interested in the
809 		 * specified tail being pushed, which it was.
810 		 */
811 		return true;
812 	case desc_reserved:
813 	case desc_committed:
814 		return false;
815 	case desc_finalized:
816 		desc_make_reusable(desc_ring, tail_id);
817 		break;
818 	case desc_reusable:
819 		break;
820 	}
821 
822 	/*
823 	 * Data blocks must be invalidated before their associated
824 	 * descriptor can be made available for recycling. Invalidating
825 	 * them later is not possible because there is no way to trust
826 	 * data blocks once their associated descriptor is gone.
827 	 */
828 
829 	if (!data_push_tail(rb, desc.text_blk_lpos.next))
830 		return false;
831 
832 	/*
833 	 * Check the next descriptor after @tail_id before pushing the tail
834 	 * to it because the tail must always be in a finalized or reusable
835 	 * state. The implementation of prb_first_seq() relies on this.
836 	 *
837 	 * A successful read implies that the next descriptor is less than or
838 	 * equal to @head_id so there is no risk of pushing the tail past the
839 	 * head.
840 	 */
841 	d_state = desc_read(desc_ring, DESC_ID(tail_id + 1), &desc,
842 			    NULL, NULL); /* LMM(desc_push_tail:A) */
843 
844 	if (d_state == desc_finalized || d_state == desc_reusable) {
845 		/*
846 		 * Guarantee any descriptor states that have transitioned to
847 		 * reusable are stored before pushing the tail ID. This allows
848 		 * verifying the recycled descriptor state. A full memory
849 		 * barrier is needed since other CPUs may have made the
850 		 * descriptor states reusable. This pairs with desc_reserve:D.
851 		 */
852 		atomic_long_cmpxchg(&desc_ring->tail_id, tail_id,
853 				    DESC_ID(tail_id + 1)); /* LMM(desc_push_tail:B) */
854 	} else {
855 		/*
856 		 * Guarantee the last state load from desc_read() is before
857 		 * reloading @tail_id in order to see a new tail ID in the
858 		 * case that the descriptor has been recycled. This pairs
859 		 * with desc_reserve:D.
860 		 *
861 		 * Memory barrier involvement:
862 		 *
863 		 * If desc_push_tail:A reads from desc_reserve:F, then
864 		 * desc_push_tail:D reads from desc_push_tail:B.
865 		 *
866 		 * Relies on:
867 		 *
868 		 * MB from desc_push_tail:B to desc_reserve:F
869 		 *    matching
870 		 * RMB from desc_push_tail:A to desc_push_tail:D
871 		 *
872 		 * Note: desc_push_tail:B and desc_reserve:F can be different
873 		 *       CPUs. However, the desc_reserve:F CPU (which performs
874 		 *       the full memory barrier) must have previously seen
875 		 *       desc_push_tail:B.
876 		 */
877 		smp_rmb(); /* LMM(desc_push_tail:C) */
878 
879 		/*
880 		 * Re-check the tail ID. The descriptor following @tail_id is
881 		 * not in an allowed tail state. But if the tail has since
882 		 * been moved by another CPU, then it does not matter.
883 		 */
884 		if (atomic_long_read(&desc_ring->tail_id) == tail_id) /* LMM(desc_push_tail:D) */
885 			return false;
886 	}
887 
888 	return true;
889 }
890 
891 /* Reserve a new descriptor, invalidating the oldest if necessary. */
892 static bool desc_reserve(struct printk_ringbuffer *rb, unsigned long *id_out)
893 {
894 	struct prb_desc_ring *desc_ring = &rb->desc_ring;
895 	unsigned long prev_state_val;
896 	unsigned long id_prev_wrap;
897 	struct prb_desc *desc;
898 	unsigned long head_id;
899 	unsigned long id;
900 
901 	head_id = atomic_long_read(&desc_ring->head_id); /* LMM(desc_reserve:A) */
902 
903 	do {
904 		id = DESC_ID(head_id + 1);
905 		id_prev_wrap = DESC_ID_PREV_WRAP(desc_ring, id);
906 
907 		/*
908 		 * Guarantee the head ID is read before reading the tail ID.
909 		 * Since the tail ID is updated before the head ID, this
910 		 * guarantees that @id_prev_wrap is never ahead of the tail
911 		 * ID. This pairs with desc_reserve:D.
912 		 *
913 		 * Memory barrier involvement:
914 		 *
915 		 * If desc_reserve:A reads from desc_reserve:D, then
916 		 * desc_reserve:C reads from desc_push_tail:B.
917 		 *
918 		 * Relies on:
919 		 *
920 		 * MB from desc_push_tail:B to desc_reserve:D
921 		 *    matching
922 		 * RMB from desc_reserve:A to desc_reserve:C
923 		 *
924 		 * Note: desc_push_tail:B and desc_reserve:D can be different
925 		 *       CPUs. However, the desc_reserve:D CPU (which performs
926 		 *       the full memory barrier) must have previously seen
927 		 *       desc_push_tail:B.
928 		 */
929 		smp_rmb(); /* LMM(desc_reserve:B) */
930 
931 		if (id_prev_wrap == atomic_long_read(&desc_ring->tail_id
932 						    )) { /* LMM(desc_reserve:C) */
933 			/*
934 			 * Make space for the new descriptor by
935 			 * advancing the tail.
936 			 */
937 			if (!desc_push_tail(rb, id_prev_wrap))
938 				return false;
939 		}
940 
941 		/*
942 		 * 1. Guarantee the tail ID is read before validating the
943 		 *    recycled descriptor state. A read memory barrier is
944 		 *    sufficient for this. This pairs with desc_push_tail:B.
945 		 *
946 		 *    Memory barrier involvement:
947 		 *
948 		 *    If desc_reserve:C reads from desc_push_tail:B, then
949 		 *    desc_reserve:E reads from desc_make_reusable:A.
950 		 *
951 		 *    Relies on:
952 		 *
953 		 *    MB from desc_make_reusable:A to desc_push_tail:B
954 		 *       matching
955 		 *    RMB from desc_reserve:C to desc_reserve:E
956 		 *
957 		 *    Note: desc_make_reusable:A and desc_push_tail:B can be
958 		 *          different CPUs. However, the desc_push_tail:B CPU
959 		 *          (which performs the full memory barrier) must have
960 		 *          previously seen desc_make_reusable:A.
961 		 *
962 		 * 2. Guarantee the tail ID is stored before storing the head
963 		 *    ID. This pairs with desc_reserve:B.
964 		 *
965 		 * 3. Guarantee any data ring tail changes are stored before
966 		 *    recycling the descriptor. Data ring tail changes can
967 		 *    happen via desc_push_tail()->data_push_tail(). A full
968 		 *    memory barrier is needed since another CPU may have
969 		 *    pushed the data ring tails. This pairs with
970 		 *    data_push_tail:B.
971 		 *
972 		 * 4. Guarantee a new tail ID is stored before recycling the
973 		 *    descriptor. A full memory barrier is needed since
974 		 *    another CPU may have pushed the tail ID. This pairs
975 		 *    with desc_push_tail:C and this also pairs with
976 		 *    prb_first_seq:C.
977 		 *
978 		 * 5. Guarantee the head ID is stored before trying to
979 		 *    finalize the previous descriptor. This pairs with
980 		 *    _prb_commit:B.
981 		 */
982 	} while (!atomic_long_try_cmpxchg(&desc_ring->head_id, &head_id,
983 					  id)); /* LMM(desc_reserve:D) */
984 
985 	desc = to_desc(desc_ring, id);
986 
987 	/*
988 	 * If the descriptor has been recycled, verify the old state val.
989 	 * See "ABA Issues" about why this verification is performed.
990 	 */
991 	prev_state_val = atomic_long_read(&desc->state_var); /* LMM(desc_reserve:E) */
992 	if (prev_state_val &&
993 	    get_desc_state(id_prev_wrap, prev_state_val) != desc_reusable) {
994 		WARN_ON_ONCE(1);
995 		return false;
996 	}
997 
998 	/*
999 	 * Assign the descriptor a new ID and set its state to reserved.
1000 	 * See "ABA Issues" about why cmpxchg() instead of set() is used.
1001 	 *
1002 	 * Guarantee the new descriptor ID and state is stored before making
1003 	 * any other changes. A write memory barrier is sufficient for this.
1004 	 * This pairs with desc_read:D.
1005 	 */
1006 	if (!atomic_long_try_cmpxchg(&desc->state_var, &prev_state_val,
1007 			DESC_SV(id, desc_reserved))) { /* LMM(desc_reserve:F) */
1008 		WARN_ON_ONCE(1);
1009 		return false;
1010 	}
1011 
1012 	/* Now data in @desc can be modified: LMM(desc_reserve:G) */
1013 
1014 	*id_out = id;
1015 	return true;
1016 }
1017 
1018 static bool is_blk_wrapped(struct prb_data_ring *data_ring,
1019 			   unsigned long begin_lpos, unsigned long next_lpos)
1020 {
1021 	/*
1022 	 * Subtract one from next_lpos since it's not actually part of this data
1023 	 * block. This allows perfectly fitting records to not wrap.
1024 	 */
1025 	return DATA_WRAPS(data_ring, begin_lpos) !=
1026 	       DATA_WRAPS(data_ring, next_lpos - 1);
1027 }
1028 
1029 /* Determine the end of a data block. */
1030 static unsigned long get_next_lpos(struct prb_data_ring *data_ring,
1031 				   unsigned long lpos, unsigned int size)
1032 {
1033 	unsigned long begin_lpos;
1034 	unsigned long next_lpos;
1035 
1036 	begin_lpos = lpos;
1037 	next_lpos = lpos + size;
1038 
1039 	/* First check if the data block does not wrap. */
1040 	if (!is_blk_wrapped(data_ring, begin_lpos, next_lpos))
1041 		return next_lpos;
1042 
1043 	/* Wrapping data blocks store their data at the beginning. */
1044 	return (DATA_THIS_WRAP_START_LPOS(data_ring, next_lpos) + size);
1045 }
1046 
1047 /*
1048  * Allocate a new data block, invalidating the oldest data block(s)
1049  * if necessary. This function also associates the data block with
1050  * a specified descriptor.
1051  */
1052 static char *data_alloc(struct printk_ringbuffer *rb, unsigned int size,
1053 			struct prb_data_blk_lpos *blk_lpos, unsigned long id)
1054 {
1055 	struct prb_data_ring *data_ring = &rb->text_data_ring;
1056 	struct prb_data_block *blk;
1057 	unsigned long begin_lpos;
1058 	unsigned long next_lpos;
1059 
1060 	if (size == 0) {
1061 		/*
1062 		 * Data blocks are not created for empty lines. Instead, the
1063 		 * reader will recognize these special lpos values and handle
1064 		 * it appropriately.
1065 		 */
1066 		blk_lpos->begin = EMPTY_LINE_LPOS;
1067 		blk_lpos->next = EMPTY_LINE_LPOS;
1068 		return NULL;
1069 	}
1070 
1071 	size = to_blk_size(size);
1072 
1073 	begin_lpos = atomic_long_read(&data_ring->head_lpos);
1074 
1075 	do {
1076 		next_lpos = get_next_lpos(data_ring, begin_lpos, size);
1077 
1078 		/*
1079 		 * data_check_size() prevents data block allocation that could
1080 		 * cause illegal ringbuffer states. But double check that the
1081 		 * used space will not be bigger than the ring buffer. Wrapped
1082 		 * messages need to reserve more space, see get_next_lpos().
1083 		 *
1084 		 * Specify a data-less block when the check or the allocation
1085 		 * fails.
1086 		 */
1087 		if (WARN_ON_ONCE(next_lpos - begin_lpos > DATA_SIZE(data_ring)) ||
1088 		    !data_push_tail(rb, next_lpos - DATA_SIZE(data_ring))) {
1089 			blk_lpos->begin = FAILED_LPOS;
1090 			blk_lpos->next = FAILED_LPOS;
1091 			return NULL;
1092 		}
1093 
1094 		/*
1095 		 * 1. Guarantee any descriptor states that have transitioned
1096 		 *    to reusable are stored before modifying the newly
1097 		 *    allocated data area. A full memory barrier is needed
1098 		 *    since other CPUs may have made the descriptor states
1099 		 *    reusable. See data_push_tail:A about why the reusable
1100 		 *    states are visible. This pairs with desc_read:D.
1101 		 *
1102 		 * 2. Guarantee any updated tail lpos is stored before
1103 		 *    modifying the newly allocated data area. Another CPU may
1104 		 *    be in data_make_reusable() and is reading a block ID
1105 		 *    from this area. data_make_reusable() can handle reading
1106 		 *    a garbage block ID value, but then it must be able to
1107 		 *    load a new tail lpos. A full memory barrier is needed
1108 		 *    since other CPUs may have updated the tail lpos. This
1109 		 *    pairs with data_push_tail:B.
1110 		 */
1111 	} while (!atomic_long_try_cmpxchg(&data_ring->head_lpos, &begin_lpos,
1112 					  next_lpos)); /* LMM(data_alloc:A) */
1113 
1114 	blk = to_block(data_ring, begin_lpos);
1115 	blk->id = id; /* LMM(data_alloc:B) */
1116 
1117 	if (is_blk_wrapped(data_ring, begin_lpos, next_lpos)) {
1118 		/* Wrapping data blocks store their data at the beginning. */
1119 		blk = to_block(data_ring, 0);
1120 
1121 		/*
1122 		 * Store the ID on the wrapped block for consistency.
1123 		 * The printk_ringbuffer does not actually use it.
1124 		 */
1125 		blk->id = id;
1126 	}
1127 
1128 	blk_lpos->begin = begin_lpos;
1129 	blk_lpos->next = next_lpos;
1130 
1131 	return &blk->data[0];
1132 }
1133 
1134 /*
1135  * Try to resize an existing data block associated with the descriptor
1136  * specified by @id. If the resized data block should become wrapped, it
1137  * copies the old data to the new data block. If @size yields a data block
1138  * with the same or less size, the data block is left as is.
1139  *
1140  * Fail if this is not the last allocated data block or if there is not
1141  * enough space or it is not possible make enough space.
1142  *
1143  * Return a pointer to the beginning of the entire data buffer or NULL on
1144  * failure.
1145  */
1146 static char *data_realloc(struct printk_ringbuffer *rb, unsigned int size,
1147 			  struct prb_data_blk_lpos *blk_lpos, unsigned long id)
1148 {
1149 	struct prb_data_ring *data_ring = &rb->text_data_ring;
1150 	struct prb_data_block *blk;
1151 	unsigned long head_lpos;
1152 	unsigned long next_lpos;
1153 	bool wrapped;
1154 
1155 	/* Reallocation only works if @blk_lpos is the newest data block. */
1156 	head_lpos = atomic_long_read(&data_ring->head_lpos);
1157 	if (head_lpos != blk_lpos->next)
1158 		return NULL;
1159 
1160 	/* Keep track if @blk_lpos was a wrapping data block. */
1161 	wrapped = is_blk_wrapped(data_ring, blk_lpos->begin, blk_lpos->next);
1162 
1163 	size = to_blk_size(size);
1164 
1165 	next_lpos = get_next_lpos(data_ring, blk_lpos->begin, size);
1166 
1167 	/*
1168 	 * Use the current data block when the size does not increase, i.e.
1169 	 * when @head_lpos is already able to accommodate the new @next_lpos.
1170 	 *
1171 	 * Note that need_more_space() could never return false here because
1172 	 * the difference between the positions was bigger than the data
1173 	 * buffer size. The data block is reopened and can't get reused.
1174 	 */
1175 	if (!need_more_space(data_ring, head_lpos, next_lpos)) {
1176 		if (wrapped)
1177 			blk = to_block(data_ring, 0);
1178 		else
1179 			blk = to_block(data_ring, blk_lpos->begin);
1180 		return &blk->data[0];
1181 	}
1182 
1183 	/*
1184 	 * data_check_size() prevents data block reallocation that could
1185 	 * cause illegal ringbuffer states. But double check that the
1186 	 * new used space will not be bigger than the ring buffer. Wrapped
1187 	 * messages need to reserve more space, see get_next_lpos().
1188 	 *
1189 	 * Specify failure when the check or the allocation fails.
1190 	 */
1191 	if (WARN_ON_ONCE(next_lpos - blk_lpos->begin > DATA_SIZE(data_ring)) ||
1192 	    !data_push_tail(rb, next_lpos - DATA_SIZE(data_ring))) {
1193 		return NULL;
1194 	}
1195 
1196 	/* The memory barrier involvement is the same as data_alloc:A. */
1197 	if (!atomic_long_try_cmpxchg(&data_ring->head_lpos, &head_lpos,
1198 				     next_lpos)) { /* LMM(data_realloc:A) */
1199 		return NULL;
1200 	}
1201 
1202 	blk = to_block(data_ring, blk_lpos->begin);
1203 
1204 	if (is_blk_wrapped(data_ring, blk_lpos->begin, next_lpos)) {
1205 		struct prb_data_block *old_blk = blk;
1206 
1207 		/* Wrapping data blocks store their data at the beginning. */
1208 		blk = to_block(data_ring, 0);
1209 
1210 		/*
1211 		 * Store the ID on the wrapped block for consistency.
1212 		 * The printk_ringbuffer does not actually use it.
1213 		 */
1214 		blk->id = id;
1215 
1216 		if (!wrapped) {
1217 			/*
1218 			 * Since the allocated space is now in the newly
1219 			 * created wrapping data block, copy the content
1220 			 * from the old data block.
1221 			 */
1222 			memcpy(&blk->data[0], &old_blk->data[0],
1223 			       (blk_lpos->next - blk_lpos->begin) - sizeof(blk->id));
1224 		}
1225 	}
1226 
1227 	blk_lpos->next = next_lpos;
1228 
1229 	return &blk->data[0];
1230 }
1231 
1232 /* Return the number of bytes used by a data block. */
1233 static unsigned int space_used(struct prb_data_ring *data_ring,
1234 			       struct prb_data_blk_lpos *blk_lpos)
1235 {
1236 	/* Data-less blocks take no space. */
1237 	if (BLK_DATALESS(blk_lpos))
1238 		return 0;
1239 
1240 	/* Data block does not wrap. */
1241 	if (!is_blk_wrapped(data_ring, blk_lpos->begin, blk_lpos->next))
1242 		return blk_lpos->next - blk_lpos->begin;
1243 
1244 	/*
1245 	 * For wrapping data blocks, the trailing (wasted) space is
1246 	 * also counted.
1247 	 */
1248 	return (DATA_INDEX(data_ring, blk_lpos->next) +
1249 		DATA_SIZE(data_ring) - DATA_INDEX(data_ring, blk_lpos->begin));
1250 }
1251 
1252 /*
1253  * Given @blk_lpos, return a pointer to the writer data from the data block
1254  * and calculate the size of the data part. A NULL pointer is returned if
1255  * @blk_lpos specifies values that could never be legal.
1256  *
1257  * This function (used by readers) performs strict validation on the lpos
1258  * values to possibly detect bugs in the writer code. A WARN_ON_ONCE() is
1259  * triggered if an internal error is detected.
1260  */
1261 static const char *get_data(struct prb_data_ring *data_ring,
1262 			    struct prb_data_blk_lpos *blk_lpos,
1263 			    unsigned int *data_size)
1264 {
1265 	struct prb_data_block *db;
1266 
1267 	/* Data-less data block description. */
1268 	if (BLK_DATALESS(blk_lpos)) {
1269 		/*
1270 		 * Records that are just empty lines are also valid, even
1271 		 * though they do not have a data block. For such records
1272 		 * explicitly return empty string data to signify success.
1273 		 */
1274 		if (blk_lpos->begin == EMPTY_LINE_LPOS &&
1275 		    blk_lpos->next == EMPTY_LINE_LPOS) {
1276 			*data_size = 0;
1277 			return "";
1278 		}
1279 
1280 		/* Data lost, invalid, or otherwise unavailable. */
1281 		return NULL;
1282 	}
1283 
1284 	/* Regular data block: @begin and @next in the same wrap. */
1285 	if (!is_blk_wrapped(data_ring, blk_lpos->begin, blk_lpos->next)) {
1286 		db = to_block(data_ring, blk_lpos->begin);
1287 		*data_size = blk_lpos->next - blk_lpos->begin;
1288 
1289 	/* Wrapping data block: @begin is one wrap behind @next. */
1290 	} else if (!is_blk_wrapped(data_ring,
1291 				   blk_lpos->begin + DATA_SIZE(data_ring),
1292 				   blk_lpos->next)) {
1293 		db = to_block(data_ring, 0);
1294 		*data_size = DATA_INDEX(data_ring, blk_lpos->next);
1295 
1296 	/* Illegal block description. */
1297 	} else {
1298 		WARN_ON_ONCE(1);
1299 		return NULL;
1300 	}
1301 
1302 	/* A valid data block will always be aligned to the ID size. */
1303 	if (WARN_ON_ONCE(blk_lpos->begin != ALIGN(blk_lpos->begin, sizeof(db->id))) ||
1304 	    WARN_ON_ONCE(blk_lpos->next != ALIGN(blk_lpos->next, sizeof(db->id)))) {
1305 		return NULL;
1306 	}
1307 
1308 	/*
1309 	 * A regular data block will always have an ID and at least
1310 	 * 1 byte of data. Data-less blocks were handled earlier.
1311 	 */
1312 	if (WARN_ON_ONCE(*data_size <= sizeof(db->id)))
1313 		return NULL;
1314 
1315 	/* Subtract block ID space from size to reflect data size. */
1316 	*data_size -= sizeof(db->id);
1317 
1318 	/* Sanity check the max size of the regular data block. */
1319 	if (WARN_ON_ONCE(!data_check_size(data_ring, *data_size)))
1320 		return NULL;
1321 
1322 	return &db->data[0];
1323 }
1324 
1325 /*
1326  * Attempt to transition the newest descriptor from committed back to reserved
1327  * so that the record can be modified by a writer again. This is only possible
1328  * if the descriptor is not yet finalized and the provided @caller_id matches.
1329  */
1330 static struct prb_desc *desc_reopen_last(struct prb_desc_ring *desc_ring,
1331 					 u32 caller_id, unsigned long *id_out)
1332 {
1333 	unsigned long prev_state_val;
1334 	enum desc_state d_state;
1335 	struct prb_desc *d;
1336 	unsigned long id;
1337 	u32 cid;
1338 
1339 	id = atomic_long_read(&desc_ring->head_id);
1340 
1341 	/*
1342 	 * To reduce unnecessarily reopening, first check if the descriptor
1343 	 * state and caller ID are correct.
1344 	 */
1345 	d_state = desc_read(desc_ring, id, NULL, NULL, &cid);
1346 	if (d_state != desc_committed || cid != caller_id)
1347 		return NULL;
1348 
1349 	d = to_desc(desc_ring, id);
1350 
1351 	prev_state_val = DESC_SV(id, desc_committed);
1352 
1353 	/*
1354 	 * Guarantee the reserved state is stored before reading any
1355 	 * record data. A full memory barrier is needed because @state_var
1356 	 * modification is followed by reading. This pairs with _prb_commit:B.
1357 	 *
1358 	 * Memory barrier involvement:
1359 	 *
1360 	 * If desc_reopen_last:A reads from _prb_commit:B, then
1361 	 * prb_reserve_in_last:A reads from _prb_commit:A.
1362 	 *
1363 	 * Relies on:
1364 	 *
1365 	 * WMB from _prb_commit:A to _prb_commit:B
1366 	 *    matching
1367 	 * MB from desc_reopen_last:A to prb_reserve_in_last:A
1368 	 */
1369 	if (!atomic_long_try_cmpxchg(&d->state_var, &prev_state_val,
1370 			DESC_SV(id, desc_reserved))) { /* LMM(desc_reopen_last:A) */
1371 		return NULL;
1372 	}
1373 
1374 	*id_out = id;
1375 	return d;
1376 }
1377 
1378 /**
1379  * prb_reserve_in_last() - Re-reserve and extend the space in the ringbuffer
1380  *                         used by the newest record.
1381  *
1382  * @e:         The entry structure to setup.
1383  * @rb:        The ringbuffer to re-reserve and extend data in.
1384  * @r:         The record structure to allocate buffers for.
1385  * @caller_id: The caller ID of the caller (reserving writer).
1386  * @max_size:  Fail if the extended size would be greater than this.
1387  *
1388  * This is the public function available to writers to re-reserve and extend
1389  * data.
1390  *
1391  * The writer specifies the text size to extend (not the new total size) by
1392  * setting the @text_buf_size field of @r. To ensure proper initialization
1393  * of @r, prb_rec_init_wr() should be used.
1394  *
1395  * This function will fail if @caller_id does not match the caller ID of the
1396  * newest record. In that case the caller must reserve new data using
1397  * prb_reserve().
1398  *
1399  * Context: Any context. Disables local interrupts on success.
1400  * Return: true if text data could be extended, otherwise false.
1401  *
1402  * On success:
1403  *
1404  *   - @r->text_buf points to the beginning of the entire text buffer.
1405  *
1406  *   - @r->text_buf_size is set to the new total size of the buffer.
1407  *
1408  *   - @r->info is not touched so that @r->info->text_len could be used
1409  *     to append the text.
1410  *
1411  *   - prb_record_text_space() can be used on @e to query the new
1412  *     actually used space.
1413  *
1414  * Important: All @r->info fields will already be set with the current values
1415  *            for the record. I.e. @r->info->text_len will be less than
1416  *            @text_buf_size. Writers can use @r->info->text_len to know
1417  *            where concatenation begins and writers should update
1418  *            @r->info->text_len after concatenating.
1419  */
1420 bool prb_reserve_in_last(struct prb_reserved_entry *e, struct printk_ringbuffer *rb,
1421 			 struct printk_record *r, u32 caller_id, unsigned int max_size)
1422 {
1423 	struct prb_desc_ring *desc_ring = &rb->desc_ring;
1424 	struct printk_info *info;
1425 	unsigned int data_size;
1426 	struct prb_desc *d;
1427 	unsigned long id;
1428 
1429 	local_irq_save(e->irqflags);
1430 
1431 	/* Transition the newest descriptor back to the reserved state. */
1432 	d = desc_reopen_last(desc_ring, caller_id, &id);
1433 	if (!d) {
1434 		local_irq_restore(e->irqflags);
1435 		goto fail_reopen;
1436 	}
1437 
1438 	/* Now the writer has exclusive access: LMM(prb_reserve_in_last:A) */
1439 
1440 	info = to_info(desc_ring, id);
1441 
1442 	/*
1443 	 * Set the @e fields here so that prb_commit() can be used if
1444 	 * anything fails from now on.
1445 	 */
1446 	e->rb = rb;
1447 	e->id = id;
1448 
1449 	/*
1450 	 * desc_reopen_last() checked the caller_id, but there was no
1451 	 * exclusive access at that point. The descriptor may have
1452 	 * changed since then.
1453 	 */
1454 	if (caller_id != info->caller_id)
1455 		goto fail;
1456 
1457 	if (BLK_DATALESS(&d->text_blk_lpos)) {
1458 		if (WARN_ON_ONCE(info->text_len != 0)) {
1459 			pr_warn_once("wrong text_len value (%hu, expecting 0)\n",
1460 				     info->text_len);
1461 			info->text_len = 0;
1462 		}
1463 
1464 		if (!data_check_size(&rb->text_data_ring, r->text_buf_size))
1465 			goto fail;
1466 
1467 		if (r->text_buf_size > max_size)
1468 			goto fail;
1469 
1470 		r->text_buf = data_alloc(rb, r->text_buf_size,
1471 					 &d->text_blk_lpos, id);
1472 	} else {
1473 		if (!get_data(&rb->text_data_ring, &d->text_blk_lpos, &data_size))
1474 			goto fail;
1475 
1476 		/*
1477 		 * Increase the buffer size to include the original size. If
1478 		 * the meta data (@text_len) is not sane, use the full data
1479 		 * block size.
1480 		 */
1481 		if (WARN_ON_ONCE(info->text_len > data_size)) {
1482 			pr_warn_once("wrong text_len value (%hu, expecting <=%u)\n",
1483 				     info->text_len, data_size);
1484 			info->text_len = data_size;
1485 		}
1486 		r->text_buf_size += info->text_len;
1487 
1488 		if (!data_check_size(&rb->text_data_ring, r->text_buf_size))
1489 			goto fail;
1490 
1491 		if (r->text_buf_size > max_size)
1492 			goto fail;
1493 
1494 		r->text_buf = data_realloc(rb, r->text_buf_size,
1495 					   &d->text_blk_lpos, id);
1496 	}
1497 	if (r->text_buf_size && !r->text_buf)
1498 		goto fail;
1499 
1500 	r->info = info;
1501 
1502 	e->text_space = space_used(&rb->text_data_ring, &d->text_blk_lpos);
1503 
1504 	return true;
1505 fail:
1506 	prb_commit(e);
1507 	/* prb_commit() re-enabled interrupts. */
1508 fail_reopen:
1509 	/* Make it clear to the caller that the re-reserve failed. */
1510 	memset(r, 0, sizeof(*r));
1511 	return false;
1512 }
1513 
1514 /*
1515  * @last_finalized_seq value guarantees that all records up to and including
1516  * this sequence number are finalized and can be read. The only exception are
1517  * too old records which have already been overwritten.
1518  *
1519  * It is also guaranteed that @last_finalized_seq only increases.
1520  *
1521  * Be aware that finalized records following non-finalized records are not
1522  * reported because they are not yet available to the reader. For example,
1523  * a new record stored via printk() will not be available to a printer if
1524  * it follows a record that has not been finalized yet. However, once that
1525  * non-finalized record becomes finalized, @last_finalized_seq will be
1526  * appropriately updated and the full set of finalized records will be
1527  * available to the printer. And since each printk() caller will either
1528  * directly print or trigger deferred printing of all available unprinted
1529  * records, all printk() messages will get printed.
1530  */
1531 static u64 desc_last_finalized_seq(struct printk_ringbuffer *rb)
1532 {
1533 	struct prb_desc_ring *desc_ring = &rb->desc_ring;
1534 	unsigned long ulseq;
1535 
1536 	/*
1537 	 * Guarantee the sequence number is loaded before loading the
1538 	 * associated record in order to guarantee that the record can be
1539 	 * seen by this CPU. This pairs with desc_update_last_finalized:A.
1540 	 */
1541 	ulseq = atomic_long_read_acquire(&desc_ring->last_finalized_seq
1542 					); /* LMM(desc_last_finalized_seq:A) */
1543 
1544 	return __ulseq_to_u64seq(rb, ulseq);
1545 }
1546 
1547 static bool _prb_read_valid(struct printk_ringbuffer *rb, u64 *seq,
1548 			    struct printk_record *r, unsigned int *line_count);
1549 
1550 /*
1551  * Check if there are records directly following @last_finalized_seq that are
1552  * finalized. If so, update @last_finalized_seq to the latest of these
1553  * records. It is not allowed to skip over records that are not yet finalized.
1554  */
1555 static void desc_update_last_finalized(struct printk_ringbuffer *rb)
1556 {
1557 	struct prb_desc_ring *desc_ring = &rb->desc_ring;
1558 	u64 old_seq = desc_last_finalized_seq(rb);
1559 	unsigned long oldval;
1560 	unsigned long newval;
1561 	u64 finalized_seq;
1562 	u64 try_seq;
1563 
1564 try_again:
1565 	finalized_seq = old_seq;
1566 	try_seq = finalized_seq + 1;
1567 
1568 	/* Try to find later finalized records. */
1569 	while (_prb_read_valid(rb, &try_seq, NULL, NULL)) {
1570 		finalized_seq = try_seq;
1571 		try_seq++;
1572 	}
1573 
1574 	/* No update needed if no later finalized record was found. */
1575 	if (finalized_seq == old_seq)
1576 		return;
1577 
1578 	oldval = __u64seq_to_ulseq(old_seq);
1579 	newval = __u64seq_to_ulseq(finalized_seq);
1580 
1581 	/*
1582 	 * Set the sequence number of a later finalized record that has been
1583 	 * seen.
1584 	 *
1585 	 * Guarantee the record data is visible to other CPUs before storing
1586 	 * its sequence number. This pairs with desc_last_finalized_seq:A.
1587 	 *
1588 	 * Memory barrier involvement:
1589 	 *
1590 	 * If desc_last_finalized_seq:A reads from
1591 	 * desc_update_last_finalized:A, then desc_read:A reads from
1592 	 * _prb_commit:B.
1593 	 *
1594 	 * Relies on:
1595 	 *
1596 	 * RELEASE from _prb_commit:B to desc_update_last_finalized:A
1597 	 *    matching
1598 	 * ACQUIRE from desc_last_finalized_seq:A to desc_read:A
1599 	 *
1600 	 * Note: _prb_commit:B and desc_update_last_finalized:A can be
1601 	 *       different CPUs. However, the desc_update_last_finalized:A
1602 	 *       CPU (which performs the release) must have previously seen
1603 	 *       _prb_commit:B.
1604 	 */
1605 	if (!atomic_long_try_cmpxchg_release(&desc_ring->last_finalized_seq,
1606 				&oldval, newval)) { /* LMM(desc_update_last_finalized:A) */
1607 		old_seq = __ulseq_to_u64seq(rb, oldval);
1608 		goto try_again;
1609 	}
1610 }
1611 
1612 /*
1613  * Attempt to finalize a specified descriptor. If this fails, the descriptor
1614  * is either already final or it will finalize itself when the writer commits.
1615  */
1616 static void desc_make_final(struct printk_ringbuffer *rb, unsigned long id)
1617 {
1618 	struct prb_desc_ring *desc_ring = &rb->desc_ring;
1619 	unsigned long prev_state_val = DESC_SV(id, desc_committed);
1620 	struct prb_desc *d = to_desc(desc_ring, id);
1621 
1622 	if (atomic_long_try_cmpxchg_relaxed(&d->state_var, &prev_state_val,
1623 			DESC_SV(id, desc_finalized))) { /* LMM(desc_make_final:A) */
1624 		desc_update_last_finalized(rb);
1625 	}
1626 }
1627 
1628 /**
1629  * prb_reserve() - Reserve space in the ringbuffer.
1630  *
1631  * @e:  The entry structure to setup.
1632  * @rb: The ringbuffer to reserve data in.
1633  * @r:  The record structure to allocate buffers for.
1634  *
1635  * This is the public function available to writers to reserve data.
1636  *
1637  * The writer specifies the text size to reserve by setting the
1638  * @text_buf_size field of @r. To ensure proper initialization of @r,
1639  * prb_rec_init_wr() should be used.
1640  *
1641  * Context: Any context. Disables local interrupts on success.
1642  * Return: true if at least text data could be allocated, otherwise false.
1643  *
1644  * On success, the fields @info and @text_buf of @r will be set by this
1645  * function and should be filled in by the writer before committing. Also
1646  * on success, prb_record_text_space() can be used on @e to query the actual
1647  * space used for the text data block.
1648  *
1649  * Important: @info->text_len needs to be set correctly by the writer in
1650  *            order for data to be readable and/or extended. Its value
1651  *            is initialized to 0.
1652  */
1653 bool prb_reserve(struct prb_reserved_entry *e, struct printk_ringbuffer *rb,
1654 		 struct printk_record *r)
1655 {
1656 	struct prb_desc_ring *desc_ring = &rb->desc_ring;
1657 	struct printk_info *info;
1658 	struct prb_desc *d;
1659 	unsigned long id;
1660 	u64 seq;
1661 
1662 	if (!data_check_size(&rb->text_data_ring, r->text_buf_size))
1663 		goto fail;
1664 
1665 	/*
1666 	 * Descriptors in the reserved state act as blockers to all further
1667 	 * reservations once the desc_ring has fully wrapped. Disable
1668 	 * interrupts during the reserve/commit window in order to minimize
1669 	 * the likelihood of this happening.
1670 	 */
1671 	local_irq_save(e->irqflags);
1672 
1673 	if (!desc_reserve(rb, &id)) {
1674 		/* Descriptor reservation failures are tracked. */
1675 		atomic_long_inc(&rb->fail);
1676 		local_irq_restore(e->irqflags);
1677 		goto fail;
1678 	}
1679 
1680 	d = to_desc(desc_ring, id);
1681 	info = to_info(desc_ring, id);
1682 
1683 	/*
1684 	 * All @info fields (except @seq) are cleared and must be filled in
1685 	 * by the writer. Save @seq before clearing because it is used to
1686 	 * determine the new sequence number.
1687 	 */
1688 	seq = info->seq;
1689 	memset(info, 0, sizeof(*info));
1690 
1691 	/*
1692 	 * Set the @e fields here so that prb_commit() can be used if
1693 	 * text data allocation fails.
1694 	 */
1695 	e->rb = rb;
1696 	e->id = id;
1697 
1698 	/*
1699 	 * Initialize the sequence number if it has "never been set".
1700 	 * Otherwise just increment it by a full wrap.
1701 	 *
1702 	 * @seq is considered "never been set" if it has a value of 0,
1703 	 * _except_ for @infos[0], which was specially setup by the ringbuffer
1704 	 * initializer and therefore is always considered as set.
1705 	 *
1706 	 * See the "Bootstrap" comment block in printk_ringbuffer.h for
1707 	 * details about how the initializer bootstraps the descriptors.
1708 	 */
1709 	if (seq == 0 && DESC_INDEX(desc_ring, id) != 0)
1710 		info->seq = DESC_INDEX(desc_ring, id);
1711 	else
1712 		info->seq = seq + DESCS_COUNT(desc_ring);
1713 
1714 	/*
1715 	 * New data is about to be reserved. Once that happens, previous
1716 	 * descriptors are no longer able to be extended. Finalize the
1717 	 * previous descriptor now so that it can be made available to
1718 	 * readers. (For seq==0 there is no previous descriptor.)
1719 	 */
1720 	if (info->seq > 0)
1721 		desc_make_final(rb, DESC_ID(id - 1));
1722 
1723 	r->text_buf = data_alloc(rb, r->text_buf_size, &d->text_blk_lpos, id);
1724 	/* If text data allocation fails, a data-less record is committed. */
1725 	if (r->text_buf_size && !r->text_buf) {
1726 		prb_commit(e);
1727 		/* prb_commit() re-enabled interrupts. */
1728 		goto fail;
1729 	}
1730 
1731 	r->info = info;
1732 
1733 	/* Record full text space used by record. */
1734 	e->text_space = space_used(&rb->text_data_ring, &d->text_blk_lpos);
1735 
1736 	return true;
1737 fail:
1738 	/* Make it clear to the caller that the reserve failed. */
1739 	memset(r, 0, sizeof(*r));
1740 	return false;
1741 }
1742 EXPORT_SYMBOL_IF_KUNIT(prb_reserve);
1743 
1744 /* Commit the data (possibly finalizing it) and restore interrupts. */
1745 static void _prb_commit(struct prb_reserved_entry *e, unsigned long state_val)
1746 {
1747 	struct prb_desc_ring *desc_ring = &e->rb->desc_ring;
1748 	struct prb_desc *d = to_desc(desc_ring, e->id);
1749 	unsigned long prev_state_val = DESC_SV(e->id, desc_reserved);
1750 
1751 	/* Now the writer has finished all writing: LMM(_prb_commit:A) */
1752 
1753 	/*
1754 	 * Set the descriptor as committed. See "ABA Issues" about why
1755 	 * cmpxchg() instead of set() is used.
1756 	 *
1757 	 * 1  Guarantee all record data is stored before the descriptor state
1758 	 *    is stored as committed. A write memory barrier is sufficient
1759 	 *    for this. This pairs with desc_read:B and desc_reopen_last:A.
1760 	 *
1761 	 * 2. Guarantee the descriptor state is stored as committed before
1762 	 *    re-checking the head ID in order to possibly finalize this
1763 	 *    descriptor. This pairs with desc_reserve:D.
1764 	 *
1765 	 *    Memory barrier involvement:
1766 	 *
1767 	 *    If prb_commit:A reads from desc_reserve:D, then
1768 	 *    desc_make_final:A reads from _prb_commit:B.
1769 	 *
1770 	 *    Relies on:
1771 	 *
1772 	 *    MB from _prb_commit:B to prb_commit:A
1773 	 *       matching
1774 	 *    MB from desc_reserve:D to desc_make_final:A
1775 	 */
1776 	if (!atomic_long_try_cmpxchg(&d->state_var, &prev_state_val,
1777 			DESC_SV(e->id, state_val))) { /* LMM(_prb_commit:B) */
1778 		WARN_ON_ONCE(1);
1779 	}
1780 
1781 	/* Restore interrupts, the reserve/commit window is finished. */
1782 	local_irq_restore(e->irqflags);
1783 }
1784 
1785 /**
1786  * prb_commit() - Commit (previously reserved) data to the ringbuffer.
1787  *
1788  * @e: The entry containing the reserved data information.
1789  *
1790  * This is the public function available to writers to commit data.
1791  *
1792  * Note that the data is not yet available to readers until it is finalized.
1793  * Finalizing happens automatically when space for the next record is
1794  * reserved.
1795  *
1796  * See prb_final_commit() for a version of this function that finalizes
1797  * immediately.
1798  *
1799  * Context: Any context. Enables local interrupts.
1800  */
1801 void prb_commit(struct prb_reserved_entry *e)
1802 {
1803 	struct prb_desc_ring *desc_ring = &e->rb->desc_ring;
1804 	unsigned long head_id;
1805 
1806 	_prb_commit(e, desc_committed);
1807 
1808 	/*
1809 	 * If this descriptor is no longer the head (i.e. a new record has
1810 	 * been allocated), extending the data for this record is no longer
1811 	 * allowed and therefore it must be finalized.
1812 	 */
1813 	head_id = atomic_long_read(&desc_ring->head_id); /* LMM(prb_commit:A) */
1814 	if (head_id != e->id)
1815 		desc_make_final(e->rb, e->id);
1816 }
1817 EXPORT_SYMBOL_IF_KUNIT(prb_commit);
1818 
1819 /**
1820  * prb_final_commit() - Commit and finalize (previously reserved) data to
1821  *                      the ringbuffer.
1822  *
1823  * @e: The entry containing the reserved data information.
1824  *
1825  * This is the public function available to writers to commit+finalize data.
1826  *
1827  * By finalizing, the data is made immediately available to readers.
1828  *
1829  * This function should only be used if there are no intentions of extending
1830  * this data using prb_reserve_in_last().
1831  *
1832  * Context: Any context. Enables local interrupts.
1833  */
1834 void prb_final_commit(struct prb_reserved_entry *e)
1835 {
1836 	_prb_commit(e, desc_finalized);
1837 
1838 	desc_update_last_finalized(e->rb);
1839 }
1840 
1841 /*
1842  * Count the number of lines in provided text. All text has at least 1 line
1843  * (even if @text_size is 0). Each '\n' processed is counted as an additional
1844  * line.
1845  */
1846 static unsigned int count_lines(const char *text, unsigned int text_size)
1847 {
1848 	unsigned int next_size = text_size;
1849 	unsigned int line_count = 1;
1850 	const char *next = text;
1851 
1852 	while (next_size) {
1853 		next = memchr(next, '\n', next_size);
1854 		if (!next)
1855 			break;
1856 		line_count++;
1857 		next++;
1858 		next_size = text_size - (next - text);
1859 	}
1860 
1861 	return line_count;
1862 }
1863 
1864 /*
1865  * Given @blk_lpos, copy an expected @len of data into the provided buffer.
1866  * If @line_count is provided, count the number of lines in the data.
1867  *
1868  * This function (used by readers) performs strict validation on the data
1869  * size to possibly detect bugs in the writer code. A WARN_ON_ONCE() is
1870  * triggered if an internal error is detected.
1871  */
1872 static bool copy_data(struct prb_data_ring *data_ring,
1873 		      struct prb_data_blk_lpos *blk_lpos, u16 len, char *buf,
1874 		      unsigned int buf_size, unsigned int *line_count)
1875 {
1876 	unsigned int data_size;
1877 	const char *data;
1878 
1879 	/* Caller might not want any data. */
1880 	if ((!buf || !buf_size) && !line_count)
1881 		return true;
1882 
1883 	data = get_data(data_ring, blk_lpos, &data_size);
1884 	if (!data)
1885 		return false;
1886 
1887 	/*
1888 	 * Actual cannot be less than expected. It can be more than expected
1889 	 * because of the trailing alignment padding.
1890 	 *
1891 	 * Note that invalid @len values can occur because the caller loads
1892 	 * the value during an allowed data race.
1893 	 */
1894 	if (data_size < (unsigned int)len)
1895 		return false;
1896 
1897 	/* Caller interested in the line count? */
1898 	if (line_count)
1899 		*line_count = count_lines(data, len);
1900 
1901 	/* Caller interested in the data content? */
1902 	if (!buf || !buf_size)
1903 		return true;
1904 
1905 	data_size = min_t(unsigned int, buf_size, len);
1906 
1907 	memcpy(&buf[0], data, data_size); /* LMM(copy_data:A) */
1908 	return true;
1909 }
1910 
1911 /*
1912  * This is an extended version of desc_read(). It gets a copy of a specified
1913  * descriptor. However, it also verifies that the record is finalized and has
1914  * the sequence number @seq. On success, 0 is returned.
1915  *
1916  * Error return values:
1917  * -EINVAL: A finalized record with sequence number @seq does not exist.
1918  * -ENOENT: A finalized record with sequence number @seq exists, but its data
1919  *          is not available. This is a valid record, so readers should
1920  *          continue with the next record.
1921  */
1922 static int desc_read_finalized_seq(struct prb_desc_ring *desc_ring,
1923 				   unsigned long id, u64 seq,
1924 				   struct prb_desc *desc_out)
1925 {
1926 	struct prb_data_blk_lpos *blk_lpos = &desc_out->text_blk_lpos;
1927 	enum desc_state d_state;
1928 	u64 s;
1929 
1930 	d_state = desc_read(desc_ring, id, desc_out, &s, NULL);
1931 
1932 	/*
1933 	 * An unexpected @id (desc_miss) or @seq mismatch means the record
1934 	 * does not exist. A descriptor in the reserved or committed state
1935 	 * means the record does not yet exist for the reader.
1936 	 */
1937 	if (d_state == desc_miss ||
1938 	    d_state == desc_reserved ||
1939 	    d_state == desc_committed ||
1940 	    s != seq) {
1941 		return -EINVAL;
1942 	}
1943 
1944 	/*
1945 	 * A descriptor in the reusable state may no longer have its data
1946 	 * available; report it as existing but with lost data. Or the record
1947 	 * may actually be a record with lost data.
1948 	 */
1949 	if (d_state == desc_reusable ||
1950 	    (blk_lpos->begin == FAILED_LPOS && blk_lpos->next == FAILED_LPOS)) {
1951 		return -ENOENT;
1952 	}
1953 
1954 	return 0;
1955 }
1956 
1957 /*
1958  * Copy the ringbuffer data from the record with @seq to the provided
1959  * @r buffer. On success, 0 is returned.
1960  *
1961  * See desc_read_finalized_seq() for error return values.
1962  */
1963 static int prb_read(struct printk_ringbuffer *rb, u64 seq,
1964 		    struct printk_record *r, unsigned int *line_count)
1965 {
1966 	struct prb_desc_ring *desc_ring = &rb->desc_ring;
1967 	struct printk_info *info = to_info(desc_ring, seq);
1968 	struct prb_desc *rdesc = to_desc(desc_ring, seq);
1969 	atomic_long_t *state_var = &rdesc->state_var;
1970 	struct prb_desc desc;
1971 	unsigned long id;
1972 	int err;
1973 
1974 	/* Extract the ID, used to specify the descriptor to read. */
1975 	id = DESC_ID(atomic_long_read(state_var));
1976 
1977 	/* Get a local copy of the correct descriptor (if available). */
1978 	err = desc_read_finalized_seq(desc_ring, id, seq, &desc);
1979 
1980 	/*
1981 	 * If @r is NULL, the caller is only interested in the availability
1982 	 * of the record.
1983 	 */
1984 	if (err || !r)
1985 		return err;
1986 
1987 	/* If requested, copy meta data. */
1988 	if (r->info)
1989 		memcpy(r->info, info, sizeof(*(r->info)));
1990 
1991 	/* Copy text data. If it fails, this is a data-less record. */
1992 	if (!copy_data(&rb->text_data_ring, &desc.text_blk_lpos, info->text_len,
1993 		       r->text_buf, r->text_buf_size, line_count)) {
1994 		return -ENOENT;
1995 	}
1996 
1997 	/* Ensure the record is still finalized and has the same @seq. */
1998 	return desc_read_finalized_seq(desc_ring, id, seq, &desc);
1999 }
2000 
2001 /* Get the sequence number of the tail descriptor. */
2002 u64 prb_first_seq(struct printk_ringbuffer *rb)
2003 {
2004 	struct prb_desc_ring *desc_ring = &rb->desc_ring;
2005 	enum desc_state d_state;
2006 	unsigned long id;
2007 	u64 seq;
2008 
2009 	for (;;) {
2010 		id = atomic_long_read(&rb->desc_ring.tail_id); /* LMM(prb_first_seq:A) */
2011 
2012 		d_state = desc_read(desc_ring, id, NULL, &seq, NULL); /* LMM(prb_first_seq:B) */
2013 
2014 		/*
2015 		 * This loop will not be infinite because the tail is
2016 		 * _always_ in the finalized or reusable state.
2017 		 */
2018 		if (d_state == desc_finalized || d_state == desc_reusable)
2019 			break;
2020 
2021 		/*
2022 		 * Guarantee the last state load from desc_read() is before
2023 		 * reloading @tail_id in order to see a new tail in the case
2024 		 * that the descriptor has been recycled. This pairs with
2025 		 * desc_reserve:D.
2026 		 *
2027 		 * Memory barrier involvement:
2028 		 *
2029 		 * If prb_first_seq:B reads from desc_reserve:F, then
2030 		 * prb_first_seq:A reads from desc_push_tail:B.
2031 		 *
2032 		 * Relies on:
2033 		 *
2034 		 * MB from desc_push_tail:B to desc_reserve:F
2035 		 *    matching
2036 		 * RMB from prb_first_seq:B to prb_first_seq:A
2037 		 */
2038 		smp_rmb(); /* LMM(prb_first_seq:C) */
2039 	}
2040 
2041 	return seq;
2042 }
2043 
2044 /**
2045  * prb_next_reserve_seq() - Get the sequence number after the most recently
2046  *                  reserved record.
2047  *
2048  * @rb:  The ringbuffer to get the sequence number from.
2049  *
2050  * This is the public function available to readers to see what sequence
2051  * number will be assigned to the next reserved record.
2052  *
2053  * Note that depending on the situation, this value can be equal to or
2054  * higher than the sequence number returned by prb_next_seq().
2055  *
2056  * Context: Any context.
2057  * Return: The sequence number that will be assigned to the next record
2058  *         reserved.
2059  */
2060 u64 prb_next_reserve_seq(struct printk_ringbuffer *rb)
2061 {
2062 	struct prb_desc_ring *desc_ring = &rb->desc_ring;
2063 	unsigned long last_finalized_id;
2064 	atomic_long_t *state_var;
2065 	u64 last_finalized_seq;
2066 	unsigned long head_id;
2067 	struct prb_desc desc;
2068 	unsigned long diff;
2069 	struct prb_desc *d;
2070 	int err;
2071 
2072 	/*
2073 	 * It may not be possible to read a sequence number for @head_id.
2074 	 * So the ID of @last_finailzed_seq is used to calculate what the
2075 	 * sequence number of @head_id will be.
2076 	 */
2077 
2078 try_again:
2079 	last_finalized_seq = desc_last_finalized_seq(rb);
2080 
2081 	/*
2082 	 * @head_id is loaded after @last_finalized_seq to ensure that
2083 	 * it points to the record with @last_finalized_seq or newer.
2084 	 *
2085 	 * Memory barrier involvement:
2086 	 *
2087 	 * If desc_last_finalized_seq:A reads from
2088 	 * desc_update_last_finalized:A, then
2089 	 * prb_next_reserve_seq:A reads from desc_reserve:D.
2090 	 *
2091 	 * Relies on:
2092 	 *
2093 	 * RELEASE from desc_reserve:D to desc_update_last_finalized:A
2094 	 *    matching
2095 	 * ACQUIRE from desc_last_finalized_seq:A to prb_next_reserve_seq:A
2096 	 *
2097 	 * Note: desc_reserve:D and desc_update_last_finalized:A can be
2098 	 *       different CPUs. However, the desc_update_last_finalized:A CPU
2099 	 *       (which performs the release) must have previously seen
2100 	 *       desc_read:C, which implies desc_reserve:D can be seen.
2101 	 */
2102 	head_id = atomic_long_read(&desc_ring->head_id); /* LMM(prb_next_reserve_seq:A) */
2103 
2104 	d = to_desc(desc_ring, last_finalized_seq);
2105 	state_var = &d->state_var;
2106 
2107 	/* Extract the ID, used to specify the descriptor to read. */
2108 	last_finalized_id = DESC_ID(atomic_long_read(state_var));
2109 
2110 	/* Ensure @last_finalized_id is correct. */
2111 	err = desc_read_finalized_seq(desc_ring, last_finalized_id, last_finalized_seq, &desc);
2112 
2113 	if (err == -EINVAL) {
2114 		if (last_finalized_seq == 0) {
2115 			/*
2116 			 * No record has been finalized or even reserved yet.
2117 			 *
2118 			 * The @head_id is initialized such that the first
2119 			 * increment will yield the first record (seq=0).
2120 			 * Handle it separately to avoid a negative @diff
2121 			 * below.
2122 			 */
2123 			if (head_id == DESC0_ID(desc_ring->count_bits))
2124 				return 0;
2125 
2126 			/*
2127 			 * One or more descriptors are already reserved. Use
2128 			 * the descriptor ID of the first one (@seq=0) for
2129 			 * the @diff below.
2130 			 */
2131 			last_finalized_id = DESC0_ID(desc_ring->count_bits) + 1;
2132 		} else {
2133 			/* Record must have been overwritten. Try again. */
2134 			goto try_again;
2135 		}
2136 	}
2137 
2138 	/* Diff of known descriptor IDs to compute related sequence numbers. */
2139 	diff = head_id - last_finalized_id;
2140 
2141 	/*
2142 	 * @head_id points to the most recently reserved record, but this
2143 	 * function returns the sequence number that will be assigned to the
2144 	 * next (not yet reserved) record. Thus +1 is needed.
2145 	 */
2146 	return (last_finalized_seq + diff + 1);
2147 }
2148 
2149 /*
2150  * Non-blocking read of a record.
2151  *
2152  * On success @seq is updated to the record that was read and (if provided)
2153  * @r and @line_count will contain the read/calculated data.
2154  *
2155  * On failure @seq is updated to a record that is not yet available to the
2156  * reader, but it will be the next record available to the reader.
2157  *
2158  * Note: When the current CPU is in panic, this function will skip over any
2159  *       non-existent/non-finalized records in order to allow the panic CPU
2160  *       to print any and all records that have been finalized.
2161  */
2162 static bool _prb_read_valid(struct printk_ringbuffer *rb, u64 *seq,
2163 			    struct printk_record *r, unsigned int *line_count)
2164 {
2165 	u64 tail_seq;
2166 	int err;
2167 
2168 	while ((err = prb_read(rb, *seq, r, line_count))) {
2169 		tail_seq = prb_first_seq(rb);
2170 
2171 		if (*seq < tail_seq) {
2172 			/*
2173 			 * Behind the tail. Catch up and try again. This
2174 			 * can happen for -ENOENT and -EINVAL cases.
2175 			 */
2176 			*seq = tail_seq;
2177 
2178 		} else if (err == -ENOENT) {
2179 			/* Record exists, but the data was lost. Skip. */
2180 			(*seq)++;
2181 
2182 		} else {
2183 			/*
2184 			 * Non-existent/non-finalized record. Must stop.
2185 			 *
2186 			 * For panic situations it cannot be expected that
2187 			 * non-finalized records will become finalized. But
2188 			 * there may be other finalized records beyond that
2189 			 * need to be printed for a panic situation. If this
2190 			 * is the panic CPU, skip this
2191 			 * non-existent/non-finalized record unless non-panic
2192 			 * CPUs are still running and their debugging is
2193 			 * explicitly enabled.
2194 			 *
2195 			 * Note that new messages printed on panic CPU are
2196 			 * finalized when we are here. The only exception
2197 			 * might be the last message without trailing newline.
2198 			 * But it would have the sequence number returned
2199 			 * by "prb_next_reserve_seq() - 1".
2200 			 */
2201 			if (panic_on_this_cpu() &&
2202 			    (!debug_non_panic_cpus || legacy_allow_panic_sync) &&
2203 			    ((*seq + 1) < prb_next_reserve_seq(rb))) {
2204 				(*seq)++;
2205 			} else {
2206 				return false;
2207 			}
2208 		}
2209 	}
2210 
2211 	return true;
2212 }
2213 
2214 /**
2215  * prb_read_valid() - Non-blocking read of a requested record or (if gone)
2216  *                    the next available record.
2217  *
2218  * @rb:  The ringbuffer to read from.
2219  * @seq: The sequence number of the record to read.
2220  * @r:   A record data buffer to store the read record to.
2221  *
2222  * This is the public function available to readers to read a record.
2223  *
2224  * The reader provides the @info and @text_buf buffers of @r to be
2225  * filled in. Any of the buffer pointers can be set to NULL if the reader
2226  * is not interested in that data. To ensure proper initialization of @r,
2227  * prb_rec_init_rd() should be used.
2228  *
2229  * Context: Any context.
2230  * Return: true if a record was read, otherwise false.
2231  *
2232  * On success, the reader must check r->info.seq to see which record was
2233  * actually read. This allows the reader to detect dropped records.
2234  *
2235  * Failure means @seq refers to a record not yet available to the reader.
2236  */
2237 bool prb_read_valid(struct printk_ringbuffer *rb, u64 seq,
2238 		    struct printk_record *r)
2239 {
2240 	return _prb_read_valid(rb, &seq, r, NULL);
2241 }
2242 EXPORT_SYMBOL_IF_KUNIT(prb_read_valid);
2243 
2244 /**
2245  * prb_read_valid_info() - Non-blocking read of meta data for a requested
2246  *                         record or (if gone) the next available record.
2247  *
2248  * @rb:         The ringbuffer to read from.
2249  * @seq:        The sequence number of the record to read.
2250  * @info:       A buffer to store the read record meta data to.
2251  * @line_count: A buffer to store the number of lines in the record text.
2252  *
2253  * This is the public function available to readers to read only the
2254  * meta data of a record.
2255  *
2256  * The reader provides the @info, @line_count buffers to be filled in.
2257  * Either of the buffer pointers can be set to NULL if the reader is not
2258  * interested in that data.
2259  *
2260  * Context: Any context.
2261  * Return: true if a record's meta data was read, otherwise false.
2262  *
2263  * On success, the reader must check info->seq to see which record meta data
2264  * was actually read. This allows the reader to detect dropped records.
2265  *
2266  * Failure means @seq refers to a record not yet available to the reader.
2267  */
2268 bool prb_read_valid_info(struct printk_ringbuffer *rb, u64 seq,
2269 			 struct printk_info *info, unsigned int *line_count)
2270 {
2271 	struct printk_record r;
2272 
2273 	prb_rec_init_rd(&r, info, NULL, 0);
2274 
2275 	return _prb_read_valid(rb, &seq, &r, line_count);
2276 }
2277 
2278 /**
2279  * prb_first_valid_seq() - Get the sequence number of the oldest available
2280  *                         record.
2281  *
2282  * @rb: The ringbuffer to get the sequence number from.
2283  *
2284  * This is the public function available to readers to see what the
2285  * first/oldest valid sequence number is.
2286  *
2287  * This provides readers a starting point to begin iterating the ringbuffer.
2288  *
2289  * Context: Any context.
2290  * Return: The sequence number of the first/oldest record or, if the
2291  *         ringbuffer is empty, 0 is returned.
2292  */
2293 u64 prb_first_valid_seq(struct printk_ringbuffer *rb)
2294 {
2295 	u64 seq = 0;
2296 
2297 	if (!_prb_read_valid(rb, &seq, NULL, NULL))
2298 		return 0;
2299 
2300 	return seq;
2301 }
2302 
2303 /**
2304  * prb_next_seq() - Get the sequence number after the last available record.
2305  *
2306  * @rb:  The ringbuffer to get the sequence number from.
2307  *
2308  * This is the public function available to readers to see what the next
2309  * newest sequence number available to readers will be.
2310  *
2311  * This provides readers a sequence number to jump to if all currently
2312  * available records should be skipped. It is guaranteed that all records
2313  * previous to the returned value have been finalized and are (or were)
2314  * available to the reader.
2315  *
2316  * Context: Any context.
2317  * Return: The sequence number of the next newest (not yet available) record
2318  *         for readers.
2319  */
2320 u64 prb_next_seq(struct printk_ringbuffer *rb)
2321 {
2322 	u64 seq;
2323 
2324 	seq = desc_last_finalized_seq(rb);
2325 
2326 	/*
2327 	 * Begin searching after the last finalized record.
2328 	 *
2329 	 * On 0, the search must begin at 0 because of hack#2
2330 	 * of the bootstrapping phase it is not known if a
2331 	 * record at index 0 exists.
2332 	 */
2333 	if (seq != 0)
2334 		seq++;
2335 
2336 	/*
2337 	 * The information about the last finalized @seq might be inaccurate.
2338 	 * Search forward to find the current one.
2339 	 */
2340 	while (_prb_read_valid(rb, &seq, NULL, NULL))
2341 		seq++;
2342 
2343 	return seq;
2344 }
2345 
2346 /**
2347  * prb_init() - Initialize a ringbuffer to use provided external buffers.
2348  *
2349  * @rb:       The ringbuffer to initialize.
2350  * @text_buf: The data buffer for text data.
2351  * @textbits: The size of @text_buf as a power-of-2 value.
2352  * @descs:    The descriptor buffer for ringbuffer records.
2353  * @descbits: The count of @descs items as a power-of-2 value.
2354  * @infos:    The printk_info buffer for ringbuffer records.
2355  *
2356  * This is the public function available to writers to setup a ringbuffer
2357  * during runtime using provided buffers.
2358  *
2359  * This must match the initialization of DEFINE_PRINTKRB().
2360  *
2361  * Context: Any context.
2362  */
2363 void prb_init(struct printk_ringbuffer *rb,
2364 	      char *text_buf, unsigned int textbits,
2365 	      struct prb_desc *descs, unsigned int descbits,
2366 	      struct printk_info *infos)
2367 {
2368 	memset(descs, 0, _DESCS_COUNT(descbits) * sizeof(descs[0]));
2369 	memset(infos, 0, _DESCS_COUNT(descbits) * sizeof(infos[0]));
2370 
2371 	rb->desc_ring.count_bits = descbits;
2372 	rb->desc_ring.descs = descs;
2373 	rb->desc_ring.infos = infos;
2374 	atomic_long_set(&rb->desc_ring.head_id, DESC0_ID(descbits));
2375 	atomic_long_set(&rb->desc_ring.tail_id, DESC0_ID(descbits));
2376 	atomic_long_set(&rb->desc_ring.last_finalized_seq, 0);
2377 
2378 	rb->text_data_ring.size_bits = textbits;
2379 	rb->text_data_ring.data = text_buf;
2380 	atomic_long_set(&rb->text_data_ring.head_lpos, BLK0_LPOS(textbits));
2381 	atomic_long_set(&rb->text_data_ring.tail_lpos, BLK0_LPOS(textbits));
2382 
2383 	atomic_long_set(&rb->fail, 0);
2384 
2385 	atomic_long_set(&(descs[_DESCS_COUNT(descbits) - 1].state_var), DESC0_SV(descbits));
2386 	descs[_DESCS_COUNT(descbits) - 1].text_blk_lpos.begin = FAILED_LPOS;
2387 	descs[_DESCS_COUNT(descbits) - 1].text_blk_lpos.next = FAILED_LPOS;
2388 
2389 	infos[0].seq = -(u64)_DESCS_COUNT(descbits);
2390 	infos[_DESCS_COUNT(descbits) - 1].seq = 0;
2391 }
2392 EXPORT_SYMBOL_IF_KUNIT(prb_init);
2393 
2394 /**
2395  * prb_record_text_space() - Query the full actual used ringbuffer space for
2396  *                           the text data of a reserved entry.
2397  *
2398  * @e: The successfully reserved entry to query.
2399  *
2400  * This is the public function available to writers to see how much actual
2401  * space is used in the ringbuffer to store the text data of the specified
2402  * entry.
2403  *
2404  * This function is only valid if @e has been successfully reserved using
2405  * prb_reserve().
2406  *
2407  * Context: Any context.
2408  * Return: The size in bytes used by the text data of the associated record.
2409  */
2410 unsigned int prb_record_text_space(struct prb_reserved_entry *e)
2411 {
2412 	return e->text_space;
2413 }
2414