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