xref: /linux/kernel/trace/ring_buffer.c (revision 2f87d0916ce0d2925cedbc9e8f5d6291ba2ac7b2)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Generic ring buffer
4  *
5  * Copyright (C) 2008 Steven Rostedt <srostedt@redhat.com>
6  */
7 #include <linux/trace_recursion.h>
8 #include <linux/trace_events.h>
9 #include <linux/ring_buffer.h>
10 #include <linux/trace_clock.h>
11 #include <linux/sched/clock.h>
12 #include <linux/cacheflush.h>
13 #include <linux/trace_seq.h>
14 #include <linux/spinlock.h>
15 #include <linux/irq_work.h>
16 #include <linux/security.h>
17 #include <linux/uaccess.h>
18 #include <linux/hardirq.h>
19 #include <linux/kthread.h>	/* for self test */
20 #include <linux/module.h>
21 #include <linux/percpu.h>
22 #include <linux/mutex.h>
23 #include <linux/delay.h>
24 #include <linux/slab.h>
25 #include <linux/init.h>
26 #include <linux/hash.h>
27 #include <linux/list.h>
28 #include <linux/cpu.h>
29 #include <linux/oom.h>
30 #include <linux/mm.h>
31 
32 #include <asm/local64.h>
33 #include <asm/local.h>
34 
35 #include "trace.h"
36 
37 /*
38  * The "absolute" timestamp in the buffer is only 59 bits.
39  * If a clock has the 5 MSBs set, it needs to be saved and
40  * reinserted.
41  */
42 #define TS_MSB		(0xf8ULL << 56)
43 #define ABS_TS_MASK	(~TS_MSB)
44 
45 static void update_pages_handler(struct work_struct *work);
46 
47 #define RING_BUFFER_META_MAGIC	0xBADFEED
48 
49 struct ring_buffer_meta {
50 	int		magic;
51 	int		struct_size;
52 	unsigned long	text_addr;
53 	unsigned long	data_addr;
54 	unsigned long	first_buffer;
55 	unsigned long	head_buffer;
56 	unsigned long	commit_buffer;
57 	__u32		subbuf_size;
58 	__u32		nr_subbufs;
59 	int		buffers[];
60 };
61 
62 /*
63  * The ring buffer header is special. We must manually up keep it.
64  */
ring_buffer_print_entry_header(struct trace_seq * s)65 int ring_buffer_print_entry_header(struct trace_seq *s)
66 {
67 	trace_seq_puts(s, "# compressed entry header\n");
68 	trace_seq_puts(s, "\ttype_len    :    5 bits\n");
69 	trace_seq_puts(s, "\ttime_delta  :   27 bits\n");
70 	trace_seq_puts(s, "\tarray       :   32 bits\n");
71 	trace_seq_putc(s, '\n');
72 	trace_seq_printf(s, "\tpadding     : type == %d\n",
73 			 RINGBUF_TYPE_PADDING);
74 	trace_seq_printf(s, "\ttime_extend : type == %d\n",
75 			 RINGBUF_TYPE_TIME_EXTEND);
76 	trace_seq_printf(s, "\ttime_stamp : type == %d\n",
77 			 RINGBUF_TYPE_TIME_STAMP);
78 	trace_seq_printf(s, "\tdata max type_len  == %d\n",
79 			 RINGBUF_TYPE_DATA_TYPE_LEN_MAX);
80 
81 	return !trace_seq_has_overflowed(s);
82 }
83 
84 /*
85  * The ring buffer is made up of a list of pages. A separate list of pages is
86  * allocated for each CPU. A writer may only write to a buffer that is
87  * associated with the CPU it is currently executing on.  A reader may read
88  * from any per cpu buffer.
89  *
90  * The reader is special. For each per cpu buffer, the reader has its own
91  * reader page. When a reader has read the entire reader page, this reader
92  * page is swapped with another page in the ring buffer.
93  *
94  * Now, as long as the writer is off the reader page, the reader can do what
95  * ever it wants with that page. The writer will never write to that page
96  * again (as long as it is out of the ring buffer).
97  *
98  * Here's some silly ASCII art.
99  *
100  *   +------+
101  *   |reader|          RING BUFFER
102  *   |page  |
103  *   +------+        +---+   +---+   +---+
104  *                   |   |-->|   |-->|   |
105  *                   +---+   +---+   +---+
106  *                     ^               |
107  *                     |               |
108  *                     +---------------+
109  *
110  *
111  *   +------+
112  *   |reader|          RING BUFFER
113  *   |page  |------------------v
114  *   +------+        +---+   +---+   +---+
115  *                   |   |-->|   |-->|   |
116  *                   +---+   +---+   +---+
117  *                     ^               |
118  *                     |               |
119  *                     +---------------+
120  *
121  *
122  *   +------+
123  *   |reader|          RING BUFFER
124  *   |page  |------------------v
125  *   +------+        +---+   +---+   +---+
126  *      ^            |   |-->|   |-->|   |
127  *      |            +---+   +---+   +---+
128  *      |                              |
129  *      |                              |
130  *      +------------------------------+
131  *
132  *
133  *   +------+
134  *   |buffer|          RING BUFFER
135  *   |page  |------------------v
136  *   +------+        +---+   +---+   +---+
137  *      ^            |   |   |   |-->|   |
138  *      |   New      +---+   +---+   +---+
139  *      |  Reader------^               |
140  *      |   page                       |
141  *      +------------------------------+
142  *
143  *
144  * After we make this swap, the reader can hand this page off to the splice
145  * code and be done with it. It can even allocate a new page if it needs to
146  * and swap that into the ring buffer.
147  *
148  * We will be using cmpxchg soon to make all this lockless.
149  *
150  */
151 
152 /* Used for individual buffers (after the counter) */
153 #define RB_BUFFER_OFF		(1 << 20)
154 
155 #define BUF_PAGE_HDR_SIZE offsetof(struct buffer_data_page, data)
156 
157 #define RB_EVNT_HDR_SIZE (offsetof(struct ring_buffer_event, array))
158 #define RB_ALIGNMENT		4U
159 #define RB_MAX_SMALL_DATA	(RB_ALIGNMENT * RINGBUF_TYPE_DATA_TYPE_LEN_MAX)
160 #define RB_EVNT_MIN_SIZE	8U	/* two 32bit words */
161 
162 #ifndef CONFIG_HAVE_64BIT_ALIGNED_ACCESS
163 # define RB_FORCE_8BYTE_ALIGNMENT	0
164 # define RB_ARCH_ALIGNMENT		RB_ALIGNMENT
165 #else
166 # define RB_FORCE_8BYTE_ALIGNMENT	1
167 # define RB_ARCH_ALIGNMENT		8U
168 #endif
169 
170 #define RB_ALIGN_DATA		__aligned(RB_ARCH_ALIGNMENT)
171 
172 /* define RINGBUF_TYPE_DATA for 'case RINGBUF_TYPE_DATA:' */
173 #define RINGBUF_TYPE_DATA 0 ... RINGBUF_TYPE_DATA_TYPE_LEN_MAX
174 
175 enum {
176 	RB_LEN_TIME_EXTEND = 8,
177 	RB_LEN_TIME_STAMP =  8,
178 };
179 
180 #define skip_time_extend(event) \
181 	((struct ring_buffer_event *)((char *)event + RB_LEN_TIME_EXTEND))
182 
183 #define extended_time(event) \
184 	(event->type_len >= RINGBUF_TYPE_TIME_EXTEND)
185 
rb_null_event(struct ring_buffer_event * event)186 static inline bool rb_null_event(struct ring_buffer_event *event)
187 {
188 	return event->type_len == RINGBUF_TYPE_PADDING && !event->time_delta;
189 }
190 
rb_event_set_padding(struct ring_buffer_event * event)191 static void rb_event_set_padding(struct ring_buffer_event *event)
192 {
193 	/* padding has a NULL time_delta */
194 	event->type_len = RINGBUF_TYPE_PADDING;
195 	event->time_delta = 0;
196 }
197 
198 static unsigned
rb_event_data_length(struct ring_buffer_event * event)199 rb_event_data_length(struct ring_buffer_event *event)
200 {
201 	unsigned length;
202 
203 	if (event->type_len)
204 		length = event->type_len * RB_ALIGNMENT;
205 	else
206 		length = event->array[0];
207 	return length + RB_EVNT_HDR_SIZE;
208 }
209 
210 /*
211  * Return the length of the given event. Will return
212  * the length of the time extend if the event is a
213  * time extend.
214  */
215 static inline unsigned
rb_event_length(struct ring_buffer_event * event)216 rb_event_length(struct ring_buffer_event *event)
217 {
218 	switch (event->type_len) {
219 	case RINGBUF_TYPE_PADDING:
220 		if (rb_null_event(event))
221 			/* undefined */
222 			return -1;
223 		return  event->array[0] + RB_EVNT_HDR_SIZE;
224 
225 	case RINGBUF_TYPE_TIME_EXTEND:
226 		return RB_LEN_TIME_EXTEND;
227 
228 	case RINGBUF_TYPE_TIME_STAMP:
229 		return RB_LEN_TIME_STAMP;
230 
231 	case RINGBUF_TYPE_DATA:
232 		return rb_event_data_length(event);
233 	default:
234 		WARN_ON_ONCE(1);
235 	}
236 	/* not hit */
237 	return 0;
238 }
239 
240 /*
241  * Return total length of time extend and data,
242  *   or just the event length for all other events.
243  */
244 static inline unsigned
rb_event_ts_length(struct ring_buffer_event * event)245 rb_event_ts_length(struct ring_buffer_event *event)
246 {
247 	unsigned len = 0;
248 
249 	if (extended_time(event)) {
250 		/* time extends include the data event after it */
251 		len = RB_LEN_TIME_EXTEND;
252 		event = skip_time_extend(event);
253 	}
254 	return len + rb_event_length(event);
255 }
256 
257 /**
258  * ring_buffer_event_length - return the length of the event
259  * @event: the event to get the length of
260  *
261  * Returns the size of the data load of a data event.
262  * If the event is something other than a data event, it
263  * returns the size of the event itself. With the exception
264  * of a TIME EXTEND, where it still returns the size of the
265  * data load of the data event after it.
266  */
ring_buffer_event_length(struct ring_buffer_event * event)267 unsigned ring_buffer_event_length(struct ring_buffer_event *event)
268 {
269 	unsigned length;
270 
271 	if (extended_time(event))
272 		event = skip_time_extend(event);
273 
274 	length = rb_event_length(event);
275 	if (event->type_len > RINGBUF_TYPE_DATA_TYPE_LEN_MAX)
276 		return length;
277 	length -= RB_EVNT_HDR_SIZE;
278 	if (length > RB_MAX_SMALL_DATA + sizeof(event->array[0]))
279                 length -= sizeof(event->array[0]);
280 	return length;
281 }
282 EXPORT_SYMBOL_GPL(ring_buffer_event_length);
283 
284 /* inline for ring buffer fast paths */
285 static __always_inline void *
rb_event_data(struct ring_buffer_event * event)286 rb_event_data(struct ring_buffer_event *event)
287 {
288 	if (extended_time(event))
289 		event = skip_time_extend(event);
290 	WARN_ON_ONCE(event->type_len > RINGBUF_TYPE_DATA_TYPE_LEN_MAX);
291 	/* If length is in len field, then array[0] has the data */
292 	if (event->type_len)
293 		return (void *)&event->array[0];
294 	/* Otherwise length is in array[0] and array[1] has the data */
295 	return (void *)&event->array[1];
296 }
297 
298 /**
299  * ring_buffer_event_data - return the data of the event
300  * @event: the event to get the data from
301  */
ring_buffer_event_data(struct ring_buffer_event * event)302 void *ring_buffer_event_data(struct ring_buffer_event *event)
303 {
304 	return rb_event_data(event);
305 }
306 EXPORT_SYMBOL_GPL(ring_buffer_event_data);
307 
308 #define for_each_buffer_cpu(buffer, cpu)		\
309 	for_each_cpu(cpu, buffer->cpumask)
310 
311 #define for_each_online_buffer_cpu(buffer, cpu)		\
312 	for_each_cpu_and(cpu, buffer->cpumask, cpu_online_mask)
313 
314 #define TS_SHIFT	27
315 #define TS_MASK		((1ULL << TS_SHIFT) - 1)
316 #define TS_DELTA_TEST	(~TS_MASK)
317 
rb_event_time_stamp(struct ring_buffer_event * event)318 static u64 rb_event_time_stamp(struct ring_buffer_event *event)
319 {
320 	u64 ts;
321 
322 	ts = event->array[0];
323 	ts <<= TS_SHIFT;
324 	ts += event->time_delta;
325 
326 	return ts;
327 }
328 
329 /* Flag when events were overwritten */
330 #define RB_MISSED_EVENTS	(1 << 31)
331 /* Missed count stored at end */
332 #define RB_MISSED_STORED	(1 << 30)
333 
334 #define RB_MISSED_MASK		(3 << 30)
335 
336 struct buffer_data_page {
337 	u64		 time_stamp;	/* page time stamp */
338 	local_t		 commit;	/* write committed index */
339 	unsigned char	 data[] RB_ALIGN_DATA;	/* data of buffer page */
340 };
341 
342 struct buffer_data_read_page {
343 	unsigned		order;	/* order of the page */
344 	struct buffer_data_page	*data;	/* actual data, stored in this page */
345 };
346 
347 /*
348  * Note, the buffer_page list must be first. The buffer pages
349  * are allocated in cache lines, which means that each buffer
350  * page will be at the beginning of a cache line, and thus
351  * the least significant bits will be zero. We use this to
352  * add flags in the list struct pointers, to make the ring buffer
353  * lockless.
354  */
355 struct buffer_page {
356 	struct list_head list;		/* list of buffer pages */
357 	local_t		 write;		/* index for next write */
358 	unsigned	 read;		/* index for next read */
359 	local_t		 entries;	/* entries on this page */
360 	unsigned long	 real_end;	/* real end of data */
361 	unsigned	 order;		/* order of the page */
362 	u32		 id:30;		/* ID for external mapping */
363 	u32		 range:1;	/* Mapped via a range */
364 	struct buffer_data_page *page;	/* Actual data page */
365 };
366 
367 /*
368  * The buffer page counters, write and entries, must be reset
369  * atomically when crossing page boundaries. To synchronize this
370  * update, two counters are inserted into the number. One is
371  * the actual counter for the write position or count on the page.
372  *
373  * The other is a counter of updaters. Before an update happens
374  * the update partition of the counter is incremented. This will
375  * allow the updater to update the counter atomically.
376  *
377  * The counter is 20 bits, and the state data is 12.
378  */
379 #define RB_WRITE_MASK		0xfffff
380 #define RB_WRITE_INTCNT		(1 << 20)
381 
rb_init_page(struct buffer_data_page * bpage)382 static void rb_init_page(struct buffer_data_page *bpage)
383 {
384 	local_set(&bpage->commit, 0);
385 }
386 
rb_page_commit(struct buffer_page * bpage)387 static __always_inline unsigned int rb_page_commit(struct buffer_page *bpage)
388 {
389 	return local_read(&bpage->page->commit);
390 }
391 
free_buffer_page(struct buffer_page * bpage)392 static void free_buffer_page(struct buffer_page *bpage)
393 {
394 	/* Range pages are not to be freed */
395 	if (!bpage->range)
396 		free_pages((unsigned long)bpage->page, bpage->order);
397 	kfree(bpage);
398 }
399 
400 /*
401  * We need to fit the time_stamp delta into 27 bits.
402  */
test_time_stamp(u64 delta)403 static inline bool test_time_stamp(u64 delta)
404 {
405 	return !!(delta & TS_DELTA_TEST);
406 }
407 
408 struct rb_irq_work {
409 	struct irq_work			work;
410 	wait_queue_head_t		waiters;
411 	wait_queue_head_t		full_waiters;
412 	atomic_t			seq;
413 	bool				waiters_pending;
414 	bool				full_waiters_pending;
415 	bool				wakeup_full;
416 };
417 
418 /*
419  * Structure to hold event state and handle nested events.
420  */
421 struct rb_event_info {
422 	u64			ts;
423 	u64			delta;
424 	u64			before;
425 	u64			after;
426 	unsigned long		length;
427 	struct buffer_page	*tail_page;
428 	int			add_timestamp;
429 };
430 
431 /*
432  * Used for the add_timestamp
433  *  NONE
434  *  EXTEND - wants a time extend
435  *  ABSOLUTE - the buffer requests all events to have absolute time stamps
436  *  FORCE - force a full time stamp.
437  */
438 enum {
439 	RB_ADD_STAMP_NONE		= 0,
440 	RB_ADD_STAMP_EXTEND		= BIT(1),
441 	RB_ADD_STAMP_ABSOLUTE		= BIT(2),
442 	RB_ADD_STAMP_FORCE		= BIT(3)
443 };
444 /*
445  * Used for which event context the event is in.
446  *  TRANSITION = 0
447  *  NMI     = 1
448  *  IRQ     = 2
449  *  SOFTIRQ = 3
450  *  NORMAL  = 4
451  *
452  * See trace_recursive_lock() comment below for more details.
453  */
454 enum {
455 	RB_CTX_TRANSITION,
456 	RB_CTX_NMI,
457 	RB_CTX_IRQ,
458 	RB_CTX_SOFTIRQ,
459 	RB_CTX_NORMAL,
460 	RB_CTX_MAX
461 };
462 
463 struct rb_time_struct {
464 	local64_t	time;
465 };
466 typedef struct rb_time_struct rb_time_t;
467 
468 #define MAX_NEST	5
469 
470 /*
471  * head_page == tail_page && head == tail then buffer is empty.
472  */
473 struct ring_buffer_per_cpu {
474 	int				cpu;
475 	atomic_t			record_disabled;
476 	atomic_t			resize_disabled;
477 	struct trace_buffer	*buffer;
478 	raw_spinlock_t			reader_lock;	/* serialize readers */
479 	arch_spinlock_t			lock;
480 	struct lock_class_key		lock_key;
481 	struct buffer_data_page		*free_page;
482 	unsigned long			nr_pages;
483 	unsigned int			current_context;
484 	struct list_head		*pages;
485 	struct buffer_page		*head_page;	/* read from head */
486 	struct buffer_page		*tail_page;	/* write to tail */
487 	struct buffer_page		*commit_page;	/* committed pages */
488 	struct buffer_page		*reader_page;
489 	unsigned long			lost_events;
490 	unsigned long			last_overrun;
491 	unsigned long			nest;
492 	local_t				entries_bytes;
493 	local_t				entries;
494 	local_t				overrun;
495 	local_t				commit_overrun;
496 	local_t				dropped_events;
497 	local_t				committing;
498 	local_t				commits;
499 	local_t				pages_touched;
500 	local_t				pages_lost;
501 	local_t				pages_read;
502 	long				last_pages_touch;
503 	size_t				shortest_full;
504 	unsigned long			read;
505 	unsigned long			read_bytes;
506 	rb_time_t			write_stamp;
507 	rb_time_t			before_stamp;
508 	u64				event_stamp[MAX_NEST];
509 	u64				read_stamp;
510 	/* pages removed since last reset */
511 	unsigned long			pages_removed;
512 
513 	unsigned int			mapped;
514 	unsigned int			user_mapped;	/* user space mapping */
515 	struct mutex			mapping_lock;
516 	unsigned long			*subbuf_ids;	/* ID to subbuf VA */
517 	struct trace_buffer_meta	*meta_page;
518 	struct ring_buffer_meta		*ring_meta;
519 
520 	/* ring buffer pages to update, > 0 to add, < 0 to remove */
521 	long				nr_pages_to_update;
522 	struct list_head		new_pages; /* new pages to add */
523 	struct work_struct		update_pages_work;
524 	struct completion		update_done;
525 
526 	struct rb_irq_work		irq_work;
527 };
528 
529 struct trace_buffer {
530 	unsigned			flags;
531 	int				cpus;
532 	atomic_t			record_disabled;
533 	atomic_t			resizing;
534 	cpumask_var_t			cpumask;
535 
536 	struct lock_class_key		*reader_lock_key;
537 
538 	struct mutex			mutex;
539 
540 	struct ring_buffer_per_cpu	**buffers;
541 
542 	struct hlist_node		node;
543 	u64				(*clock)(void);
544 
545 	struct rb_irq_work		irq_work;
546 	bool				time_stamp_abs;
547 
548 	unsigned long			range_addr_start;
549 	unsigned long			range_addr_end;
550 
551 	long				last_text_delta;
552 	long				last_data_delta;
553 
554 	unsigned int			subbuf_size;
555 	unsigned int			subbuf_order;
556 	unsigned int			max_data_size;
557 };
558 
559 struct ring_buffer_iter {
560 	struct ring_buffer_per_cpu	*cpu_buffer;
561 	unsigned long			head;
562 	unsigned long			next_event;
563 	struct buffer_page		*head_page;
564 	struct buffer_page		*cache_reader_page;
565 	unsigned long			cache_read;
566 	unsigned long			cache_pages_removed;
567 	u64				read_stamp;
568 	u64				page_stamp;
569 	struct ring_buffer_event	*event;
570 	size_t				event_size;
571 	int				missed_events;
572 };
573 
ring_buffer_print_page_header(struct trace_buffer * buffer,struct trace_seq * s)574 int ring_buffer_print_page_header(struct trace_buffer *buffer, struct trace_seq *s)
575 {
576 	struct buffer_data_page field;
577 
578 	trace_seq_printf(s, "\tfield: u64 timestamp;\t"
579 			 "offset:0;\tsize:%u;\tsigned:%u;\n",
580 			 (unsigned int)sizeof(field.time_stamp),
581 			 (unsigned int)is_signed_type(u64));
582 
583 	trace_seq_printf(s, "\tfield: local_t commit;\t"
584 			 "offset:%u;\tsize:%u;\tsigned:%u;\n",
585 			 (unsigned int)offsetof(typeof(field), commit),
586 			 (unsigned int)sizeof(field.commit),
587 			 (unsigned int)is_signed_type(long));
588 
589 	trace_seq_printf(s, "\tfield: int overwrite;\t"
590 			 "offset:%u;\tsize:%u;\tsigned:%u;\n",
591 			 (unsigned int)offsetof(typeof(field), commit),
592 			 1,
593 			 (unsigned int)is_signed_type(long));
594 
595 	trace_seq_printf(s, "\tfield: char data;\t"
596 			 "offset:%u;\tsize:%u;\tsigned:%u;\n",
597 			 (unsigned int)offsetof(typeof(field), data),
598 			 (unsigned int)buffer->subbuf_size,
599 			 (unsigned int)is_signed_type(char));
600 
601 	return !trace_seq_has_overflowed(s);
602 }
603 
rb_time_read(rb_time_t * t,u64 * ret)604 static inline void rb_time_read(rb_time_t *t, u64 *ret)
605 {
606 	*ret = local64_read(&t->time);
607 }
rb_time_set(rb_time_t * t,u64 val)608 static void rb_time_set(rb_time_t *t, u64 val)
609 {
610 	local64_set(&t->time, val);
611 }
612 
613 /*
614  * Enable this to make sure that the event passed to
615  * ring_buffer_event_time_stamp() is not committed and also
616  * is on the buffer that it passed in.
617  */
618 //#define RB_VERIFY_EVENT
619 #ifdef RB_VERIFY_EVENT
620 static struct list_head *rb_list_head(struct list_head *list);
verify_event(struct ring_buffer_per_cpu * cpu_buffer,void * event)621 static void verify_event(struct ring_buffer_per_cpu *cpu_buffer,
622 			 void *event)
623 {
624 	struct buffer_page *page = cpu_buffer->commit_page;
625 	struct buffer_page *tail_page = READ_ONCE(cpu_buffer->tail_page);
626 	struct list_head *next;
627 	long commit, write;
628 	unsigned long addr = (unsigned long)event;
629 	bool done = false;
630 	int stop = 0;
631 
632 	/* Make sure the event exists and is not committed yet */
633 	do {
634 		if (page == tail_page || WARN_ON_ONCE(stop++ > 100))
635 			done = true;
636 		commit = local_read(&page->page->commit);
637 		write = local_read(&page->write);
638 		if (addr >= (unsigned long)&page->page->data[commit] &&
639 		    addr < (unsigned long)&page->page->data[write])
640 			return;
641 
642 		next = rb_list_head(page->list.next);
643 		page = list_entry(next, struct buffer_page, list);
644 	} while (!done);
645 	WARN_ON_ONCE(1);
646 }
647 #else
verify_event(struct ring_buffer_per_cpu * cpu_buffer,void * event)648 static inline void verify_event(struct ring_buffer_per_cpu *cpu_buffer,
649 			 void *event)
650 {
651 }
652 #endif
653 
654 /*
655  * The absolute time stamp drops the 5 MSBs and some clocks may
656  * require them. The rb_fix_abs_ts() will take a previous full
657  * time stamp, and add the 5 MSB of that time stamp on to the
658  * saved absolute time stamp. Then they are compared in case of
659  * the unlikely event that the latest time stamp incremented
660  * the 5 MSB.
661  */
rb_fix_abs_ts(u64 abs,u64 save_ts)662 static inline u64 rb_fix_abs_ts(u64 abs, u64 save_ts)
663 {
664 	if (save_ts & TS_MSB) {
665 		abs |= save_ts & TS_MSB;
666 		/* Check for overflow */
667 		if (unlikely(abs < save_ts))
668 			abs += 1ULL << 59;
669 	}
670 	return abs;
671 }
672 
673 static inline u64 rb_time_stamp(struct trace_buffer *buffer);
674 
675 /**
676  * ring_buffer_event_time_stamp - return the event's current time stamp
677  * @buffer: The buffer that the event is on
678  * @event: the event to get the time stamp of
679  *
680  * Note, this must be called after @event is reserved, and before it is
681  * committed to the ring buffer. And must be called from the same
682  * context where the event was reserved (normal, softirq, irq, etc).
683  *
684  * Returns the time stamp associated with the current event.
685  * If the event has an extended time stamp, then that is used as
686  * the time stamp to return.
687  * In the highly unlikely case that the event was nested more than
688  * the max nesting, then the write_stamp of the buffer is returned,
689  * otherwise  current time is returned, but that really neither of
690  * the last two cases should ever happen.
691  */
ring_buffer_event_time_stamp(struct trace_buffer * buffer,struct ring_buffer_event * event)692 u64 ring_buffer_event_time_stamp(struct trace_buffer *buffer,
693 				 struct ring_buffer_event *event)
694 {
695 	struct ring_buffer_per_cpu *cpu_buffer = buffer->buffers[smp_processor_id()];
696 	unsigned int nest;
697 	u64 ts;
698 
699 	/* If the event includes an absolute time, then just use that */
700 	if (event->type_len == RINGBUF_TYPE_TIME_STAMP) {
701 		ts = rb_event_time_stamp(event);
702 		return rb_fix_abs_ts(ts, cpu_buffer->tail_page->page->time_stamp);
703 	}
704 
705 	nest = local_read(&cpu_buffer->committing);
706 	verify_event(cpu_buffer, event);
707 	if (WARN_ON_ONCE(!nest))
708 		goto fail;
709 
710 	/* Read the current saved nesting level time stamp */
711 	if (likely(--nest < MAX_NEST))
712 		return cpu_buffer->event_stamp[nest];
713 
714 	/* Shouldn't happen, warn if it does */
715 	WARN_ONCE(1, "nest (%d) greater than max", nest);
716 
717  fail:
718 	rb_time_read(&cpu_buffer->write_stamp, &ts);
719 
720 	return ts;
721 }
722 
723 /**
724  * ring_buffer_nr_dirty_pages - get the number of used pages in the ring buffer
725  * @buffer: The ring_buffer to get the number of pages from
726  * @cpu: The cpu of the ring_buffer to get the number of pages from
727  *
728  * Returns the number of pages that have content in the ring buffer.
729  */
ring_buffer_nr_dirty_pages(struct trace_buffer * buffer,int cpu)730 size_t ring_buffer_nr_dirty_pages(struct trace_buffer *buffer, int cpu)
731 {
732 	size_t read;
733 	size_t lost;
734 	size_t cnt;
735 
736 	read = local_read(&buffer->buffers[cpu]->pages_read);
737 	lost = local_read(&buffer->buffers[cpu]->pages_lost);
738 	cnt = local_read(&buffer->buffers[cpu]->pages_touched);
739 
740 	if (WARN_ON_ONCE(cnt < lost))
741 		return 0;
742 
743 	cnt -= lost;
744 
745 	/* The reader can read an empty page, but not more than that */
746 	if (cnt < read) {
747 		WARN_ON_ONCE(read > cnt + 1);
748 		return 0;
749 	}
750 
751 	return cnt - read;
752 }
753 
full_hit(struct trace_buffer * buffer,int cpu,int full)754 static __always_inline bool full_hit(struct trace_buffer *buffer, int cpu, int full)
755 {
756 	struct ring_buffer_per_cpu *cpu_buffer = buffer->buffers[cpu];
757 	size_t nr_pages;
758 	size_t dirty;
759 
760 	nr_pages = cpu_buffer->nr_pages;
761 	if (!nr_pages || !full)
762 		return true;
763 
764 	/*
765 	 * Add one as dirty will never equal nr_pages, as the sub-buffer
766 	 * that the writer is on is not counted as dirty.
767 	 * This is needed if "buffer_percent" is set to 100.
768 	 */
769 	dirty = ring_buffer_nr_dirty_pages(buffer, cpu) + 1;
770 
771 	return (dirty * 100) >= (full * nr_pages);
772 }
773 
774 /*
775  * rb_wake_up_waiters - wake up tasks waiting for ring buffer input
776  *
777  * Schedules a delayed work to wake up any task that is blocked on the
778  * ring buffer waiters queue.
779  */
rb_wake_up_waiters(struct irq_work * work)780 static void rb_wake_up_waiters(struct irq_work *work)
781 {
782 	struct rb_irq_work *rbwork = container_of(work, struct rb_irq_work, work);
783 
784 	/* For waiters waiting for the first wake up */
785 	(void)atomic_fetch_inc_release(&rbwork->seq);
786 
787 	wake_up_all(&rbwork->waiters);
788 	if (rbwork->full_waiters_pending || rbwork->wakeup_full) {
789 		/* Only cpu_buffer sets the above flags */
790 		struct ring_buffer_per_cpu *cpu_buffer =
791 			container_of(rbwork, struct ring_buffer_per_cpu, irq_work);
792 
793 		/* Called from interrupt context */
794 		raw_spin_lock(&cpu_buffer->reader_lock);
795 		rbwork->wakeup_full = false;
796 		rbwork->full_waiters_pending = false;
797 
798 		/* Waking up all waiters, they will reset the shortest full */
799 		cpu_buffer->shortest_full = 0;
800 		raw_spin_unlock(&cpu_buffer->reader_lock);
801 
802 		wake_up_all(&rbwork->full_waiters);
803 	}
804 }
805 
806 /**
807  * ring_buffer_wake_waiters - wake up any waiters on this ring buffer
808  * @buffer: The ring buffer to wake waiters on
809  * @cpu: The CPU buffer to wake waiters on
810  *
811  * In the case of a file that represents a ring buffer is closing,
812  * it is prudent to wake up any waiters that are on this.
813  */
ring_buffer_wake_waiters(struct trace_buffer * buffer,int cpu)814 void ring_buffer_wake_waiters(struct trace_buffer *buffer, int cpu)
815 {
816 	struct ring_buffer_per_cpu *cpu_buffer;
817 	struct rb_irq_work *rbwork;
818 
819 	if (!buffer)
820 		return;
821 
822 	if (cpu == RING_BUFFER_ALL_CPUS) {
823 
824 		/* Wake up individual ones too. One level recursion */
825 		for_each_buffer_cpu(buffer, cpu)
826 			ring_buffer_wake_waiters(buffer, cpu);
827 
828 		rbwork = &buffer->irq_work;
829 	} else {
830 		if (WARN_ON_ONCE(!buffer->buffers))
831 			return;
832 		if (WARN_ON_ONCE(cpu >= nr_cpu_ids))
833 			return;
834 
835 		cpu_buffer = buffer->buffers[cpu];
836 		/* The CPU buffer may not have been initialized yet */
837 		if (!cpu_buffer)
838 			return;
839 		rbwork = &cpu_buffer->irq_work;
840 	}
841 
842 	/* This can be called in any context */
843 	irq_work_queue(&rbwork->work);
844 }
845 
rb_watermark_hit(struct trace_buffer * buffer,int cpu,int full)846 static bool rb_watermark_hit(struct trace_buffer *buffer, int cpu, int full)
847 {
848 	struct ring_buffer_per_cpu *cpu_buffer;
849 	bool ret = false;
850 
851 	/* Reads of all CPUs always waits for any data */
852 	if (cpu == RING_BUFFER_ALL_CPUS)
853 		return !ring_buffer_empty(buffer);
854 
855 	cpu_buffer = buffer->buffers[cpu];
856 
857 	if (!ring_buffer_empty_cpu(buffer, cpu)) {
858 		unsigned long flags;
859 		bool pagebusy;
860 
861 		if (!full)
862 			return true;
863 
864 		raw_spin_lock_irqsave(&cpu_buffer->reader_lock, flags);
865 		pagebusy = cpu_buffer->reader_page == cpu_buffer->commit_page;
866 		ret = !pagebusy && full_hit(buffer, cpu, full);
867 
868 		if (!ret && (!cpu_buffer->shortest_full ||
869 			     cpu_buffer->shortest_full > full)) {
870 		    cpu_buffer->shortest_full = full;
871 		}
872 		raw_spin_unlock_irqrestore(&cpu_buffer->reader_lock, flags);
873 	}
874 	return ret;
875 }
876 
877 static inline bool
rb_wait_cond(struct rb_irq_work * rbwork,struct trace_buffer * buffer,int cpu,int full,ring_buffer_cond_fn cond,void * data)878 rb_wait_cond(struct rb_irq_work *rbwork, struct trace_buffer *buffer,
879 	     int cpu, int full, ring_buffer_cond_fn cond, void *data)
880 {
881 	if (rb_watermark_hit(buffer, cpu, full))
882 		return true;
883 
884 	if (cond(data))
885 		return true;
886 
887 	/*
888 	 * The events can happen in critical sections where
889 	 * checking a work queue can cause deadlocks.
890 	 * After adding a task to the queue, this flag is set
891 	 * only to notify events to try to wake up the queue
892 	 * using irq_work.
893 	 *
894 	 * We don't clear it even if the buffer is no longer
895 	 * empty. The flag only causes the next event to run
896 	 * irq_work to do the work queue wake up. The worse
897 	 * that can happen if we race with !trace_empty() is that
898 	 * an event will cause an irq_work to try to wake up
899 	 * an empty queue.
900 	 *
901 	 * There's no reason to protect this flag either, as
902 	 * the work queue and irq_work logic will do the necessary
903 	 * synchronization for the wake ups. The only thing
904 	 * that is necessary is that the wake up happens after
905 	 * a task has been queued. It's OK for spurious wake ups.
906 	 */
907 	if (full)
908 		rbwork->full_waiters_pending = true;
909 	else
910 		rbwork->waiters_pending = true;
911 
912 	return false;
913 }
914 
915 struct rb_wait_data {
916 	struct rb_irq_work		*irq_work;
917 	int				seq;
918 };
919 
920 /*
921  * The default wait condition for ring_buffer_wait() is to just to exit the
922  * wait loop the first time it is woken up.
923  */
rb_wait_once(void * data)924 static bool rb_wait_once(void *data)
925 {
926 	struct rb_wait_data *rdata = data;
927 	struct rb_irq_work *rbwork = rdata->irq_work;
928 
929 	return atomic_read_acquire(&rbwork->seq) != rdata->seq;
930 }
931 
932 /**
933  * ring_buffer_wait - wait for input to the ring buffer
934  * @buffer: buffer to wait on
935  * @cpu: the cpu buffer to wait on
936  * @full: wait until the percentage of pages are available, if @cpu != RING_BUFFER_ALL_CPUS
937  * @cond: condition function to break out of wait (NULL to run once)
938  * @data: the data to pass to @cond.
939  *
940  * If @cpu == RING_BUFFER_ALL_CPUS then the task will wake up as soon
941  * as data is added to any of the @buffer's cpu buffers. Otherwise
942  * it will wait for data to be added to a specific cpu buffer.
943  */
ring_buffer_wait(struct trace_buffer * buffer,int cpu,int full,ring_buffer_cond_fn cond,void * data)944 int ring_buffer_wait(struct trace_buffer *buffer, int cpu, int full,
945 		     ring_buffer_cond_fn cond, void *data)
946 {
947 	struct ring_buffer_per_cpu *cpu_buffer;
948 	struct wait_queue_head *waitq;
949 	struct rb_irq_work *rbwork;
950 	struct rb_wait_data rdata;
951 	int ret = 0;
952 
953 	/*
954 	 * Depending on what the caller is waiting for, either any
955 	 * data in any cpu buffer, or a specific buffer, put the
956 	 * caller on the appropriate wait queue.
957 	 */
958 	if (cpu == RING_BUFFER_ALL_CPUS) {
959 		rbwork = &buffer->irq_work;
960 		/* Full only makes sense on per cpu reads */
961 		full = 0;
962 	} else {
963 		if (!cpumask_test_cpu(cpu, buffer->cpumask))
964 			return -ENODEV;
965 		cpu_buffer = buffer->buffers[cpu];
966 		rbwork = &cpu_buffer->irq_work;
967 	}
968 
969 	if (full)
970 		waitq = &rbwork->full_waiters;
971 	else
972 		waitq = &rbwork->waiters;
973 
974 	/* Set up to exit loop as soon as it is woken */
975 	if (!cond) {
976 		cond = rb_wait_once;
977 		rdata.irq_work = rbwork;
978 		rdata.seq = atomic_read_acquire(&rbwork->seq);
979 		data = &rdata;
980 	}
981 
982 	ret = wait_event_interruptible((*waitq),
983 				rb_wait_cond(rbwork, buffer, cpu, full, cond, data));
984 
985 	return ret;
986 }
987 
988 /**
989  * ring_buffer_poll_wait - poll on buffer input
990  * @buffer: buffer to wait on
991  * @cpu: the cpu buffer to wait on
992  * @filp: the file descriptor
993  * @poll_table: The poll descriptor
994  * @full: wait until the percentage of pages are available, if @cpu != RING_BUFFER_ALL_CPUS
995  *
996  * If @cpu == RING_BUFFER_ALL_CPUS then the task will wake up as soon
997  * as data is added to any of the @buffer's cpu buffers. Otherwise
998  * it will wait for data to be added to a specific cpu buffer.
999  *
1000  * Returns EPOLLIN | EPOLLRDNORM if data exists in the buffers,
1001  * zero otherwise.
1002  */
ring_buffer_poll_wait(struct trace_buffer * buffer,int cpu,struct file * filp,poll_table * poll_table,int full)1003 __poll_t ring_buffer_poll_wait(struct trace_buffer *buffer, int cpu,
1004 			  struct file *filp, poll_table *poll_table, int full)
1005 {
1006 	struct ring_buffer_per_cpu *cpu_buffer;
1007 	struct rb_irq_work *rbwork;
1008 
1009 	if (cpu == RING_BUFFER_ALL_CPUS) {
1010 		rbwork = &buffer->irq_work;
1011 		full = 0;
1012 	} else {
1013 		if (!cpumask_test_cpu(cpu, buffer->cpumask))
1014 			return EPOLLERR;
1015 
1016 		cpu_buffer = buffer->buffers[cpu];
1017 		rbwork = &cpu_buffer->irq_work;
1018 	}
1019 
1020 	if (full) {
1021 		poll_wait(filp, &rbwork->full_waiters, poll_table);
1022 
1023 		if (rb_watermark_hit(buffer, cpu, full))
1024 			return EPOLLIN | EPOLLRDNORM;
1025 		/*
1026 		 * Only allow full_waiters_pending update to be seen after
1027 		 * the shortest_full is set (in rb_watermark_hit). If the
1028 		 * writer sees the full_waiters_pending flag set, it will
1029 		 * compare the amount in the ring buffer to shortest_full.
1030 		 * If the amount in the ring buffer is greater than the
1031 		 * shortest_full percent, it will call the irq_work handler
1032 		 * to wake up this list. The irq_handler will reset shortest_full
1033 		 * back to zero. That's done under the reader_lock, but
1034 		 * the below smp_mb() makes sure that the update to
1035 		 * full_waiters_pending doesn't leak up into the above.
1036 		 */
1037 		smp_mb();
1038 		rbwork->full_waiters_pending = true;
1039 		return 0;
1040 	}
1041 
1042 	poll_wait(filp, &rbwork->waiters, poll_table);
1043 	rbwork->waiters_pending = true;
1044 
1045 	/*
1046 	 * There's a tight race between setting the waiters_pending and
1047 	 * checking if the ring buffer is empty.  Once the waiters_pending bit
1048 	 * is set, the next event will wake the task up, but we can get stuck
1049 	 * if there's only a single event in.
1050 	 *
1051 	 * FIXME: Ideally, we need a memory barrier on the writer side as well,
1052 	 * but adding a memory barrier to all events will cause too much of a
1053 	 * performance hit in the fast path.  We only need a memory barrier when
1054 	 * the buffer goes from empty to having content.  But as this race is
1055 	 * extremely small, and it's not a problem if another event comes in, we
1056 	 * will fix it later.
1057 	 */
1058 	smp_mb();
1059 
1060 	if ((cpu == RING_BUFFER_ALL_CPUS && !ring_buffer_empty(buffer)) ||
1061 	    (cpu != RING_BUFFER_ALL_CPUS && !ring_buffer_empty_cpu(buffer, cpu)))
1062 		return EPOLLIN | EPOLLRDNORM;
1063 	return 0;
1064 }
1065 
1066 /* buffer may be either ring_buffer or ring_buffer_per_cpu */
1067 #define RB_WARN_ON(b, cond)						\
1068 	({								\
1069 		int _____ret = unlikely(cond);				\
1070 		if (_____ret) {						\
1071 			if (__same_type(*(b), struct ring_buffer_per_cpu)) { \
1072 				struct ring_buffer_per_cpu *__b =	\
1073 					(void *)b;			\
1074 				atomic_inc(&__b->buffer->record_disabled); \
1075 			} else						\
1076 				atomic_inc(&b->record_disabled);	\
1077 			WARN_ON(1);					\
1078 		}							\
1079 		_____ret;						\
1080 	})
1081 
1082 /* Up this if you want to test the TIME_EXTENTS and normalization */
1083 #define DEBUG_SHIFT 0
1084 
rb_time_stamp(struct trace_buffer * buffer)1085 static inline u64 rb_time_stamp(struct trace_buffer *buffer)
1086 {
1087 	u64 ts;
1088 
1089 	/* Skip retpolines :-( */
1090 	if (IS_ENABLED(CONFIG_MITIGATION_RETPOLINE) && likely(buffer->clock == trace_clock_local))
1091 		ts = trace_clock_local();
1092 	else
1093 		ts = buffer->clock();
1094 
1095 	/* shift to debug/test normalization and TIME_EXTENTS */
1096 	return ts << DEBUG_SHIFT;
1097 }
1098 
ring_buffer_time_stamp(struct trace_buffer * buffer)1099 u64 ring_buffer_time_stamp(struct trace_buffer *buffer)
1100 {
1101 	u64 time;
1102 
1103 	preempt_disable_notrace();
1104 	time = rb_time_stamp(buffer);
1105 	preempt_enable_notrace();
1106 
1107 	return time;
1108 }
1109 EXPORT_SYMBOL_GPL(ring_buffer_time_stamp);
1110 
ring_buffer_normalize_time_stamp(struct trace_buffer * buffer,int cpu,u64 * ts)1111 void ring_buffer_normalize_time_stamp(struct trace_buffer *buffer,
1112 				      int cpu, u64 *ts)
1113 {
1114 	/* Just stupid testing the normalize function and deltas */
1115 	*ts >>= DEBUG_SHIFT;
1116 }
1117 EXPORT_SYMBOL_GPL(ring_buffer_normalize_time_stamp);
1118 
1119 /*
1120  * Making the ring buffer lockless makes things tricky.
1121  * Although writes only happen on the CPU that they are on,
1122  * and they only need to worry about interrupts. Reads can
1123  * happen on any CPU.
1124  *
1125  * The reader page is always off the ring buffer, but when the
1126  * reader finishes with a page, it needs to swap its page with
1127  * a new one from the buffer. The reader needs to take from
1128  * the head (writes go to the tail). But if a writer is in overwrite
1129  * mode and wraps, it must push the head page forward.
1130  *
1131  * Here lies the problem.
1132  *
1133  * The reader must be careful to replace only the head page, and
1134  * not another one. As described at the top of the file in the
1135  * ASCII art, the reader sets its old page to point to the next
1136  * page after head. It then sets the page after head to point to
1137  * the old reader page. But if the writer moves the head page
1138  * during this operation, the reader could end up with the tail.
1139  *
1140  * We use cmpxchg to help prevent this race. We also do something
1141  * special with the page before head. We set the LSB to 1.
1142  *
1143  * When the writer must push the page forward, it will clear the
1144  * bit that points to the head page, move the head, and then set
1145  * the bit that points to the new head page.
1146  *
1147  * We also don't want an interrupt coming in and moving the head
1148  * page on another writer. Thus we use the second LSB to catch
1149  * that too. Thus:
1150  *
1151  * head->list->prev->next        bit 1          bit 0
1152  *                              -------        -------
1153  * Normal page                     0              0
1154  * Points to head page             0              1
1155  * New head page                   1              0
1156  *
1157  * Note we can not trust the prev pointer of the head page, because:
1158  *
1159  * +----+       +-----+        +-----+
1160  * |    |------>|  T  |---X--->|  N  |
1161  * |    |<------|     |        |     |
1162  * +----+       +-----+        +-----+
1163  *   ^                           ^ |
1164  *   |          +-----+          | |
1165  *   +----------|  R  |----------+ |
1166  *              |     |<-----------+
1167  *              +-----+
1168  *
1169  * Key:  ---X-->  HEAD flag set in pointer
1170  *         T      Tail page
1171  *         R      Reader page
1172  *         N      Next page
1173  *
1174  * (see __rb_reserve_next() to see where this happens)
1175  *
1176  *  What the above shows is that the reader just swapped out
1177  *  the reader page with a page in the buffer, but before it
1178  *  could make the new header point back to the new page added
1179  *  it was preempted by a writer. The writer moved forward onto
1180  *  the new page added by the reader and is about to move forward
1181  *  again.
1182  *
1183  *  You can see, it is legitimate for the previous pointer of
1184  *  the head (or any page) not to point back to itself. But only
1185  *  temporarily.
1186  */
1187 
1188 #define RB_PAGE_NORMAL		0UL
1189 #define RB_PAGE_HEAD		1UL
1190 #define RB_PAGE_UPDATE		2UL
1191 
1192 
1193 #define RB_FLAG_MASK		3UL
1194 
1195 /* PAGE_MOVED is not part of the mask */
1196 #define RB_PAGE_MOVED		4UL
1197 
1198 /*
1199  * rb_list_head - remove any bit
1200  */
rb_list_head(struct list_head * list)1201 static struct list_head *rb_list_head(struct list_head *list)
1202 {
1203 	unsigned long val = (unsigned long)list;
1204 
1205 	return (struct list_head *)(val & ~RB_FLAG_MASK);
1206 }
1207 
1208 /*
1209  * rb_is_head_page - test if the given page is the head page
1210  *
1211  * Because the reader may move the head_page pointer, we can
1212  * not trust what the head page is (it may be pointing to
1213  * the reader page). But if the next page is a header page,
1214  * its flags will be non zero.
1215  */
1216 static inline int
rb_is_head_page(struct buffer_page * page,struct list_head * list)1217 rb_is_head_page(struct buffer_page *page, struct list_head *list)
1218 {
1219 	unsigned long val;
1220 
1221 	val = (unsigned long)list->next;
1222 
1223 	if ((val & ~RB_FLAG_MASK) != (unsigned long)&page->list)
1224 		return RB_PAGE_MOVED;
1225 
1226 	return val & RB_FLAG_MASK;
1227 }
1228 
1229 /*
1230  * rb_is_reader_page
1231  *
1232  * The unique thing about the reader page, is that, if the
1233  * writer is ever on it, the previous pointer never points
1234  * back to the reader page.
1235  */
rb_is_reader_page(struct buffer_page * page)1236 static bool rb_is_reader_page(struct buffer_page *page)
1237 {
1238 	struct list_head *list = page->list.prev;
1239 
1240 	return rb_list_head(list->next) != &page->list;
1241 }
1242 
1243 /*
1244  * rb_set_list_to_head - set a list_head to be pointing to head.
1245  */
rb_set_list_to_head(struct list_head * list)1246 static void rb_set_list_to_head(struct list_head *list)
1247 {
1248 	unsigned long *ptr;
1249 
1250 	ptr = (unsigned long *)&list->next;
1251 	*ptr |= RB_PAGE_HEAD;
1252 	*ptr &= ~RB_PAGE_UPDATE;
1253 }
1254 
1255 /*
1256  * rb_head_page_activate - sets up head page
1257  */
rb_head_page_activate(struct ring_buffer_per_cpu * cpu_buffer)1258 static void rb_head_page_activate(struct ring_buffer_per_cpu *cpu_buffer)
1259 {
1260 	struct buffer_page *head;
1261 
1262 	head = cpu_buffer->head_page;
1263 	if (!head)
1264 		return;
1265 
1266 	/*
1267 	 * Set the previous list pointer to have the HEAD flag.
1268 	 */
1269 	rb_set_list_to_head(head->list.prev);
1270 
1271 	if (cpu_buffer->ring_meta) {
1272 		struct ring_buffer_meta *meta = cpu_buffer->ring_meta;
1273 		meta->head_buffer = (unsigned long)head->page;
1274 	}
1275 }
1276 
rb_list_head_clear(struct list_head * list)1277 static void rb_list_head_clear(struct list_head *list)
1278 {
1279 	unsigned long *ptr = (unsigned long *)&list->next;
1280 
1281 	*ptr &= ~RB_FLAG_MASK;
1282 }
1283 
1284 /*
1285  * rb_head_page_deactivate - clears head page ptr (for free list)
1286  */
1287 static void
rb_head_page_deactivate(struct ring_buffer_per_cpu * cpu_buffer)1288 rb_head_page_deactivate(struct ring_buffer_per_cpu *cpu_buffer)
1289 {
1290 	struct list_head *hd;
1291 
1292 	/* Go through the whole list and clear any pointers found. */
1293 	rb_list_head_clear(cpu_buffer->pages);
1294 
1295 	list_for_each(hd, cpu_buffer->pages)
1296 		rb_list_head_clear(hd);
1297 }
1298 
rb_head_page_set(struct ring_buffer_per_cpu * cpu_buffer,struct buffer_page * head,struct buffer_page * prev,int old_flag,int new_flag)1299 static int rb_head_page_set(struct ring_buffer_per_cpu *cpu_buffer,
1300 			    struct buffer_page *head,
1301 			    struct buffer_page *prev,
1302 			    int old_flag, int new_flag)
1303 {
1304 	struct list_head *list;
1305 	unsigned long val = (unsigned long)&head->list;
1306 	unsigned long ret;
1307 
1308 	list = &prev->list;
1309 
1310 	val &= ~RB_FLAG_MASK;
1311 
1312 	ret = cmpxchg((unsigned long *)&list->next,
1313 		      val | old_flag, val | new_flag);
1314 
1315 	/* check if the reader took the page */
1316 	if ((ret & ~RB_FLAG_MASK) != val)
1317 		return RB_PAGE_MOVED;
1318 
1319 	return ret & RB_FLAG_MASK;
1320 }
1321 
rb_head_page_set_update(struct ring_buffer_per_cpu * cpu_buffer,struct buffer_page * head,struct buffer_page * prev,int old_flag)1322 static int rb_head_page_set_update(struct ring_buffer_per_cpu *cpu_buffer,
1323 				   struct buffer_page *head,
1324 				   struct buffer_page *prev,
1325 				   int old_flag)
1326 {
1327 	return rb_head_page_set(cpu_buffer, head, prev,
1328 				old_flag, RB_PAGE_UPDATE);
1329 }
1330 
rb_head_page_set_head(struct ring_buffer_per_cpu * cpu_buffer,struct buffer_page * head,struct buffer_page * prev,int old_flag)1331 static int rb_head_page_set_head(struct ring_buffer_per_cpu *cpu_buffer,
1332 				 struct buffer_page *head,
1333 				 struct buffer_page *prev,
1334 				 int old_flag)
1335 {
1336 	return rb_head_page_set(cpu_buffer, head, prev,
1337 				old_flag, RB_PAGE_HEAD);
1338 }
1339 
rb_head_page_set_normal(struct ring_buffer_per_cpu * cpu_buffer,struct buffer_page * head,struct buffer_page * prev,int old_flag)1340 static int rb_head_page_set_normal(struct ring_buffer_per_cpu *cpu_buffer,
1341 				   struct buffer_page *head,
1342 				   struct buffer_page *prev,
1343 				   int old_flag)
1344 {
1345 	return rb_head_page_set(cpu_buffer, head, prev,
1346 				old_flag, RB_PAGE_NORMAL);
1347 }
1348 
rb_inc_page(struct buffer_page ** bpage)1349 static inline void rb_inc_page(struct buffer_page **bpage)
1350 {
1351 	struct list_head *p = rb_list_head((*bpage)->list.next);
1352 
1353 	*bpage = list_entry(p, struct buffer_page, list);
1354 }
1355 
1356 static struct buffer_page *
rb_set_head_page(struct ring_buffer_per_cpu * cpu_buffer)1357 rb_set_head_page(struct ring_buffer_per_cpu *cpu_buffer)
1358 {
1359 	struct buffer_page *head;
1360 	struct buffer_page *page;
1361 	struct list_head *list;
1362 	int i;
1363 
1364 	if (RB_WARN_ON(cpu_buffer, !cpu_buffer->head_page))
1365 		return NULL;
1366 
1367 	/* sanity check */
1368 	list = cpu_buffer->pages;
1369 	if (RB_WARN_ON(cpu_buffer, rb_list_head(list->prev->next) != list))
1370 		return NULL;
1371 
1372 	page = head = cpu_buffer->head_page;
1373 	/*
1374 	 * It is possible that the writer moves the header behind
1375 	 * where we started, and we miss in one loop.
1376 	 * A second loop should grab the header, but we'll do
1377 	 * three loops just because I'm paranoid.
1378 	 */
1379 	for (i = 0; i < 3; i++) {
1380 		do {
1381 			if (rb_is_head_page(page, page->list.prev)) {
1382 				cpu_buffer->head_page = page;
1383 				return page;
1384 			}
1385 			rb_inc_page(&page);
1386 		} while (page != head);
1387 	}
1388 
1389 	RB_WARN_ON(cpu_buffer, 1);
1390 
1391 	return NULL;
1392 }
1393 
rb_head_page_replace(struct buffer_page * old,struct buffer_page * new)1394 static bool rb_head_page_replace(struct buffer_page *old,
1395 				struct buffer_page *new)
1396 {
1397 	unsigned long *ptr = (unsigned long *)&old->list.prev->next;
1398 	unsigned long val;
1399 
1400 	val = *ptr & ~RB_FLAG_MASK;
1401 	val |= RB_PAGE_HEAD;
1402 
1403 	return try_cmpxchg(ptr, &val, (unsigned long)&new->list);
1404 }
1405 
1406 /*
1407  * rb_tail_page_update - move the tail page forward
1408  */
rb_tail_page_update(struct ring_buffer_per_cpu * cpu_buffer,struct buffer_page * tail_page,struct buffer_page * next_page)1409 static void rb_tail_page_update(struct ring_buffer_per_cpu *cpu_buffer,
1410 			       struct buffer_page *tail_page,
1411 			       struct buffer_page *next_page)
1412 {
1413 	unsigned long old_entries;
1414 	unsigned long old_write;
1415 
1416 	/*
1417 	 * The tail page now needs to be moved forward.
1418 	 *
1419 	 * We need to reset the tail page, but without messing
1420 	 * with possible erasing of data brought in by interrupts
1421 	 * that have moved the tail page and are currently on it.
1422 	 *
1423 	 * We add a counter to the write field to denote this.
1424 	 */
1425 	old_write = local_add_return(RB_WRITE_INTCNT, &next_page->write);
1426 	old_entries = local_add_return(RB_WRITE_INTCNT, &next_page->entries);
1427 
1428 	/*
1429 	 * Just make sure we have seen our old_write and synchronize
1430 	 * with any interrupts that come in.
1431 	 */
1432 	barrier();
1433 
1434 	/*
1435 	 * If the tail page is still the same as what we think
1436 	 * it is, then it is up to us to update the tail
1437 	 * pointer.
1438 	 */
1439 	if (tail_page == READ_ONCE(cpu_buffer->tail_page)) {
1440 		/* Zero the write counter */
1441 		unsigned long val = old_write & ~RB_WRITE_MASK;
1442 		unsigned long eval = old_entries & ~RB_WRITE_MASK;
1443 
1444 		/*
1445 		 * This will only succeed if an interrupt did
1446 		 * not come in and change it. In which case, we
1447 		 * do not want to modify it.
1448 		 *
1449 		 * We add (void) to let the compiler know that we do not care
1450 		 * about the return value of these functions. We use the
1451 		 * cmpxchg to only update if an interrupt did not already
1452 		 * do it for us. If the cmpxchg fails, we don't care.
1453 		 */
1454 		(void)local_cmpxchg(&next_page->write, old_write, val);
1455 		(void)local_cmpxchg(&next_page->entries, old_entries, eval);
1456 
1457 		/*
1458 		 * No need to worry about races with clearing out the commit.
1459 		 * it only can increment when a commit takes place. But that
1460 		 * only happens in the outer most nested commit.
1461 		 */
1462 		local_set(&next_page->page->commit, 0);
1463 
1464 		/* Either we update tail_page or an interrupt does */
1465 		if (try_cmpxchg(&cpu_buffer->tail_page, &tail_page, next_page))
1466 			local_inc(&cpu_buffer->pages_touched);
1467 	}
1468 }
1469 
rb_check_bpage(struct ring_buffer_per_cpu * cpu_buffer,struct buffer_page * bpage)1470 static void rb_check_bpage(struct ring_buffer_per_cpu *cpu_buffer,
1471 			  struct buffer_page *bpage)
1472 {
1473 	unsigned long val = (unsigned long)bpage;
1474 
1475 	RB_WARN_ON(cpu_buffer, val & RB_FLAG_MASK);
1476 }
1477 
1478 /**
1479  * rb_check_pages - integrity check of buffer pages
1480  * @cpu_buffer: CPU buffer with pages to test
1481  *
1482  * As a safety measure we check to make sure the data pages have not
1483  * been corrupted.
1484  *
1485  * Callers of this function need to guarantee that the list of pages doesn't get
1486  * modified during the check. In particular, if it's possible that the function
1487  * is invoked with concurrent readers which can swap in a new reader page then
1488  * the caller should take cpu_buffer->reader_lock.
1489  */
rb_check_pages(struct ring_buffer_per_cpu * cpu_buffer)1490 static void rb_check_pages(struct ring_buffer_per_cpu *cpu_buffer)
1491 {
1492 	struct list_head *head = rb_list_head(cpu_buffer->pages);
1493 	struct list_head *tmp;
1494 
1495 	if (RB_WARN_ON(cpu_buffer,
1496 			rb_list_head(rb_list_head(head->next)->prev) != head))
1497 		return;
1498 
1499 	if (RB_WARN_ON(cpu_buffer,
1500 			rb_list_head(rb_list_head(head->prev)->next) != head))
1501 		return;
1502 
1503 	for (tmp = rb_list_head(head->next); tmp != head; tmp = rb_list_head(tmp->next)) {
1504 		if (RB_WARN_ON(cpu_buffer,
1505 				rb_list_head(rb_list_head(tmp->next)->prev) != tmp))
1506 			return;
1507 
1508 		if (RB_WARN_ON(cpu_buffer,
1509 				rb_list_head(rb_list_head(tmp->prev)->next) != tmp))
1510 			return;
1511 	}
1512 }
1513 
1514 /*
1515  * Take an address, add the meta data size as well as the array of
1516  * array subbuffer indexes, then align it to a subbuffer size.
1517  *
1518  * This is used to help find the next per cpu subbuffer within a mapped range.
1519  */
1520 static unsigned long
rb_range_align_subbuf(unsigned long addr,int subbuf_size,int nr_subbufs)1521 rb_range_align_subbuf(unsigned long addr, int subbuf_size, int nr_subbufs)
1522 {
1523 	addr += sizeof(struct ring_buffer_meta) +
1524 		sizeof(int) * nr_subbufs;
1525 	return ALIGN(addr, subbuf_size);
1526 }
1527 
1528 /*
1529  * Return the ring_buffer_meta for a given @cpu.
1530  */
rb_range_meta(struct trace_buffer * buffer,int nr_pages,int cpu)1531 static void *rb_range_meta(struct trace_buffer *buffer, int nr_pages, int cpu)
1532 {
1533 	int subbuf_size = buffer->subbuf_size + BUF_PAGE_HDR_SIZE;
1534 	unsigned long ptr = buffer->range_addr_start;
1535 	struct ring_buffer_meta *meta;
1536 	int nr_subbufs;
1537 
1538 	if (!ptr)
1539 		return NULL;
1540 
1541 	/* When nr_pages passed in is zero, the first meta has already been initialized */
1542 	if (!nr_pages) {
1543 		meta = (struct ring_buffer_meta *)ptr;
1544 		nr_subbufs = meta->nr_subbufs;
1545 	} else {
1546 		meta = NULL;
1547 		/* Include the reader page */
1548 		nr_subbufs = nr_pages + 1;
1549 	}
1550 
1551 	/*
1552 	 * The first chunk may not be subbuffer aligned, where as
1553 	 * the rest of the chunks are.
1554 	 */
1555 	if (cpu) {
1556 		ptr = rb_range_align_subbuf(ptr, subbuf_size, nr_subbufs);
1557 		ptr += subbuf_size * nr_subbufs;
1558 
1559 		/* We can use multiplication to find chunks greater than 1 */
1560 		if (cpu > 1) {
1561 			unsigned long size;
1562 			unsigned long p;
1563 
1564 			/* Save the beginning of this CPU chunk */
1565 			p = ptr;
1566 			ptr = rb_range_align_subbuf(ptr, subbuf_size, nr_subbufs);
1567 			ptr += subbuf_size * nr_subbufs;
1568 
1569 			/* Now all chunks after this are the same size */
1570 			size = ptr - p;
1571 			ptr += size * (cpu - 2);
1572 		}
1573 	}
1574 	return (void *)ptr;
1575 }
1576 
1577 /* Return the start of subbufs given the meta pointer */
rb_subbufs_from_meta(struct ring_buffer_meta * meta)1578 static void *rb_subbufs_from_meta(struct ring_buffer_meta *meta)
1579 {
1580 	int subbuf_size = meta->subbuf_size;
1581 	unsigned long ptr;
1582 
1583 	ptr = (unsigned long)meta;
1584 	ptr = rb_range_align_subbuf(ptr, subbuf_size, meta->nr_subbufs);
1585 
1586 	return (void *)ptr;
1587 }
1588 
1589 /*
1590  * Return a specific sub-buffer for a given @cpu defined by @idx.
1591  */
rb_range_buffer(struct ring_buffer_per_cpu * cpu_buffer,int idx)1592 static void *rb_range_buffer(struct ring_buffer_per_cpu *cpu_buffer, int idx)
1593 {
1594 	struct ring_buffer_meta *meta;
1595 	unsigned long ptr;
1596 	int subbuf_size;
1597 
1598 	meta = rb_range_meta(cpu_buffer->buffer, 0, cpu_buffer->cpu);
1599 	if (!meta)
1600 		return NULL;
1601 
1602 	if (WARN_ON_ONCE(idx >= meta->nr_subbufs))
1603 		return NULL;
1604 
1605 	subbuf_size = meta->subbuf_size;
1606 
1607 	/* Map this buffer to the order that's in meta->buffers[] */
1608 	idx = meta->buffers[idx];
1609 
1610 	ptr = (unsigned long)rb_subbufs_from_meta(meta);
1611 
1612 	ptr += subbuf_size * idx;
1613 	if (ptr + subbuf_size > cpu_buffer->buffer->range_addr_end)
1614 		return NULL;
1615 
1616 	return (void *)ptr;
1617 }
1618 
1619 /*
1620  * See if the existing memory contains valid ring buffer data.
1621  * As the previous kernel must be the same as this kernel, all
1622  * the calculations (size of buffers and number of buffers)
1623  * must be the same.
1624  */
rb_meta_valid(struct ring_buffer_meta * meta,int cpu,struct trace_buffer * buffer,int nr_pages)1625 static bool rb_meta_valid(struct ring_buffer_meta *meta, int cpu,
1626 			  struct trace_buffer *buffer, int nr_pages)
1627 {
1628 	int subbuf_size = PAGE_SIZE;
1629 	struct buffer_data_page *subbuf;
1630 	unsigned long buffers_start;
1631 	unsigned long buffers_end;
1632 	int i;
1633 
1634 	/* Check the meta magic and meta struct size */
1635 	if (meta->magic != RING_BUFFER_META_MAGIC ||
1636 	    meta->struct_size != sizeof(*meta)) {
1637 		pr_info("Ring buffer boot meta[%d] mismatch of magic or struct size\n", cpu);
1638 		return false;
1639 	}
1640 
1641 	/* The subbuffer's size and number of subbuffers must match */
1642 	if (meta->subbuf_size != subbuf_size ||
1643 	    meta->nr_subbufs != nr_pages + 1) {
1644 		pr_info("Ring buffer boot meta [%d] mismatch of subbuf_size/nr_pages\n", cpu);
1645 		return false;
1646 	}
1647 
1648 	buffers_start = meta->first_buffer;
1649 	buffers_end = meta->first_buffer + (subbuf_size * meta->nr_subbufs);
1650 
1651 	/* Is the head and commit buffers within the range of buffers? */
1652 	if (meta->head_buffer < buffers_start ||
1653 	    meta->head_buffer >= buffers_end) {
1654 		pr_info("Ring buffer boot meta [%d] head buffer out of range\n", cpu);
1655 		return false;
1656 	}
1657 
1658 	if (meta->commit_buffer < buffers_start ||
1659 	    meta->commit_buffer >= buffers_end) {
1660 		pr_info("Ring buffer boot meta [%d] commit buffer out of range\n", cpu);
1661 		return false;
1662 	}
1663 
1664 	subbuf = rb_subbufs_from_meta(meta);
1665 
1666 	/* Is the meta buffers and the subbufs themselves have correct data? */
1667 	for (i = 0; i < meta->nr_subbufs; i++) {
1668 		if (meta->buffers[i] < 0 ||
1669 		    meta->buffers[i] >= meta->nr_subbufs) {
1670 			pr_info("Ring buffer boot meta [%d] array out of range\n", cpu);
1671 			return false;
1672 		}
1673 
1674 		if ((unsigned)local_read(&subbuf->commit) > subbuf_size) {
1675 			pr_info("Ring buffer boot meta [%d] buffer invalid commit\n", cpu);
1676 			return false;
1677 		}
1678 
1679 		subbuf = (void *)subbuf + subbuf_size;
1680 	}
1681 
1682 	return true;
1683 }
1684 
1685 static int rb_meta_subbuf_idx(struct ring_buffer_meta *meta, void *subbuf);
1686 
rb_read_data_buffer(struct buffer_data_page * dpage,int tail,int cpu,unsigned long long * timestamp,u64 * delta_ptr)1687 static int rb_read_data_buffer(struct buffer_data_page *dpage, int tail, int cpu,
1688 			       unsigned long long *timestamp, u64 *delta_ptr)
1689 {
1690 	struct ring_buffer_event *event;
1691 	u64 ts, delta;
1692 	int events = 0;
1693 	int e;
1694 
1695 	*delta_ptr = 0;
1696 	*timestamp = 0;
1697 
1698 	ts = dpage->time_stamp;
1699 
1700 	for (e = 0; e < tail; e += rb_event_length(event)) {
1701 
1702 		event = (struct ring_buffer_event *)(dpage->data + e);
1703 
1704 		switch (event->type_len) {
1705 
1706 		case RINGBUF_TYPE_TIME_EXTEND:
1707 			delta = rb_event_time_stamp(event);
1708 			ts += delta;
1709 			break;
1710 
1711 		case RINGBUF_TYPE_TIME_STAMP:
1712 			delta = rb_event_time_stamp(event);
1713 			delta = rb_fix_abs_ts(delta, ts);
1714 			if (delta < ts) {
1715 				*delta_ptr = delta;
1716 				*timestamp = ts;
1717 				return -1;
1718 			}
1719 			ts = delta;
1720 			break;
1721 
1722 		case RINGBUF_TYPE_PADDING:
1723 			if (event->time_delta == 1)
1724 				break;
1725 			fallthrough;
1726 		case RINGBUF_TYPE_DATA:
1727 			events++;
1728 			ts += event->time_delta;
1729 			break;
1730 
1731 		default:
1732 			return -1;
1733 		}
1734 	}
1735 	*timestamp = ts;
1736 	return events;
1737 }
1738 
rb_validate_buffer(struct buffer_data_page * dpage,int cpu)1739 static int rb_validate_buffer(struct buffer_data_page *dpage, int cpu)
1740 {
1741 	unsigned long long ts;
1742 	u64 delta;
1743 	int tail;
1744 
1745 	tail = local_read(&dpage->commit);
1746 	return rb_read_data_buffer(dpage, tail, cpu, &ts, &delta);
1747 }
1748 
1749 /* If the meta data has been validated, now validate the events */
rb_meta_validate_events(struct ring_buffer_per_cpu * cpu_buffer)1750 static void rb_meta_validate_events(struct ring_buffer_per_cpu *cpu_buffer)
1751 {
1752 	struct ring_buffer_meta *meta = cpu_buffer->ring_meta;
1753 	struct buffer_page *head_page;
1754 	unsigned long entry_bytes = 0;
1755 	unsigned long entries = 0;
1756 	int ret;
1757 	int i;
1758 
1759 	if (!meta || !meta->head_buffer)
1760 		return;
1761 
1762 	/* Do the reader page first */
1763 	ret = rb_validate_buffer(cpu_buffer->reader_page->page, cpu_buffer->cpu);
1764 	if (ret < 0) {
1765 		pr_info("Ring buffer reader page is invalid\n");
1766 		goto invalid;
1767 	}
1768 	entries += ret;
1769 	entry_bytes += local_read(&cpu_buffer->reader_page->page->commit);
1770 	local_set(&cpu_buffer->reader_page->entries, ret);
1771 
1772 	head_page = cpu_buffer->head_page;
1773 
1774 	/* If both the head and commit are on the reader_page then we are done. */
1775 	if (head_page == cpu_buffer->reader_page &&
1776 	    head_page == cpu_buffer->commit_page)
1777 		goto done;
1778 
1779 	/* Iterate until finding the commit page */
1780 	for (i = 0; i < meta->nr_subbufs + 1; i++, rb_inc_page(&head_page)) {
1781 
1782 		/* Reader page has already been done */
1783 		if (head_page == cpu_buffer->reader_page)
1784 			continue;
1785 
1786 		ret = rb_validate_buffer(head_page->page, cpu_buffer->cpu);
1787 		if (ret < 0) {
1788 			pr_info("Ring buffer meta [%d] invalid buffer page\n",
1789 				cpu_buffer->cpu);
1790 			goto invalid;
1791 		}
1792 		entries += ret;
1793 		entry_bytes += local_read(&head_page->page->commit);
1794 		local_set(&cpu_buffer->head_page->entries, ret);
1795 
1796 		if (head_page == cpu_buffer->commit_page)
1797 			break;
1798 	}
1799 
1800 	if (head_page != cpu_buffer->commit_page) {
1801 		pr_info("Ring buffer meta [%d] commit page not found\n",
1802 			cpu_buffer->cpu);
1803 		goto invalid;
1804 	}
1805  done:
1806 	local_set(&cpu_buffer->entries, entries);
1807 	local_set(&cpu_buffer->entries_bytes, entry_bytes);
1808 
1809 	pr_info("Ring buffer meta [%d] is from previous boot!\n", cpu_buffer->cpu);
1810 	return;
1811 
1812  invalid:
1813 	/* The content of the buffers are invalid, reset the meta data */
1814 	meta->head_buffer = 0;
1815 	meta->commit_buffer = 0;
1816 
1817 	/* Reset the reader page */
1818 	local_set(&cpu_buffer->reader_page->entries, 0);
1819 	local_set(&cpu_buffer->reader_page->page->commit, 0);
1820 
1821 	/* Reset all the subbuffers */
1822 	for (i = 0; i < meta->nr_subbufs - 1; i++, rb_inc_page(&head_page)) {
1823 		local_set(&head_page->entries, 0);
1824 		local_set(&head_page->page->commit, 0);
1825 	}
1826 }
1827 
1828 /* Used to calculate data delta */
1829 static char rb_data_ptr[] = "";
1830 
1831 #define THIS_TEXT_PTR		((unsigned long)rb_meta_init_text_addr)
1832 #define THIS_DATA_PTR		((unsigned long)rb_data_ptr)
1833 
rb_meta_init_text_addr(struct ring_buffer_meta * meta)1834 static void rb_meta_init_text_addr(struct ring_buffer_meta *meta)
1835 {
1836 	meta->text_addr = THIS_TEXT_PTR;
1837 	meta->data_addr = THIS_DATA_PTR;
1838 }
1839 
rb_range_meta_init(struct trace_buffer * buffer,int nr_pages)1840 static void rb_range_meta_init(struct trace_buffer *buffer, int nr_pages)
1841 {
1842 	struct ring_buffer_meta *meta;
1843 	unsigned long delta;
1844 	void *subbuf;
1845 	int cpu;
1846 	int i;
1847 
1848 	for (cpu = 0; cpu < nr_cpu_ids; cpu++) {
1849 		void *next_meta;
1850 
1851 		meta = rb_range_meta(buffer, nr_pages, cpu);
1852 
1853 		if (rb_meta_valid(meta, cpu, buffer, nr_pages)) {
1854 			/* Make the mappings match the current address */
1855 			subbuf = rb_subbufs_from_meta(meta);
1856 			delta = (unsigned long)subbuf - meta->first_buffer;
1857 			meta->first_buffer += delta;
1858 			meta->head_buffer += delta;
1859 			meta->commit_buffer += delta;
1860 			buffer->last_text_delta = THIS_TEXT_PTR - meta->text_addr;
1861 			buffer->last_data_delta = THIS_DATA_PTR - meta->data_addr;
1862 			continue;
1863 		}
1864 
1865 		if (cpu < nr_cpu_ids - 1)
1866 			next_meta = rb_range_meta(buffer, nr_pages, cpu + 1);
1867 		else
1868 			next_meta = (void *)buffer->range_addr_end;
1869 
1870 		memset(meta, 0, next_meta - (void *)meta);
1871 
1872 		meta->magic = RING_BUFFER_META_MAGIC;
1873 		meta->struct_size = sizeof(*meta);
1874 
1875 		meta->nr_subbufs = nr_pages + 1;
1876 		meta->subbuf_size = PAGE_SIZE;
1877 
1878 		subbuf = rb_subbufs_from_meta(meta);
1879 
1880 		meta->first_buffer = (unsigned long)subbuf;
1881 		rb_meta_init_text_addr(meta);
1882 
1883 		/*
1884 		 * The buffers[] array holds the order of the sub-buffers
1885 		 * that are after the meta data. The sub-buffers may
1886 		 * be swapped out when read and inserted into a different
1887 		 * location of the ring buffer. Although their addresses
1888 		 * remain the same, the buffers[] array contains the
1889 		 * index into the sub-buffers holding their actual order.
1890 		 */
1891 		for (i = 0; i < meta->nr_subbufs; i++) {
1892 			meta->buffers[i] = i;
1893 			rb_init_page(subbuf);
1894 			subbuf += meta->subbuf_size;
1895 		}
1896 	}
1897 }
1898 
rbm_start(struct seq_file * m,loff_t * pos)1899 static void *rbm_start(struct seq_file *m, loff_t *pos)
1900 {
1901 	struct ring_buffer_per_cpu *cpu_buffer = m->private;
1902 	struct ring_buffer_meta *meta = cpu_buffer->ring_meta;
1903 	unsigned long val;
1904 
1905 	if (!meta)
1906 		return NULL;
1907 
1908 	if (*pos > meta->nr_subbufs)
1909 		return NULL;
1910 
1911 	val = *pos;
1912 	val++;
1913 
1914 	return (void *)val;
1915 }
1916 
rbm_next(struct seq_file * m,void * v,loff_t * pos)1917 static void *rbm_next(struct seq_file *m, void *v, loff_t *pos)
1918 {
1919 	(*pos)++;
1920 
1921 	return rbm_start(m, pos);
1922 }
1923 
rbm_show(struct seq_file * m,void * v)1924 static int rbm_show(struct seq_file *m, void *v)
1925 {
1926 	struct ring_buffer_per_cpu *cpu_buffer = m->private;
1927 	struct ring_buffer_meta *meta = cpu_buffer->ring_meta;
1928 	unsigned long val = (unsigned long)v;
1929 
1930 	if (val == 1) {
1931 		seq_printf(m, "head_buffer:   %d\n",
1932 			   rb_meta_subbuf_idx(meta, (void *)meta->head_buffer));
1933 		seq_printf(m, "commit_buffer: %d\n",
1934 			   rb_meta_subbuf_idx(meta, (void *)meta->commit_buffer));
1935 		seq_printf(m, "subbuf_size:   %d\n", meta->subbuf_size);
1936 		seq_printf(m, "nr_subbufs:    %d\n", meta->nr_subbufs);
1937 		return 0;
1938 	}
1939 
1940 	val -= 2;
1941 	seq_printf(m, "buffer[%ld]:    %d\n", val, meta->buffers[val]);
1942 
1943 	return 0;
1944 }
1945 
rbm_stop(struct seq_file * m,void * p)1946 static void rbm_stop(struct seq_file *m, void *p)
1947 {
1948 }
1949 
1950 static const struct seq_operations rb_meta_seq_ops = {
1951 	.start		= rbm_start,
1952 	.next		= rbm_next,
1953 	.show		= rbm_show,
1954 	.stop		= rbm_stop,
1955 };
1956 
ring_buffer_meta_seq_init(struct file * file,struct trace_buffer * buffer,int cpu)1957 int ring_buffer_meta_seq_init(struct file *file, struct trace_buffer *buffer, int cpu)
1958 {
1959 	struct seq_file *m;
1960 	int ret;
1961 
1962 	ret = seq_open(file, &rb_meta_seq_ops);
1963 	if (ret)
1964 		return ret;
1965 
1966 	m = file->private_data;
1967 	m->private = buffer->buffers[cpu];
1968 
1969 	return 0;
1970 }
1971 
1972 /* Map the buffer_pages to the previous head and commit pages */
rb_meta_buffer_update(struct ring_buffer_per_cpu * cpu_buffer,struct buffer_page * bpage)1973 static void rb_meta_buffer_update(struct ring_buffer_per_cpu *cpu_buffer,
1974 				  struct buffer_page *bpage)
1975 {
1976 	struct ring_buffer_meta *meta = cpu_buffer->ring_meta;
1977 
1978 	if (meta->head_buffer == (unsigned long)bpage->page)
1979 		cpu_buffer->head_page = bpage;
1980 
1981 	if (meta->commit_buffer == (unsigned long)bpage->page) {
1982 		cpu_buffer->commit_page = bpage;
1983 		cpu_buffer->tail_page = bpage;
1984 	}
1985 }
1986 
__rb_allocate_pages(struct ring_buffer_per_cpu * cpu_buffer,long nr_pages,struct list_head * pages)1987 static int __rb_allocate_pages(struct ring_buffer_per_cpu *cpu_buffer,
1988 		long nr_pages, struct list_head *pages)
1989 {
1990 	struct trace_buffer *buffer = cpu_buffer->buffer;
1991 	struct ring_buffer_meta *meta = NULL;
1992 	struct buffer_page *bpage, *tmp;
1993 	bool user_thread = current->mm != NULL;
1994 	gfp_t mflags;
1995 	long i;
1996 
1997 	/*
1998 	 * Check if the available memory is there first.
1999 	 * Note, si_mem_available() only gives us a rough estimate of available
2000 	 * memory. It may not be accurate. But we don't care, we just want
2001 	 * to prevent doing any allocation when it is obvious that it is
2002 	 * not going to succeed.
2003 	 */
2004 	i = si_mem_available();
2005 	if (i < nr_pages)
2006 		return -ENOMEM;
2007 
2008 	/*
2009 	 * __GFP_RETRY_MAYFAIL flag makes sure that the allocation fails
2010 	 * gracefully without invoking oom-killer and the system is not
2011 	 * destabilized.
2012 	 */
2013 	mflags = GFP_KERNEL | __GFP_RETRY_MAYFAIL;
2014 
2015 	/*
2016 	 * If a user thread allocates too much, and si_mem_available()
2017 	 * reports there's enough memory, even though there is not.
2018 	 * Make sure the OOM killer kills this thread. This can happen
2019 	 * even with RETRY_MAYFAIL because another task may be doing
2020 	 * an allocation after this task has taken all memory.
2021 	 * This is the task the OOM killer needs to take out during this
2022 	 * loop, even if it was triggered by an allocation somewhere else.
2023 	 */
2024 	if (user_thread)
2025 		set_current_oom_origin();
2026 
2027 	if (buffer->range_addr_start)
2028 		meta = rb_range_meta(buffer, nr_pages, cpu_buffer->cpu);
2029 
2030 	for (i = 0; i < nr_pages; i++) {
2031 		struct page *page;
2032 
2033 		bpage = kzalloc_node(ALIGN(sizeof(*bpage), cache_line_size()),
2034 				    mflags, cpu_to_node(cpu_buffer->cpu));
2035 		if (!bpage)
2036 			goto free_pages;
2037 
2038 		rb_check_bpage(cpu_buffer, bpage);
2039 
2040 		/*
2041 		 * Append the pages as for mapped buffers we want to keep
2042 		 * the order
2043 		 */
2044 		list_add_tail(&bpage->list, pages);
2045 
2046 		if (meta) {
2047 			/* A range was given. Use that for the buffer page */
2048 			bpage->page = rb_range_buffer(cpu_buffer, i + 1);
2049 			if (!bpage->page)
2050 				goto free_pages;
2051 			/* If this is valid from a previous boot */
2052 			if (meta->head_buffer)
2053 				rb_meta_buffer_update(cpu_buffer, bpage);
2054 			bpage->range = 1;
2055 			bpage->id = i + 1;
2056 		} else {
2057 			page = alloc_pages_node(cpu_to_node(cpu_buffer->cpu),
2058 						mflags | __GFP_COMP | __GFP_ZERO,
2059 						cpu_buffer->buffer->subbuf_order);
2060 			if (!page)
2061 				goto free_pages;
2062 			bpage->page = page_address(page);
2063 			rb_init_page(bpage->page);
2064 		}
2065 		bpage->order = cpu_buffer->buffer->subbuf_order;
2066 
2067 		if (user_thread && fatal_signal_pending(current))
2068 			goto free_pages;
2069 	}
2070 	if (user_thread)
2071 		clear_current_oom_origin();
2072 
2073 	return 0;
2074 
2075 free_pages:
2076 	list_for_each_entry_safe(bpage, tmp, pages, list) {
2077 		list_del_init(&bpage->list);
2078 		free_buffer_page(bpage);
2079 	}
2080 	if (user_thread)
2081 		clear_current_oom_origin();
2082 
2083 	return -ENOMEM;
2084 }
2085 
rb_allocate_pages(struct ring_buffer_per_cpu * cpu_buffer,unsigned long nr_pages)2086 static int rb_allocate_pages(struct ring_buffer_per_cpu *cpu_buffer,
2087 			     unsigned long nr_pages)
2088 {
2089 	LIST_HEAD(pages);
2090 
2091 	WARN_ON(!nr_pages);
2092 
2093 	if (__rb_allocate_pages(cpu_buffer, nr_pages, &pages))
2094 		return -ENOMEM;
2095 
2096 	/*
2097 	 * The ring buffer page list is a circular list that does not
2098 	 * start and end with a list head. All page list items point to
2099 	 * other pages.
2100 	 */
2101 	cpu_buffer->pages = pages.next;
2102 	list_del(&pages);
2103 
2104 	cpu_buffer->nr_pages = nr_pages;
2105 
2106 	rb_check_pages(cpu_buffer);
2107 
2108 	return 0;
2109 }
2110 
2111 static struct ring_buffer_per_cpu *
rb_allocate_cpu_buffer(struct trace_buffer * buffer,long nr_pages,int cpu)2112 rb_allocate_cpu_buffer(struct trace_buffer *buffer, long nr_pages, int cpu)
2113 {
2114 	struct ring_buffer_per_cpu *cpu_buffer;
2115 	struct ring_buffer_meta *meta;
2116 	struct buffer_page *bpage;
2117 	struct page *page;
2118 	int ret;
2119 
2120 	cpu_buffer = kzalloc_node(ALIGN(sizeof(*cpu_buffer), cache_line_size()),
2121 				  GFP_KERNEL, cpu_to_node(cpu));
2122 	if (!cpu_buffer)
2123 		return NULL;
2124 
2125 	cpu_buffer->cpu = cpu;
2126 	cpu_buffer->buffer = buffer;
2127 	raw_spin_lock_init(&cpu_buffer->reader_lock);
2128 	lockdep_set_class(&cpu_buffer->reader_lock, buffer->reader_lock_key);
2129 	cpu_buffer->lock = (arch_spinlock_t)__ARCH_SPIN_LOCK_UNLOCKED;
2130 	INIT_WORK(&cpu_buffer->update_pages_work, update_pages_handler);
2131 	init_completion(&cpu_buffer->update_done);
2132 	init_irq_work(&cpu_buffer->irq_work.work, rb_wake_up_waiters);
2133 	init_waitqueue_head(&cpu_buffer->irq_work.waiters);
2134 	init_waitqueue_head(&cpu_buffer->irq_work.full_waiters);
2135 	mutex_init(&cpu_buffer->mapping_lock);
2136 
2137 	bpage = kzalloc_node(ALIGN(sizeof(*bpage), cache_line_size()),
2138 			    GFP_KERNEL, cpu_to_node(cpu));
2139 	if (!bpage)
2140 		goto fail_free_buffer;
2141 
2142 	rb_check_bpage(cpu_buffer, bpage);
2143 
2144 	cpu_buffer->reader_page = bpage;
2145 
2146 	if (buffer->range_addr_start) {
2147 		/*
2148 		 * Range mapped buffers have the same restrictions as memory
2149 		 * mapped ones do.
2150 		 */
2151 		cpu_buffer->mapped = 1;
2152 		cpu_buffer->ring_meta = rb_range_meta(buffer, nr_pages, cpu);
2153 		bpage->page = rb_range_buffer(cpu_buffer, 0);
2154 		if (!bpage->page)
2155 			goto fail_free_reader;
2156 		if (cpu_buffer->ring_meta->head_buffer)
2157 			rb_meta_buffer_update(cpu_buffer, bpage);
2158 		bpage->range = 1;
2159 	} else {
2160 		page = alloc_pages_node(cpu_to_node(cpu),
2161 					GFP_KERNEL | __GFP_COMP | __GFP_ZERO,
2162 					cpu_buffer->buffer->subbuf_order);
2163 		if (!page)
2164 			goto fail_free_reader;
2165 		bpage->page = page_address(page);
2166 		rb_init_page(bpage->page);
2167 	}
2168 
2169 	INIT_LIST_HEAD(&cpu_buffer->reader_page->list);
2170 	INIT_LIST_HEAD(&cpu_buffer->new_pages);
2171 
2172 	ret = rb_allocate_pages(cpu_buffer, nr_pages);
2173 	if (ret < 0)
2174 		goto fail_free_reader;
2175 
2176 	rb_meta_validate_events(cpu_buffer);
2177 
2178 	/* If the boot meta was valid then this has already been updated */
2179 	meta = cpu_buffer->ring_meta;
2180 	if (!meta || !meta->head_buffer ||
2181 	    !cpu_buffer->head_page || !cpu_buffer->commit_page || !cpu_buffer->tail_page) {
2182 		if (meta && meta->head_buffer &&
2183 		    (cpu_buffer->head_page || cpu_buffer->commit_page || cpu_buffer->tail_page)) {
2184 			pr_warn("Ring buffer meta buffers not all mapped\n");
2185 			if (!cpu_buffer->head_page)
2186 				pr_warn("   Missing head_page\n");
2187 			if (!cpu_buffer->commit_page)
2188 				pr_warn("   Missing commit_page\n");
2189 			if (!cpu_buffer->tail_page)
2190 				pr_warn("   Missing tail_page\n");
2191 		}
2192 
2193 		cpu_buffer->head_page
2194 			= list_entry(cpu_buffer->pages, struct buffer_page, list);
2195 		cpu_buffer->tail_page = cpu_buffer->commit_page = cpu_buffer->head_page;
2196 
2197 		rb_head_page_activate(cpu_buffer);
2198 
2199 		if (cpu_buffer->ring_meta)
2200 			meta->commit_buffer = meta->head_buffer;
2201 	} else {
2202 		/* The valid meta buffer still needs to activate the head page */
2203 		rb_head_page_activate(cpu_buffer);
2204 	}
2205 
2206 	return cpu_buffer;
2207 
2208  fail_free_reader:
2209 	free_buffer_page(cpu_buffer->reader_page);
2210 
2211  fail_free_buffer:
2212 	kfree(cpu_buffer);
2213 	return NULL;
2214 }
2215 
rb_free_cpu_buffer(struct ring_buffer_per_cpu * cpu_buffer)2216 static void rb_free_cpu_buffer(struct ring_buffer_per_cpu *cpu_buffer)
2217 {
2218 	struct list_head *head = cpu_buffer->pages;
2219 	struct buffer_page *bpage, *tmp;
2220 
2221 	irq_work_sync(&cpu_buffer->irq_work.work);
2222 
2223 	free_buffer_page(cpu_buffer->reader_page);
2224 
2225 	if (head) {
2226 		rb_head_page_deactivate(cpu_buffer);
2227 
2228 		list_for_each_entry_safe(bpage, tmp, head, list) {
2229 			list_del_init(&bpage->list);
2230 			free_buffer_page(bpage);
2231 		}
2232 		bpage = list_entry(head, struct buffer_page, list);
2233 		free_buffer_page(bpage);
2234 	}
2235 
2236 	free_page((unsigned long)cpu_buffer->free_page);
2237 
2238 	kfree(cpu_buffer);
2239 }
2240 
alloc_buffer(unsigned long size,unsigned flags,int order,unsigned long start,unsigned long end,struct lock_class_key * key)2241 static struct trace_buffer *alloc_buffer(unsigned long size, unsigned flags,
2242 					 int order, unsigned long start,
2243 					 unsigned long end,
2244 					 struct lock_class_key *key)
2245 {
2246 	struct trace_buffer *buffer;
2247 	long nr_pages;
2248 	int subbuf_size;
2249 	int bsize;
2250 	int cpu;
2251 	int ret;
2252 
2253 	/* keep it in its own cache line */
2254 	buffer = kzalloc(ALIGN(sizeof(*buffer), cache_line_size()),
2255 			 GFP_KERNEL);
2256 	if (!buffer)
2257 		return NULL;
2258 
2259 	if (!zalloc_cpumask_var(&buffer->cpumask, GFP_KERNEL))
2260 		goto fail_free_buffer;
2261 
2262 	buffer->subbuf_order = order;
2263 	subbuf_size = (PAGE_SIZE << order);
2264 	buffer->subbuf_size = subbuf_size - BUF_PAGE_HDR_SIZE;
2265 
2266 	/* Max payload is buffer page size - header (8bytes) */
2267 	buffer->max_data_size = buffer->subbuf_size - (sizeof(u32) * 2);
2268 
2269 	buffer->flags = flags;
2270 	buffer->clock = trace_clock_local;
2271 	buffer->reader_lock_key = key;
2272 
2273 	init_irq_work(&buffer->irq_work.work, rb_wake_up_waiters);
2274 	init_waitqueue_head(&buffer->irq_work.waiters);
2275 
2276 	buffer->cpus = nr_cpu_ids;
2277 
2278 	bsize = sizeof(void *) * nr_cpu_ids;
2279 	buffer->buffers = kzalloc(ALIGN(bsize, cache_line_size()),
2280 				  GFP_KERNEL);
2281 	if (!buffer->buffers)
2282 		goto fail_free_cpumask;
2283 
2284 	/* If start/end are specified, then that overrides size */
2285 	if (start && end) {
2286 		unsigned long ptr;
2287 		int n;
2288 
2289 		size = end - start;
2290 		size = size / nr_cpu_ids;
2291 
2292 		/*
2293 		 * The number of sub-buffers (nr_pages) is determined by the
2294 		 * total size allocated minus the meta data size.
2295 		 * Then that is divided by the number of per CPU buffers
2296 		 * needed, plus account for the integer array index that
2297 		 * will be appended to the meta data.
2298 		 */
2299 		nr_pages = (size - sizeof(struct ring_buffer_meta)) /
2300 			(subbuf_size + sizeof(int));
2301 		/* Need at least two pages plus the reader page */
2302 		if (nr_pages < 3)
2303 			goto fail_free_buffers;
2304 
2305  again:
2306 		/* Make sure that the size fits aligned */
2307 		for (n = 0, ptr = start; n < nr_cpu_ids; n++) {
2308 			ptr += sizeof(struct ring_buffer_meta) +
2309 				sizeof(int) * nr_pages;
2310 			ptr = ALIGN(ptr, subbuf_size);
2311 			ptr += subbuf_size * nr_pages;
2312 		}
2313 		if (ptr > end) {
2314 			if (nr_pages <= 3)
2315 				goto fail_free_buffers;
2316 			nr_pages--;
2317 			goto again;
2318 		}
2319 
2320 		/* nr_pages should not count the reader page */
2321 		nr_pages--;
2322 		buffer->range_addr_start = start;
2323 		buffer->range_addr_end = end;
2324 
2325 		rb_range_meta_init(buffer, nr_pages);
2326 	} else {
2327 
2328 		/* need at least two pages */
2329 		nr_pages = DIV_ROUND_UP(size, buffer->subbuf_size);
2330 		if (nr_pages < 2)
2331 			nr_pages = 2;
2332 	}
2333 
2334 	cpu = raw_smp_processor_id();
2335 	cpumask_set_cpu(cpu, buffer->cpumask);
2336 	buffer->buffers[cpu] = rb_allocate_cpu_buffer(buffer, nr_pages, cpu);
2337 	if (!buffer->buffers[cpu])
2338 		goto fail_free_buffers;
2339 
2340 	/* If already mapped, do not hook to CPU hotplug */
2341 	if (!start) {
2342 		ret = cpuhp_state_add_instance(CPUHP_TRACE_RB_PREPARE, &buffer->node);
2343 		if (ret < 0)
2344 			goto fail_free_buffers;
2345 	}
2346 
2347 	mutex_init(&buffer->mutex);
2348 
2349 	return buffer;
2350 
2351  fail_free_buffers:
2352 	for_each_buffer_cpu(buffer, cpu) {
2353 		if (buffer->buffers[cpu])
2354 			rb_free_cpu_buffer(buffer->buffers[cpu]);
2355 	}
2356 	kfree(buffer->buffers);
2357 
2358  fail_free_cpumask:
2359 	free_cpumask_var(buffer->cpumask);
2360 
2361  fail_free_buffer:
2362 	kfree(buffer);
2363 	return NULL;
2364 }
2365 
2366 /**
2367  * __ring_buffer_alloc - allocate a new ring_buffer
2368  * @size: the size in bytes per cpu that is needed.
2369  * @flags: attributes to set for the ring buffer.
2370  * @key: ring buffer reader_lock_key.
2371  *
2372  * Currently the only flag that is available is the RB_FL_OVERWRITE
2373  * flag. This flag means that the buffer will overwrite old data
2374  * when the buffer wraps. If this flag is not set, the buffer will
2375  * drop data when the tail hits the head.
2376  */
__ring_buffer_alloc(unsigned long size,unsigned flags,struct lock_class_key * key)2377 struct trace_buffer *__ring_buffer_alloc(unsigned long size, unsigned flags,
2378 					struct lock_class_key *key)
2379 {
2380 	/* Default buffer page size - one system page */
2381 	return alloc_buffer(size, flags, 0, 0, 0,key);
2382 
2383 }
2384 EXPORT_SYMBOL_GPL(__ring_buffer_alloc);
2385 
2386 /**
2387  * __ring_buffer_alloc_range - allocate a new ring_buffer from existing memory
2388  * @size: the size in bytes per cpu that is needed.
2389  * @flags: attributes to set for the ring buffer.
2390  * @start: start of allocated range
2391  * @range_size: size of allocated range
2392  * @order: sub-buffer order
2393  * @key: ring buffer reader_lock_key.
2394  *
2395  * Currently the only flag that is available is the RB_FL_OVERWRITE
2396  * flag. This flag means that the buffer will overwrite old data
2397  * when the buffer wraps. If this flag is not set, the buffer will
2398  * drop data when the tail hits the head.
2399  */
__ring_buffer_alloc_range(unsigned long size,unsigned flags,int order,unsigned long start,unsigned long range_size,struct lock_class_key * key)2400 struct trace_buffer *__ring_buffer_alloc_range(unsigned long size, unsigned flags,
2401 					       int order, unsigned long start,
2402 					       unsigned long range_size,
2403 					       struct lock_class_key *key)
2404 {
2405 	return alloc_buffer(size, flags, order, start, start + range_size, key);
2406 }
2407 
2408 /**
2409  * ring_buffer_last_boot_delta - return the delta offset from last boot
2410  * @buffer: The buffer to return the delta from
2411  * @text: Return text delta
2412  * @data: Return data delta
2413  *
2414  * Returns: The true if the delta is non zero
2415  */
ring_buffer_last_boot_delta(struct trace_buffer * buffer,long * text,long * data)2416 bool ring_buffer_last_boot_delta(struct trace_buffer *buffer, long *text,
2417 				 long *data)
2418 {
2419 	if (!buffer)
2420 		return false;
2421 
2422 	if (!buffer->last_text_delta)
2423 		return false;
2424 
2425 	*text = buffer->last_text_delta;
2426 	*data = buffer->last_data_delta;
2427 
2428 	return true;
2429 }
2430 
2431 /**
2432  * ring_buffer_free - free a ring buffer.
2433  * @buffer: the buffer to free.
2434  */
2435 void
ring_buffer_free(struct trace_buffer * buffer)2436 ring_buffer_free(struct trace_buffer *buffer)
2437 {
2438 	int cpu;
2439 
2440 	cpuhp_state_remove_instance(CPUHP_TRACE_RB_PREPARE, &buffer->node);
2441 
2442 	irq_work_sync(&buffer->irq_work.work);
2443 
2444 	for_each_buffer_cpu(buffer, cpu)
2445 		rb_free_cpu_buffer(buffer->buffers[cpu]);
2446 
2447 	kfree(buffer->buffers);
2448 	free_cpumask_var(buffer->cpumask);
2449 
2450 	kfree(buffer);
2451 }
2452 EXPORT_SYMBOL_GPL(ring_buffer_free);
2453 
ring_buffer_set_clock(struct trace_buffer * buffer,u64 (* clock)(void))2454 void ring_buffer_set_clock(struct trace_buffer *buffer,
2455 			   u64 (*clock)(void))
2456 {
2457 	buffer->clock = clock;
2458 }
2459 
ring_buffer_set_time_stamp_abs(struct trace_buffer * buffer,bool abs)2460 void ring_buffer_set_time_stamp_abs(struct trace_buffer *buffer, bool abs)
2461 {
2462 	buffer->time_stamp_abs = abs;
2463 }
2464 
ring_buffer_time_stamp_abs(struct trace_buffer * buffer)2465 bool ring_buffer_time_stamp_abs(struct trace_buffer *buffer)
2466 {
2467 	return buffer->time_stamp_abs;
2468 }
2469 
rb_page_entries(struct buffer_page * bpage)2470 static inline unsigned long rb_page_entries(struct buffer_page *bpage)
2471 {
2472 	return local_read(&bpage->entries) & RB_WRITE_MASK;
2473 }
2474 
rb_page_write(struct buffer_page * bpage)2475 static inline unsigned long rb_page_write(struct buffer_page *bpage)
2476 {
2477 	return local_read(&bpage->write) & RB_WRITE_MASK;
2478 }
2479 
2480 static bool
rb_remove_pages(struct ring_buffer_per_cpu * cpu_buffer,unsigned long nr_pages)2481 rb_remove_pages(struct ring_buffer_per_cpu *cpu_buffer, unsigned long nr_pages)
2482 {
2483 	struct list_head *tail_page, *to_remove, *next_page;
2484 	struct buffer_page *to_remove_page, *tmp_iter_page;
2485 	struct buffer_page *last_page, *first_page;
2486 	unsigned long nr_removed;
2487 	unsigned long head_bit;
2488 	int page_entries;
2489 
2490 	head_bit = 0;
2491 
2492 	raw_spin_lock_irq(&cpu_buffer->reader_lock);
2493 	atomic_inc(&cpu_buffer->record_disabled);
2494 	/*
2495 	 * We don't race with the readers since we have acquired the reader
2496 	 * lock. We also don't race with writers after disabling recording.
2497 	 * This makes it easy to figure out the first and the last page to be
2498 	 * removed from the list. We unlink all the pages in between including
2499 	 * the first and last pages. This is done in a busy loop so that we
2500 	 * lose the least number of traces.
2501 	 * The pages are freed after we restart recording and unlock readers.
2502 	 */
2503 	tail_page = &cpu_buffer->tail_page->list;
2504 
2505 	/*
2506 	 * tail page might be on reader page, we remove the next page
2507 	 * from the ring buffer
2508 	 */
2509 	if (cpu_buffer->tail_page == cpu_buffer->reader_page)
2510 		tail_page = rb_list_head(tail_page->next);
2511 	to_remove = tail_page;
2512 
2513 	/* start of pages to remove */
2514 	first_page = list_entry(rb_list_head(to_remove->next),
2515 				struct buffer_page, list);
2516 
2517 	for (nr_removed = 0; nr_removed < nr_pages; nr_removed++) {
2518 		to_remove = rb_list_head(to_remove)->next;
2519 		head_bit |= (unsigned long)to_remove & RB_PAGE_HEAD;
2520 	}
2521 	/* Read iterators need to reset themselves when some pages removed */
2522 	cpu_buffer->pages_removed += nr_removed;
2523 
2524 	next_page = rb_list_head(to_remove)->next;
2525 
2526 	/*
2527 	 * Now we remove all pages between tail_page and next_page.
2528 	 * Make sure that we have head_bit value preserved for the
2529 	 * next page
2530 	 */
2531 	tail_page->next = (struct list_head *)((unsigned long)next_page |
2532 						head_bit);
2533 	next_page = rb_list_head(next_page);
2534 	next_page->prev = tail_page;
2535 
2536 	/* make sure pages points to a valid page in the ring buffer */
2537 	cpu_buffer->pages = next_page;
2538 
2539 	/* update head page */
2540 	if (head_bit)
2541 		cpu_buffer->head_page = list_entry(next_page,
2542 						struct buffer_page, list);
2543 
2544 	/* pages are removed, resume tracing and then free the pages */
2545 	atomic_dec(&cpu_buffer->record_disabled);
2546 	raw_spin_unlock_irq(&cpu_buffer->reader_lock);
2547 
2548 	RB_WARN_ON(cpu_buffer, list_empty(cpu_buffer->pages));
2549 
2550 	/* last buffer page to remove */
2551 	last_page = list_entry(rb_list_head(to_remove), struct buffer_page,
2552 				list);
2553 	tmp_iter_page = first_page;
2554 
2555 	do {
2556 		cond_resched();
2557 
2558 		to_remove_page = tmp_iter_page;
2559 		rb_inc_page(&tmp_iter_page);
2560 
2561 		/* update the counters */
2562 		page_entries = rb_page_entries(to_remove_page);
2563 		if (page_entries) {
2564 			/*
2565 			 * If something was added to this page, it was full
2566 			 * since it is not the tail page. So we deduct the
2567 			 * bytes consumed in ring buffer from here.
2568 			 * Increment overrun to account for the lost events.
2569 			 */
2570 			local_add(page_entries, &cpu_buffer->overrun);
2571 			local_sub(rb_page_commit(to_remove_page), &cpu_buffer->entries_bytes);
2572 			local_inc(&cpu_buffer->pages_lost);
2573 		}
2574 
2575 		/*
2576 		 * We have already removed references to this list item, just
2577 		 * free up the buffer_page and its page
2578 		 */
2579 		free_buffer_page(to_remove_page);
2580 		nr_removed--;
2581 
2582 	} while (to_remove_page != last_page);
2583 
2584 	RB_WARN_ON(cpu_buffer, nr_removed);
2585 
2586 	return nr_removed == 0;
2587 }
2588 
2589 static bool
rb_insert_pages(struct ring_buffer_per_cpu * cpu_buffer)2590 rb_insert_pages(struct ring_buffer_per_cpu *cpu_buffer)
2591 {
2592 	struct list_head *pages = &cpu_buffer->new_pages;
2593 	unsigned long flags;
2594 	bool success;
2595 	int retries;
2596 
2597 	/* Can be called at early boot up, where interrupts must not been enabled */
2598 	raw_spin_lock_irqsave(&cpu_buffer->reader_lock, flags);
2599 	/*
2600 	 * We are holding the reader lock, so the reader page won't be swapped
2601 	 * in the ring buffer. Now we are racing with the writer trying to
2602 	 * move head page and the tail page.
2603 	 * We are going to adapt the reader page update process where:
2604 	 * 1. We first splice the start and end of list of new pages between
2605 	 *    the head page and its previous page.
2606 	 * 2. We cmpxchg the prev_page->next to point from head page to the
2607 	 *    start of new pages list.
2608 	 * 3. Finally, we update the head->prev to the end of new list.
2609 	 *
2610 	 * We will try this process 10 times, to make sure that we don't keep
2611 	 * spinning.
2612 	 */
2613 	retries = 10;
2614 	success = false;
2615 	while (retries--) {
2616 		struct list_head *head_page, *prev_page;
2617 		struct list_head *last_page, *first_page;
2618 		struct list_head *head_page_with_bit;
2619 		struct buffer_page *hpage = rb_set_head_page(cpu_buffer);
2620 
2621 		if (!hpage)
2622 			break;
2623 		head_page = &hpage->list;
2624 		prev_page = head_page->prev;
2625 
2626 		first_page = pages->next;
2627 		last_page  = pages->prev;
2628 
2629 		head_page_with_bit = (struct list_head *)
2630 				     ((unsigned long)head_page | RB_PAGE_HEAD);
2631 
2632 		last_page->next = head_page_with_bit;
2633 		first_page->prev = prev_page;
2634 
2635 		/* caution: head_page_with_bit gets updated on cmpxchg failure */
2636 		if (try_cmpxchg(&prev_page->next,
2637 				&head_page_with_bit, first_page)) {
2638 			/*
2639 			 * yay, we replaced the page pointer to our new list,
2640 			 * now, we just have to update to head page's prev
2641 			 * pointer to point to end of list
2642 			 */
2643 			head_page->prev = last_page;
2644 			success = true;
2645 			break;
2646 		}
2647 	}
2648 
2649 	if (success)
2650 		INIT_LIST_HEAD(pages);
2651 	/*
2652 	 * If we weren't successful in adding in new pages, warn and stop
2653 	 * tracing
2654 	 */
2655 	RB_WARN_ON(cpu_buffer, !success);
2656 	raw_spin_unlock_irqrestore(&cpu_buffer->reader_lock, flags);
2657 
2658 	/* free pages if they weren't inserted */
2659 	if (!success) {
2660 		struct buffer_page *bpage, *tmp;
2661 		list_for_each_entry_safe(bpage, tmp, &cpu_buffer->new_pages,
2662 					 list) {
2663 			list_del_init(&bpage->list);
2664 			free_buffer_page(bpage);
2665 		}
2666 	}
2667 	return success;
2668 }
2669 
rb_update_pages(struct ring_buffer_per_cpu * cpu_buffer)2670 static void rb_update_pages(struct ring_buffer_per_cpu *cpu_buffer)
2671 {
2672 	bool success;
2673 
2674 	if (cpu_buffer->nr_pages_to_update > 0)
2675 		success = rb_insert_pages(cpu_buffer);
2676 	else
2677 		success = rb_remove_pages(cpu_buffer,
2678 					-cpu_buffer->nr_pages_to_update);
2679 
2680 	if (success)
2681 		cpu_buffer->nr_pages += cpu_buffer->nr_pages_to_update;
2682 }
2683 
update_pages_handler(struct work_struct * work)2684 static void update_pages_handler(struct work_struct *work)
2685 {
2686 	struct ring_buffer_per_cpu *cpu_buffer = container_of(work,
2687 			struct ring_buffer_per_cpu, update_pages_work);
2688 	rb_update_pages(cpu_buffer);
2689 	complete(&cpu_buffer->update_done);
2690 }
2691 
2692 /**
2693  * ring_buffer_resize - resize the ring buffer
2694  * @buffer: the buffer to resize.
2695  * @size: the new size.
2696  * @cpu_id: the cpu buffer to resize
2697  *
2698  * Minimum size is 2 * buffer->subbuf_size.
2699  *
2700  * Returns 0 on success and < 0 on failure.
2701  */
ring_buffer_resize(struct trace_buffer * buffer,unsigned long size,int cpu_id)2702 int ring_buffer_resize(struct trace_buffer *buffer, unsigned long size,
2703 			int cpu_id)
2704 {
2705 	struct ring_buffer_per_cpu *cpu_buffer;
2706 	unsigned long nr_pages;
2707 	int cpu, err;
2708 
2709 	/*
2710 	 * Always succeed at resizing a non-existent buffer:
2711 	 */
2712 	if (!buffer)
2713 		return 0;
2714 
2715 	/* Make sure the requested buffer exists */
2716 	if (cpu_id != RING_BUFFER_ALL_CPUS &&
2717 	    !cpumask_test_cpu(cpu_id, buffer->cpumask))
2718 		return 0;
2719 
2720 	nr_pages = DIV_ROUND_UP(size, buffer->subbuf_size);
2721 
2722 	/* we need a minimum of two pages */
2723 	if (nr_pages < 2)
2724 		nr_pages = 2;
2725 
2726 	/* prevent another thread from changing buffer sizes */
2727 	mutex_lock(&buffer->mutex);
2728 	atomic_inc(&buffer->resizing);
2729 
2730 	if (cpu_id == RING_BUFFER_ALL_CPUS) {
2731 		/*
2732 		 * Don't succeed if resizing is disabled, as a reader might be
2733 		 * manipulating the ring buffer and is expecting a sane state while
2734 		 * this is true.
2735 		 */
2736 		for_each_buffer_cpu(buffer, cpu) {
2737 			cpu_buffer = buffer->buffers[cpu];
2738 			if (atomic_read(&cpu_buffer->resize_disabled)) {
2739 				err = -EBUSY;
2740 				goto out_err_unlock;
2741 			}
2742 		}
2743 
2744 		/* calculate the pages to update */
2745 		for_each_buffer_cpu(buffer, cpu) {
2746 			cpu_buffer = buffer->buffers[cpu];
2747 
2748 			cpu_buffer->nr_pages_to_update = nr_pages -
2749 							cpu_buffer->nr_pages;
2750 			/*
2751 			 * nothing more to do for removing pages or no update
2752 			 */
2753 			if (cpu_buffer->nr_pages_to_update <= 0)
2754 				continue;
2755 			/*
2756 			 * to add pages, make sure all new pages can be
2757 			 * allocated without receiving ENOMEM
2758 			 */
2759 			INIT_LIST_HEAD(&cpu_buffer->new_pages);
2760 			if (__rb_allocate_pages(cpu_buffer, cpu_buffer->nr_pages_to_update,
2761 						&cpu_buffer->new_pages)) {
2762 				/* not enough memory for new pages */
2763 				err = -ENOMEM;
2764 				goto out_err;
2765 			}
2766 
2767 			cond_resched();
2768 		}
2769 
2770 		cpus_read_lock();
2771 		/*
2772 		 * Fire off all the required work handlers
2773 		 * We can't schedule on offline CPUs, but it's not necessary
2774 		 * since we can change their buffer sizes without any race.
2775 		 */
2776 		for_each_buffer_cpu(buffer, cpu) {
2777 			cpu_buffer = buffer->buffers[cpu];
2778 			if (!cpu_buffer->nr_pages_to_update)
2779 				continue;
2780 
2781 			/* Can't run something on an offline CPU. */
2782 			if (!cpu_online(cpu)) {
2783 				rb_update_pages(cpu_buffer);
2784 				cpu_buffer->nr_pages_to_update = 0;
2785 			} else {
2786 				/* Run directly if possible. */
2787 				migrate_disable();
2788 				if (cpu != smp_processor_id()) {
2789 					migrate_enable();
2790 					schedule_work_on(cpu,
2791 							 &cpu_buffer->update_pages_work);
2792 				} else {
2793 					update_pages_handler(&cpu_buffer->update_pages_work);
2794 					migrate_enable();
2795 				}
2796 			}
2797 		}
2798 
2799 		/* wait for all the updates to complete */
2800 		for_each_buffer_cpu(buffer, cpu) {
2801 			cpu_buffer = buffer->buffers[cpu];
2802 			if (!cpu_buffer->nr_pages_to_update)
2803 				continue;
2804 
2805 			if (cpu_online(cpu))
2806 				wait_for_completion(&cpu_buffer->update_done);
2807 			cpu_buffer->nr_pages_to_update = 0;
2808 		}
2809 
2810 		cpus_read_unlock();
2811 	} else {
2812 		cpu_buffer = buffer->buffers[cpu_id];
2813 
2814 		if (nr_pages == cpu_buffer->nr_pages)
2815 			goto out;
2816 
2817 		/*
2818 		 * Don't succeed if resizing is disabled, as a reader might be
2819 		 * manipulating the ring buffer and is expecting a sane state while
2820 		 * this is true.
2821 		 */
2822 		if (atomic_read(&cpu_buffer->resize_disabled)) {
2823 			err = -EBUSY;
2824 			goto out_err_unlock;
2825 		}
2826 
2827 		cpu_buffer->nr_pages_to_update = nr_pages -
2828 						cpu_buffer->nr_pages;
2829 
2830 		INIT_LIST_HEAD(&cpu_buffer->new_pages);
2831 		if (cpu_buffer->nr_pages_to_update > 0 &&
2832 			__rb_allocate_pages(cpu_buffer, cpu_buffer->nr_pages_to_update,
2833 					    &cpu_buffer->new_pages)) {
2834 			err = -ENOMEM;
2835 			goto out_err;
2836 		}
2837 
2838 		cpus_read_lock();
2839 
2840 		/* Can't run something on an offline CPU. */
2841 		if (!cpu_online(cpu_id))
2842 			rb_update_pages(cpu_buffer);
2843 		else {
2844 			/* Run directly if possible. */
2845 			migrate_disable();
2846 			if (cpu_id == smp_processor_id()) {
2847 				rb_update_pages(cpu_buffer);
2848 				migrate_enable();
2849 			} else {
2850 				migrate_enable();
2851 				schedule_work_on(cpu_id,
2852 						 &cpu_buffer->update_pages_work);
2853 				wait_for_completion(&cpu_buffer->update_done);
2854 			}
2855 		}
2856 
2857 		cpu_buffer->nr_pages_to_update = 0;
2858 		cpus_read_unlock();
2859 	}
2860 
2861  out:
2862 	/*
2863 	 * The ring buffer resize can happen with the ring buffer
2864 	 * enabled, so that the update disturbs the tracing as little
2865 	 * as possible. But if the buffer is disabled, we do not need
2866 	 * to worry about that, and we can take the time to verify
2867 	 * that the buffer is not corrupt.
2868 	 */
2869 	if (atomic_read(&buffer->record_disabled)) {
2870 		atomic_inc(&buffer->record_disabled);
2871 		/*
2872 		 * Even though the buffer was disabled, we must make sure
2873 		 * that it is truly disabled before calling rb_check_pages.
2874 		 * There could have been a race between checking
2875 		 * record_disable and incrementing it.
2876 		 */
2877 		synchronize_rcu();
2878 		for_each_buffer_cpu(buffer, cpu) {
2879 			unsigned long flags;
2880 
2881 			cpu_buffer = buffer->buffers[cpu];
2882 			raw_spin_lock_irqsave(&cpu_buffer->reader_lock, flags);
2883 			rb_check_pages(cpu_buffer);
2884 			raw_spin_unlock_irqrestore(&cpu_buffer->reader_lock, flags);
2885 		}
2886 		atomic_dec(&buffer->record_disabled);
2887 	}
2888 
2889 	atomic_dec(&buffer->resizing);
2890 	mutex_unlock(&buffer->mutex);
2891 	return 0;
2892 
2893  out_err:
2894 	for_each_buffer_cpu(buffer, cpu) {
2895 		struct buffer_page *bpage, *tmp;
2896 
2897 		cpu_buffer = buffer->buffers[cpu];
2898 		cpu_buffer->nr_pages_to_update = 0;
2899 
2900 		if (list_empty(&cpu_buffer->new_pages))
2901 			continue;
2902 
2903 		list_for_each_entry_safe(bpage, tmp, &cpu_buffer->new_pages,
2904 					list) {
2905 			list_del_init(&bpage->list);
2906 			free_buffer_page(bpage);
2907 		}
2908 	}
2909  out_err_unlock:
2910 	atomic_dec(&buffer->resizing);
2911 	mutex_unlock(&buffer->mutex);
2912 	return err;
2913 }
2914 EXPORT_SYMBOL_GPL(ring_buffer_resize);
2915 
ring_buffer_change_overwrite(struct trace_buffer * buffer,int val)2916 void ring_buffer_change_overwrite(struct trace_buffer *buffer, int val)
2917 {
2918 	mutex_lock(&buffer->mutex);
2919 	if (val)
2920 		buffer->flags |= RB_FL_OVERWRITE;
2921 	else
2922 		buffer->flags &= ~RB_FL_OVERWRITE;
2923 	mutex_unlock(&buffer->mutex);
2924 }
2925 EXPORT_SYMBOL_GPL(ring_buffer_change_overwrite);
2926 
__rb_page_index(struct buffer_page * bpage,unsigned index)2927 static __always_inline void *__rb_page_index(struct buffer_page *bpage, unsigned index)
2928 {
2929 	return bpage->page->data + index;
2930 }
2931 
2932 static __always_inline struct ring_buffer_event *
rb_reader_event(struct ring_buffer_per_cpu * cpu_buffer)2933 rb_reader_event(struct ring_buffer_per_cpu *cpu_buffer)
2934 {
2935 	return __rb_page_index(cpu_buffer->reader_page,
2936 			       cpu_buffer->reader_page->read);
2937 }
2938 
2939 static struct ring_buffer_event *
rb_iter_head_event(struct ring_buffer_iter * iter)2940 rb_iter_head_event(struct ring_buffer_iter *iter)
2941 {
2942 	struct ring_buffer_event *event;
2943 	struct buffer_page *iter_head_page = iter->head_page;
2944 	unsigned long commit;
2945 	unsigned length;
2946 
2947 	if (iter->head != iter->next_event)
2948 		return iter->event;
2949 
2950 	/*
2951 	 * When the writer goes across pages, it issues a cmpxchg which
2952 	 * is a mb(), which will synchronize with the rmb here.
2953 	 * (see rb_tail_page_update() and __rb_reserve_next())
2954 	 */
2955 	commit = rb_page_commit(iter_head_page);
2956 	smp_rmb();
2957 
2958 	/* An event needs to be at least 8 bytes in size */
2959 	if (iter->head > commit - 8)
2960 		goto reset;
2961 
2962 	event = __rb_page_index(iter_head_page, iter->head);
2963 	length = rb_event_length(event);
2964 
2965 	/*
2966 	 * READ_ONCE() doesn't work on functions and we don't want the
2967 	 * compiler doing any crazy optimizations with length.
2968 	 */
2969 	barrier();
2970 
2971 	if ((iter->head + length) > commit || length > iter->event_size)
2972 		/* Writer corrupted the read? */
2973 		goto reset;
2974 
2975 	memcpy(iter->event, event, length);
2976 	/*
2977 	 * If the page stamp is still the same after this rmb() then the
2978 	 * event was safely copied without the writer entering the page.
2979 	 */
2980 	smp_rmb();
2981 
2982 	/* Make sure the page didn't change since we read this */
2983 	if (iter->page_stamp != iter_head_page->page->time_stamp ||
2984 	    commit > rb_page_commit(iter_head_page))
2985 		goto reset;
2986 
2987 	iter->next_event = iter->head + length;
2988 	return iter->event;
2989  reset:
2990 	/* Reset to the beginning */
2991 	iter->page_stamp = iter->read_stamp = iter->head_page->page->time_stamp;
2992 	iter->head = 0;
2993 	iter->next_event = 0;
2994 	iter->missed_events = 1;
2995 	return NULL;
2996 }
2997 
2998 /* Size is determined by what has been committed */
rb_page_size(struct buffer_page * bpage)2999 static __always_inline unsigned rb_page_size(struct buffer_page *bpage)
3000 {
3001 	return rb_page_commit(bpage) & ~RB_MISSED_MASK;
3002 }
3003 
3004 static __always_inline unsigned
rb_commit_index(struct ring_buffer_per_cpu * cpu_buffer)3005 rb_commit_index(struct ring_buffer_per_cpu *cpu_buffer)
3006 {
3007 	return rb_page_commit(cpu_buffer->commit_page);
3008 }
3009 
3010 static __always_inline unsigned
rb_event_index(struct ring_buffer_per_cpu * cpu_buffer,struct ring_buffer_event * event)3011 rb_event_index(struct ring_buffer_per_cpu *cpu_buffer, struct ring_buffer_event *event)
3012 {
3013 	unsigned long addr = (unsigned long)event;
3014 
3015 	addr &= (PAGE_SIZE << cpu_buffer->buffer->subbuf_order) - 1;
3016 
3017 	return addr - BUF_PAGE_HDR_SIZE;
3018 }
3019 
rb_inc_iter(struct ring_buffer_iter * iter)3020 static void rb_inc_iter(struct ring_buffer_iter *iter)
3021 {
3022 	struct ring_buffer_per_cpu *cpu_buffer = iter->cpu_buffer;
3023 
3024 	/*
3025 	 * The iterator could be on the reader page (it starts there).
3026 	 * But the head could have moved, since the reader was
3027 	 * found. Check for this case and assign the iterator
3028 	 * to the head page instead of next.
3029 	 */
3030 	if (iter->head_page == cpu_buffer->reader_page)
3031 		iter->head_page = rb_set_head_page(cpu_buffer);
3032 	else
3033 		rb_inc_page(&iter->head_page);
3034 
3035 	iter->page_stamp = iter->read_stamp = iter->head_page->page->time_stamp;
3036 	iter->head = 0;
3037 	iter->next_event = 0;
3038 }
3039 
3040 /* Return the index into the sub-buffers for a given sub-buffer */
rb_meta_subbuf_idx(struct ring_buffer_meta * meta,void * subbuf)3041 static int rb_meta_subbuf_idx(struct ring_buffer_meta *meta, void *subbuf)
3042 {
3043 	void *subbuf_array;
3044 
3045 	subbuf_array = (void *)meta + sizeof(int) * meta->nr_subbufs;
3046 	subbuf_array = (void *)ALIGN((unsigned long)subbuf_array, meta->subbuf_size);
3047 	return (subbuf - subbuf_array) / meta->subbuf_size;
3048 }
3049 
rb_update_meta_head(struct ring_buffer_per_cpu * cpu_buffer,struct buffer_page * next_page)3050 static void rb_update_meta_head(struct ring_buffer_per_cpu *cpu_buffer,
3051 				struct buffer_page *next_page)
3052 {
3053 	struct ring_buffer_meta *meta = cpu_buffer->ring_meta;
3054 	unsigned long old_head = (unsigned long)next_page->page;
3055 	unsigned long new_head;
3056 
3057 	rb_inc_page(&next_page);
3058 	new_head = (unsigned long)next_page->page;
3059 
3060 	/*
3061 	 * Only move it forward once, if something else came in and
3062 	 * moved it forward, then we don't want to touch it.
3063 	 */
3064 	(void)cmpxchg(&meta->head_buffer, old_head, new_head);
3065 }
3066 
rb_update_meta_reader(struct ring_buffer_per_cpu * cpu_buffer,struct buffer_page * reader)3067 static void rb_update_meta_reader(struct ring_buffer_per_cpu *cpu_buffer,
3068 				  struct buffer_page *reader)
3069 {
3070 	struct ring_buffer_meta *meta = cpu_buffer->ring_meta;
3071 	void *old_reader = cpu_buffer->reader_page->page;
3072 	void *new_reader = reader->page;
3073 	int id;
3074 
3075 	id = reader->id;
3076 	cpu_buffer->reader_page->id = id;
3077 	reader->id = 0;
3078 
3079 	meta->buffers[0] = rb_meta_subbuf_idx(meta, new_reader);
3080 	meta->buffers[id] = rb_meta_subbuf_idx(meta, old_reader);
3081 
3082 	/* The head pointer is the one after the reader */
3083 	rb_update_meta_head(cpu_buffer, reader);
3084 }
3085 
3086 /*
3087  * rb_handle_head_page - writer hit the head page
3088  *
3089  * Returns: +1 to retry page
3090  *           0 to continue
3091  *          -1 on error
3092  */
3093 static int
rb_handle_head_page(struct ring_buffer_per_cpu * cpu_buffer,struct buffer_page * tail_page,struct buffer_page * next_page)3094 rb_handle_head_page(struct ring_buffer_per_cpu *cpu_buffer,
3095 		    struct buffer_page *tail_page,
3096 		    struct buffer_page *next_page)
3097 {
3098 	struct buffer_page *new_head;
3099 	int entries;
3100 	int type;
3101 	int ret;
3102 
3103 	entries = rb_page_entries(next_page);
3104 
3105 	/*
3106 	 * The hard part is here. We need to move the head
3107 	 * forward, and protect against both readers on
3108 	 * other CPUs and writers coming in via interrupts.
3109 	 */
3110 	type = rb_head_page_set_update(cpu_buffer, next_page, tail_page,
3111 				       RB_PAGE_HEAD);
3112 
3113 	/*
3114 	 * type can be one of four:
3115 	 *  NORMAL - an interrupt already moved it for us
3116 	 *  HEAD   - we are the first to get here.
3117 	 *  UPDATE - we are the interrupt interrupting
3118 	 *           a current move.
3119 	 *  MOVED  - a reader on another CPU moved the next
3120 	 *           pointer to its reader page. Give up
3121 	 *           and try again.
3122 	 */
3123 
3124 	switch (type) {
3125 	case RB_PAGE_HEAD:
3126 		/*
3127 		 * We changed the head to UPDATE, thus
3128 		 * it is our responsibility to update
3129 		 * the counters.
3130 		 */
3131 		local_add(entries, &cpu_buffer->overrun);
3132 		local_sub(rb_page_commit(next_page), &cpu_buffer->entries_bytes);
3133 		local_inc(&cpu_buffer->pages_lost);
3134 
3135 		if (cpu_buffer->ring_meta)
3136 			rb_update_meta_head(cpu_buffer, next_page);
3137 		/*
3138 		 * The entries will be zeroed out when we move the
3139 		 * tail page.
3140 		 */
3141 
3142 		/* still more to do */
3143 		break;
3144 
3145 	case RB_PAGE_UPDATE:
3146 		/*
3147 		 * This is an interrupt that interrupt the
3148 		 * previous update. Still more to do.
3149 		 */
3150 		break;
3151 	case RB_PAGE_NORMAL:
3152 		/*
3153 		 * An interrupt came in before the update
3154 		 * and processed this for us.
3155 		 * Nothing left to do.
3156 		 */
3157 		return 1;
3158 	case RB_PAGE_MOVED:
3159 		/*
3160 		 * The reader is on another CPU and just did
3161 		 * a swap with our next_page.
3162 		 * Try again.
3163 		 */
3164 		return 1;
3165 	default:
3166 		RB_WARN_ON(cpu_buffer, 1); /* WTF??? */
3167 		return -1;
3168 	}
3169 
3170 	/*
3171 	 * Now that we are here, the old head pointer is
3172 	 * set to UPDATE. This will keep the reader from
3173 	 * swapping the head page with the reader page.
3174 	 * The reader (on another CPU) will spin till
3175 	 * we are finished.
3176 	 *
3177 	 * We just need to protect against interrupts
3178 	 * doing the job. We will set the next pointer
3179 	 * to HEAD. After that, we set the old pointer
3180 	 * to NORMAL, but only if it was HEAD before.
3181 	 * otherwise we are an interrupt, and only
3182 	 * want the outer most commit to reset it.
3183 	 */
3184 	new_head = next_page;
3185 	rb_inc_page(&new_head);
3186 
3187 	ret = rb_head_page_set_head(cpu_buffer, new_head, next_page,
3188 				    RB_PAGE_NORMAL);
3189 
3190 	/*
3191 	 * Valid returns are:
3192 	 *  HEAD   - an interrupt came in and already set it.
3193 	 *  NORMAL - One of two things:
3194 	 *            1) We really set it.
3195 	 *            2) A bunch of interrupts came in and moved
3196 	 *               the page forward again.
3197 	 */
3198 	switch (ret) {
3199 	case RB_PAGE_HEAD:
3200 	case RB_PAGE_NORMAL:
3201 		/* OK */
3202 		break;
3203 	default:
3204 		RB_WARN_ON(cpu_buffer, 1);
3205 		return -1;
3206 	}
3207 
3208 	/*
3209 	 * It is possible that an interrupt came in,
3210 	 * set the head up, then more interrupts came in
3211 	 * and moved it again. When we get back here,
3212 	 * the page would have been set to NORMAL but we
3213 	 * just set it back to HEAD.
3214 	 *
3215 	 * How do you detect this? Well, if that happened
3216 	 * the tail page would have moved.
3217 	 */
3218 	if (ret == RB_PAGE_NORMAL) {
3219 		struct buffer_page *buffer_tail_page;
3220 
3221 		buffer_tail_page = READ_ONCE(cpu_buffer->tail_page);
3222 		/*
3223 		 * If the tail had moved passed next, then we need
3224 		 * to reset the pointer.
3225 		 */
3226 		if (buffer_tail_page != tail_page &&
3227 		    buffer_tail_page != next_page)
3228 			rb_head_page_set_normal(cpu_buffer, new_head,
3229 						next_page,
3230 						RB_PAGE_HEAD);
3231 	}
3232 
3233 	/*
3234 	 * If this was the outer most commit (the one that
3235 	 * changed the original pointer from HEAD to UPDATE),
3236 	 * then it is up to us to reset it to NORMAL.
3237 	 */
3238 	if (type == RB_PAGE_HEAD) {
3239 		ret = rb_head_page_set_normal(cpu_buffer, next_page,
3240 					      tail_page,
3241 					      RB_PAGE_UPDATE);
3242 		if (RB_WARN_ON(cpu_buffer,
3243 			       ret != RB_PAGE_UPDATE))
3244 			return -1;
3245 	}
3246 
3247 	return 0;
3248 }
3249 
3250 static inline void
rb_reset_tail(struct ring_buffer_per_cpu * cpu_buffer,unsigned long tail,struct rb_event_info * info)3251 rb_reset_tail(struct ring_buffer_per_cpu *cpu_buffer,
3252 	      unsigned long tail, struct rb_event_info *info)
3253 {
3254 	unsigned long bsize = READ_ONCE(cpu_buffer->buffer->subbuf_size);
3255 	struct buffer_page *tail_page = info->tail_page;
3256 	struct ring_buffer_event *event;
3257 	unsigned long length = info->length;
3258 
3259 	/*
3260 	 * Only the event that crossed the page boundary
3261 	 * must fill the old tail_page with padding.
3262 	 */
3263 	if (tail >= bsize) {
3264 		/*
3265 		 * If the page was filled, then we still need
3266 		 * to update the real_end. Reset it to zero
3267 		 * and the reader will ignore it.
3268 		 */
3269 		if (tail == bsize)
3270 			tail_page->real_end = 0;
3271 
3272 		local_sub(length, &tail_page->write);
3273 		return;
3274 	}
3275 
3276 	event = __rb_page_index(tail_page, tail);
3277 
3278 	/*
3279 	 * Save the original length to the meta data.
3280 	 * This will be used by the reader to add lost event
3281 	 * counter.
3282 	 */
3283 	tail_page->real_end = tail;
3284 
3285 	/*
3286 	 * If this event is bigger than the minimum size, then
3287 	 * we need to be careful that we don't subtract the
3288 	 * write counter enough to allow another writer to slip
3289 	 * in on this page.
3290 	 * We put in a discarded commit instead, to make sure
3291 	 * that this space is not used again, and this space will
3292 	 * not be accounted into 'entries_bytes'.
3293 	 *
3294 	 * If we are less than the minimum size, we don't need to
3295 	 * worry about it.
3296 	 */
3297 	if (tail > (bsize - RB_EVNT_MIN_SIZE)) {
3298 		/* No room for any events */
3299 
3300 		/* Mark the rest of the page with padding */
3301 		rb_event_set_padding(event);
3302 
3303 		/* Make sure the padding is visible before the write update */
3304 		smp_wmb();
3305 
3306 		/* Set the write back to the previous setting */
3307 		local_sub(length, &tail_page->write);
3308 		return;
3309 	}
3310 
3311 	/* Put in a discarded event */
3312 	event->array[0] = (bsize - tail) - RB_EVNT_HDR_SIZE;
3313 	event->type_len = RINGBUF_TYPE_PADDING;
3314 	/* time delta must be non zero */
3315 	event->time_delta = 1;
3316 
3317 	/* account for padding bytes */
3318 	local_add(bsize - tail, &cpu_buffer->entries_bytes);
3319 
3320 	/* Make sure the padding is visible before the tail_page->write update */
3321 	smp_wmb();
3322 
3323 	/* Set write to end of buffer */
3324 	length = (tail + length) - bsize;
3325 	local_sub(length, &tail_page->write);
3326 }
3327 
3328 static inline void rb_end_commit(struct ring_buffer_per_cpu *cpu_buffer);
3329 
3330 /*
3331  * This is the slow path, force gcc not to inline it.
3332  */
3333 static noinline struct ring_buffer_event *
rb_move_tail(struct ring_buffer_per_cpu * cpu_buffer,unsigned long tail,struct rb_event_info * info)3334 rb_move_tail(struct ring_buffer_per_cpu *cpu_buffer,
3335 	     unsigned long tail, struct rb_event_info *info)
3336 {
3337 	struct buffer_page *tail_page = info->tail_page;
3338 	struct buffer_page *commit_page = cpu_buffer->commit_page;
3339 	struct trace_buffer *buffer = cpu_buffer->buffer;
3340 	struct buffer_page *next_page;
3341 	int ret;
3342 
3343 	next_page = tail_page;
3344 
3345 	rb_inc_page(&next_page);
3346 
3347 	/*
3348 	 * If for some reason, we had an interrupt storm that made
3349 	 * it all the way around the buffer, bail, and warn
3350 	 * about it.
3351 	 */
3352 	if (unlikely(next_page == commit_page)) {
3353 		local_inc(&cpu_buffer->commit_overrun);
3354 		goto out_reset;
3355 	}
3356 
3357 	/*
3358 	 * This is where the fun begins!
3359 	 *
3360 	 * We are fighting against races between a reader that
3361 	 * could be on another CPU trying to swap its reader
3362 	 * page with the buffer head.
3363 	 *
3364 	 * We are also fighting against interrupts coming in and
3365 	 * moving the head or tail on us as well.
3366 	 *
3367 	 * If the next page is the head page then we have filled
3368 	 * the buffer, unless the commit page is still on the
3369 	 * reader page.
3370 	 */
3371 	if (rb_is_head_page(next_page, &tail_page->list)) {
3372 
3373 		/*
3374 		 * If the commit is not on the reader page, then
3375 		 * move the header page.
3376 		 */
3377 		if (!rb_is_reader_page(cpu_buffer->commit_page)) {
3378 			/*
3379 			 * If we are not in overwrite mode,
3380 			 * this is easy, just stop here.
3381 			 */
3382 			if (!(buffer->flags & RB_FL_OVERWRITE)) {
3383 				local_inc(&cpu_buffer->dropped_events);
3384 				goto out_reset;
3385 			}
3386 
3387 			ret = rb_handle_head_page(cpu_buffer,
3388 						  tail_page,
3389 						  next_page);
3390 			if (ret < 0)
3391 				goto out_reset;
3392 			if (ret)
3393 				goto out_again;
3394 		} else {
3395 			/*
3396 			 * We need to be careful here too. The
3397 			 * commit page could still be on the reader
3398 			 * page. We could have a small buffer, and
3399 			 * have filled up the buffer with events
3400 			 * from interrupts and such, and wrapped.
3401 			 *
3402 			 * Note, if the tail page is also on the
3403 			 * reader_page, we let it move out.
3404 			 */
3405 			if (unlikely((cpu_buffer->commit_page !=
3406 				      cpu_buffer->tail_page) &&
3407 				     (cpu_buffer->commit_page ==
3408 				      cpu_buffer->reader_page))) {
3409 				local_inc(&cpu_buffer->commit_overrun);
3410 				goto out_reset;
3411 			}
3412 		}
3413 	}
3414 
3415 	rb_tail_page_update(cpu_buffer, tail_page, next_page);
3416 
3417  out_again:
3418 
3419 	rb_reset_tail(cpu_buffer, tail, info);
3420 
3421 	/* Commit what we have for now. */
3422 	rb_end_commit(cpu_buffer);
3423 	/* rb_end_commit() decs committing */
3424 	local_inc(&cpu_buffer->committing);
3425 
3426 	/* fail and let the caller try again */
3427 	return ERR_PTR(-EAGAIN);
3428 
3429  out_reset:
3430 	/* reset write */
3431 	rb_reset_tail(cpu_buffer, tail, info);
3432 
3433 	return NULL;
3434 }
3435 
3436 /* Slow path */
3437 static struct ring_buffer_event *
rb_add_time_stamp(struct ring_buffer_per_cpu * cpu_buffer,struct ring_buffer_event * event,u64 delta,bool abs)3438 rb_add_time_stamp(struct ring_buffer_per_cpu *cpu_buffer,
3439 		  struct ring_buffer_event *event, u64 delta, bool abs)
3440 {
3441 	if (abs)
3442 		event->type_len = RINGBUF_TYPE_TIME_STAMP;
3443 	else
3444 		event->type_len = RINGBUF_TYPE_TIME_EXTEND;
3445 
3446 	/* Not the first event on the page, or not delta? */
3447 	if (abs || rb_event_index(cpu_buffer, event)) {
3448 		event->time_delta = delta & TS_MASK;
3449 		event->array[0] = delta >> TS_SHIFT;
3450 	} else {
3451 		/* nope, just zero it */
3452 		event->time_delta = 0;
3453 		event->array[0] = 0;
3454 	}
3455 
3456 	return skip_time_extend(event);
3457 }
3458 
3459 #ifndef CONFIG_HAVE_UNSTABLE_SCHED_CLOCK
sched_clock_stable(void)3460 static inline bool sched_clock_stable(void)
3461 {
3462 	return true;
3463 }
3464 #endif
3465 
3466 static void
rb_check_timestamp(struct ring_buffer_per_cpu * cpu_buffer,struct rb_event_info * info)3467 rb_check_timestamp(struct ring_buffer_per_cpu *cpu_buffer,
3468 		   struct rb_event_info *info)
3469 {
3470 	u64 write_stamp;
3471 
3472 	WARN_ONCE(1, "Delta way too big! %llu ts=%llu before=%llu after=%llu write stamp=%llu\n%s",
3473 		  (unsigned long long)info->delta,
3474 		  (unsigned long long)info->ts,
3475 		  (unsigned long long)info->before,
3476 		  (unsigned long long)info->after,
3477 		  (unsigned long long)({rb_time_read(&cpu_buffer->write_stamp, &write_stamp); write_stamp;}),
3478 		  sched_clock_stable() ? "" :
3479 		  "If you just came from a suspend/resume,\n"
3480 		  "please switch to the trace global clock:\n"
3481 		  "  echo global > /sys/kernel/tracing/trace_clock\n"
3482 		  "or add trace_clock=global to the kernel command line\n");
3483 }
3484 
rb_add_timestamp(struct ring_buffer_per_cpu * cpu_buffer,struct ring_buffer_event ** event,struct rb_event_info * info,u64 * delta,unsigned int * length)3485 static void rb_add_timestamp(struct ring_buffer_per_cpu *cpu_buffer,
3486 				      struct ring_buffer_event **event,
3487 				      struct rb_event_info *info,
3488 				      u64 *delta,
3489 				      unsigned int *length)
3490 {
3491 	bool abs = info->add_timestamp &
3492 		(RB_ADD_STAMP_FORCE | RB_ADD_STAMP_ABSOLUTE);
3493 
3494 	if (unlikely(info->delta > (1ULL << 59))) {
3495 		/*
3496 		 * Some timers can use more than 59 bits, and when a timestamp
3497 		 * is added to the buffer, it will lose those bits.
3498 		 */
3499 		if (abs && (info->ts & TS_MSB)) {
3500 			info->delta &= ABS_TS_MASK;
3501 
3502 		/* did the clock go backwards */
3503 		} else if (info->before == info->after && info->before > info->ts) {
3504 			/* not interrupted */
3505 			static int once;
3506 
3507 			/*
3508 			 * This is possible with a recalibrating of the TSC.
3509 			 * Do not produce a call stack, but just report it.
3510 			 */
3511 			if (!once) {
3512 				once++;
3513 				pr_warn("Ring buffer clock went backwards: %llu -> %llu\n",
3514 					info->before, info->ts);
3515 			}
3516 		} else
3517 			rb_check_timestamp(cpu_buffer, info);
3518 		if (!abs)
3519 			info->delta = 0;
3520 	}
3521 	*event = rb_add_time_stamp(cpu_buffer, *event, info->delta, abs);
3522 	*length -= RB_LEN_TIME_EXTEND;
3523 	*delta = 0;
3524 }
3525 
3526 /**
3527  * rb_update_event - update event type and data
3528  * @cpu_buffer: The per cpu buffer of the @event
3529  * @event: the event to update
3530  * @info: The info to update the @event with (contains length and delta)
3531  *
3532  * Update the type and data fields of the @event. The length
3533  * is the actual size that is written to the ring buffer,
3534  * and with this, we can determine what to place into the
3535  * data field.
3536  */
3537 static void
rb_update_event(struct ring_buffer_per_cpu * cpu_buffer,struct ring_buffer_event * event,struct rb_event_info * info)3538 rb_update_event(struct ring_buffer_per_cpu *cpu_buffer,
3539 		struct ring_buffer_event *event,
3540 		struct rb_event_info *info)
3541 {
3542 	unsigned length = info->length;
3543 	u64 delta = info->delta;
3544 	unsigned int nest = local_read(&cpu_buffer->committing) - 1;
3545 
3546 	if (!WARN_ON_ONCE(nest >= MAX_NEST))
3547 		cpu_buffer->event_stamp[nest] = info->ts;
3548 
3549 	/*
3550 	 * If we need to add a timestamp, then we
3551 	 * add it to the start of the reserved space.
3552 	 */
3553 	if (unlikely(info->add_timestamp))
3554 		rb_add_timestamp(cpu_buffer, &event, info, &delta, &length);
3555 
3556 	event->time_delta = delta;
3557 	length -= RB_EVNT_HDR_SIZE;
3558 	if (length > RB_MAX_SMALL_DATA || RB_FORCE_8BYTE_ALIGNMENT) {
3559 		event->type_len = 0;
3560 		event->array[0] = length;
3561 	} else
3562 		event->type_len = DIV_ROUND_UP(length, RB_ALIGNMENT);
3563 }
3564 
rb_calculate_event_length(unsigned length)3565 static unsigned rb_calculate_event_length(unsigned length)
3566 {
3567 	struct ring_buffer_event event; /* Used only for sizeof array */
3568 
3569 	/* zero length can cause confusions */
3570 	if (!length)
3571 		length++;
3572 
3573 	if (length > RB_MAX_SMALL_DATA || RB_FORCE_8BYTE_ALIGNMENT)
3574 		length += sizeof(event.array[0]);
3575 
3576 	length += RB_EVNT_HDR_SIZE;
3577 	length = ALIGN(length, RB_ARCH_ALIGNMENT);
3578 
3579 	/*
3580 	 * In case the time delta is larger than the 27 bits for it
3581 	 * in the header, we need to add a timestamp. If another
3582 	 * event comes in when trying to discard this one to increase
3583 	 * the length, then the timestamp will be added in the allocated
3584 	 * space of this event. If length is bigger than the size needed
3585 	 * for the TIME_EXTEND, then padding has to be used. The events
3586 	 * length must be either RB_LEN_TIME_EXTEND, or greater than or equal
3587 	 * to RB_LEN_TIME_EXTEND + 8, as 8 is the minimum size for padding.
3588 	 * As length is a multiple of 4, we only need to worry if it
3589 	 * is 12 (RB_LEN_TIME_EXTEND + 4).
3590 	 */
3591 	if (length == RB_LEN_TIME_EXTEND + RB_ALIGNMENT)
3592 		length += RB_ALIGNMENT;
3593 
3594 	return length;
3595 }
3596 
3597 static inline bool
rb_try_to_discard(struct ring_buffer_per_cpu * cpu_buffer,struct ring_buffer_event * event)3598 rb_try_to_discard(struct ring_buffer_per_cpu *cpu_buffer,
3599 		  struct ring_buffer_event *event)
3600 {
3601 	unsigned long new_index, old_index;
3602 	struct buffer_page *bpage;
3603 	unsigned long addr;
3604 
3605 	new_index = rb_event_index(cpu_buffer, event);
3606 	old_index = new_index + rb_event_ts_length(event);
3607 	addr = (unsigned long)event;
3608 	addr &= ~((PAGE_SIZE << cpu_buffer->buffer->subbuf_order) - 1);
3609 
3610 	bpage = READ_ONCE(cpu_buffer->tail_page);
3611 
3612 	/*
3613 	 * Make sure the tail_page is still the same and
3614 	 * the next write location is the end of this event
3615 	 */
3616 	if (bpage->page == (void *)addr && rb_page_write(bpage) == old_index) {
3617 		unsigned long write_mask =
3618 			local_read(&bpage->write) & ~RB_WRITE_MASK;
3619 		unsigned long event_length = rb_event_length(event);
3620 
3621 		/*
3622 		 * For the before_stamp to be different than the write_stamp
3623 		 * to make sure that the next event adds an absolute
3624 		 * value and does not rely on the saved write stamp, which
3625 		 * is now going to be bogus.
3626 		 *
3627 		 * By setting the before_stamp to zero, the next event
3628 		 * is not going to use the write_stamp and will instead
3629 		 * create an absolute timestamp. This means there's no
3630 		 * reason to update the wirte_stamp!
3631 		 */
3632 		rb_time_set(&cpu_buffer->before_stamp, 0);
3633 
3634 		/*
3635 		 * If an event were to come in now, it would see that the
3636 		 * write_stamp and the before_stamp are different, and assume
3637 		 * that this event just added itself before updating
3638 		 * the write stamp. The interrupting event will fix the
3639 		 * write stamp for us, and use an absolute timestamp.
3640 		 */
3641 
3642 		/*
3643 		 * This is on the tail page. It is possible that
3644 		 * a write could come in and move the tail page
3645 		 * and write to the next page. That is fine
3646 		 * because we just shorten what is on this page.
3647 		 */
3648 		old_index += write_mask;
3649 		new_index += write_mask;
3650 
3651 		/* caution: old_index gets updated on cmpxchg failure */
3652 		if (local_try_cmpxchg(&bpage->write, &old_index, new_index)) {
3653 			/* update counters */
3654 			local_sub(event_length, &cpu_buffer->entries_bytes);
3655 			return true;
3656 		}
3657 	}
3658 
3659 	/* could not discard */
3660 	return false;
3661 }
3662 
rb_start_commit(struct ring_buffer_per_cpu * cpu_buffer)3663 static void rb_start_commit(struct ring_buffer_per_cpu *cpu_buffer)
3664 {
3665 	local_inc(&cpu_buffer->committing);
3666 	local_inc(&cpu_buffer->commits);
3667 }
3668 
3669 static __always_inline void
rb_set_commit_to_write(struct ring_buffer_per_cpu * cpu_buffer)3670 rb_set_commit_to_write(struct ring_buffer_per_cpu *cpu_buffer)
3671 {
3672 	unsigned long max_count;
3673 
3674 	/*
3675 	 * We only race with interrupts and NMIs on this CPU.
3676 	 * If we own the commit event, then we can commit
3677 	 * all others that interrupted us, since the interruptions
3678 	 * are in stack format (they finish before they come
3679 	 * back to us). This allows us to do a simple loop to
3680 	 * assign the commit to the tail.
3681 	 */
3682  again:
3683 	max_count = cpu_buffer->nr_pages * 100;
3684 
3685 	while (cpu_buffer->commit_page != READ_ONCE(cpu_buffer->tail_page)) {
3686 		if (RB_WARN_ON(cpu_buffer, !(--max_count)))
3687 			return;
3688 		if (RB_WARN_ON(cpu_buffer,
3689 			       rb_is_reader_page(cpu_buffer->tail_page)))
3690 			return;
3691 		/*
3692 		 * No need for a memory barrier here, as the update
3693 		 * of the tail_page did it for this page.
3694 		 */
3695 		local_set(&cpu_buffer->commit_page->page->commit,
3696 			  rb_page_write(cpu_buffer->commit_page));
3697 		rb_inc_page(&cpu_buffer->commit_page);
3698 		if (cpu_buffer->ring_meta) {
3699 			struct ring_buffer_meta *meta = cpu_buffer->ring_meta;
3700 			meta->commit_buffer = (unsigned long)cpu_buffer->commit_page->page;
3701 		}
3702 		/* add barrier to keep gcc from optimizing too much */
3703 		barrier();
3704 	}
3705 	while (rb_commit_index(cpu_buffer) !=
3706 	       rb_page_write(cpu_buffer->commit_page)) {
3707 
3708 		/* Make sure the readers see the content of what is committed. */
3709 		smp_wmb();
3710 		local_set(&cpu_buffer->commit_page->page->commit,
3711 			  rb_page_write(cpu_buffer->commit_page));
3712 		RB_WARN_ON(cpu_buffer,
3713 			   local_read(&cpu_buffer->commit_page->page->commit) &
3714 			   ~RB_WRITE_MASK);
3715 		barrier();
3716 	}
3717 
3718 	/* again, keep gcc from optimizing */
3719 	barrier();
3720 
3721 	/*
3722 	 * If an interrupt came in just after the first while loop
3723 	 * and pushed the tail page forward, we will be left with
3724 	 * a dangling commit that will never go forward.
3725 	 */
3726 	if (unlikely(cpu_buffer->commit_page != READ_ONCE(cpu_buffer->tail_page)))
3727 		goto again;
3728 }
3729 
rb_end_commit(struct ring_buffer_per_cpu * cpu_buffer)3730 static __always_inline void rb_end_commit(struct ring_buffer_per_cpu *cpu_buffer)
3731 {
3732 	unsigned long commits;
3733 
3734 	if (RB_WARN_ON(cpu_buffer,
3735 		       !local_read(&cpu_buffer->committing)))
3736 		return;
3737 
3738  again:
3739 	commits = local_read(&cpu_buffer->commits);
3740 	/* synchronize with interrupts */
3741 	barrier();
3742 	if (local_read(&cpu_buffer->committing) == 1)
3743 		rb_set_commit_to_write(cpu_buffer);
3744 
3745 	local_dec(&cpu_buffer->committing);
3746 
3747 	/* synchronize with interrupts */
3748 	barrier();
3749 
3750 	/*
3751 	 * Need to account for interrupts coming in between the
3752 	 * updating of the commit page and the clearing of the
3753 	 * committing counter.
3754 	 */
3755 	if (unlikely(local_read(&cpu_buffer->commits) != commits) &&
3756 	    !local_read(&cpu_buffer->committing)) {
3757 		local_inc(&cpu_buffer->committing);
3758 		goto again;
3759 	}
3760 }
3761 
rb_event_discard(struct ring_buffer_event * event)3762 static inline void rb_event_discard(struct ring_buffer_event *event)
3763 {
3764 	if (extended_time(event))
3765 		event = skip_time_extend(event);
3766 
3767 	/* array[0] holds the actual length for the discarded event */
3768 	event->array[0] = rb_event_data_length(event) - RB_EVNT_HDR_SIZE;
3769 	event->type_len = RINGBUF_TYPE_PADDING;
3770 	/* time delta must be non zero */
3771 	if (!event->time_delta)
3772 		event->time_delta = 1;
3773 }
3774 
rb_commit(struct ring_buffer_per_cpu * cpu_buffer)3775 static void rb_commit(struct ring_buffer_per_cpu *cpu_buffer)
3776 {
3777 	local_inc(&cpu_buffer->entries);
3778 	rb_end_commit(cpu_buffer);
3779 }
3780 
3781 static __always_inline void
rb_wakeups(struct trace_buffer * buffer,struct ring_buffer_per_cpu * cpu_buffer)3782 rb_wakeups(struct trace_buffer *buffer, struct ring_buffer_per_cpu *cpu_buffer)
3783 {
3784 	if (buffer->irq_work.waiters_pending) {
3785 		buffer->irq_work.waiters_pending = false;
3786 		/* irq_work_queue() supplies it's own memory barriers */
3787 		irq_work_queue(&buffer->irq_work.work);
3788 	}
3789 
3790 	if (cpu_buffer->irq_work.waiters_pending) {
3791 		cpu_buffer->irq_work.waiters_pending = false;
3792 		/* irq_work_queue() supplies it's own memory barriers */
3793 		irq_work_queue(&cpu_buffer->irq_work.work);
3794 	}
3795 
3796 	if (cpu_buffer->last_pages_touch == local_read(&cpu_buffer->pages_touched))
3797 		return;
3798 
3799 	if (cpu_buffer->reader_page == cpu_buffer->commit_page)
3800 		return;
3801 
3802 	if (!cpu_buffer->irq_work.full_waiters_pending)
3803 		return;
3804 
3805 	cpu_buffer->last_pages_touch = local_read(&cpu_buffer->pages_touched);
3806 
3807 	if (!full_hit(buffer, cpu_buffer->cpu, cpu_buffer->shortest_full))
3808 		return;
3809 
3810 	cpu_buffer->irq_work.wakeup_full = true;
3811 	cpu_buffer->irq_work.full_waiters_pending = false;
3812 	/* irq_work_queue() supplies it's own memory barriers */
3813 	irq_work_queue(&cpu_buffer->irq_work.work);
3814 }
3815 
3816 #ifdef CONFIG_RING_BUFFER_RECORD_RECURSION
3817 # define do_ring_buffer_record_recursion()	\
3818 	do_ftrace_record_recursion(_THIS_IP_, _RET_IP_)
3819 #else
3820 # define do_ring_buffer_record_recursion() do { } while (0)
3821 #endif
3822 
3823 /*
3824  * The lock and unlock are done within a preempt disable section.
3825  * The current_context per_cpu variable can only be modified
3826  * by the current task between lock and unlock. But it can
3827  * be modified more than once via an interrupt. To pass this
3828  * information from the lock to the unlock without having to
3829  * access the 'in_interrupt()' functions again (which do show
3830  * a bit of overhead in something as critical as function tracing,
3831  * we use a bitmask trick.
3832  *
3833  *  bit 1 =  NMI context
3834  *  bit 2 =  IRQ context
3835  *  bit 3 =  SoftIRQ context
3836  *  bit 4 =  normal context.
3837  *
3838  * This works because this is the order of contexts that can
3839  * preempt other contexts. A SoftIRQ never preempts an IRQ
3840  * context.
3841  *
3842  * When the context is determined, the corresponding bit is
3843  * checked and set (if it was set, then a recursion of that context
3844  * happened).
3845  *
3846  * On unlock, we need to clear this bit. To do so, just subtract
3847  * 1 from the current_context and AND it to itself.
3848  *
3849  * (binary)
3850  *  101 - 1 = 100
3851  *  101 & 100 = 100 (clearing bit zero)
3852  *
3853  *  1010 - 1 = 1001
3854  *  1010 & 1001 = 1000 (clearing bit 1)
3855  *
3856  * The least significant bit can be cleared this way, and it
3857  * just so happens that it is the same bit corresponding to
3858  * the current context.
3859  *
3860  * Now the TRANSITION bit breaks the above slightly. The TRANSITION bit
3861  * is set when a recursion is detected at the current context, and if
3862  * the TRANSITION bit is already set, it will fail the recursion.
3863  * This is needed because there's a lag between the changing of
3864  * interrupt context and updating the preempt count. In this case,
3865  * a false positive will be found. To handle this, one extra recursion
3866  * is allowed, and this is done by the TRANSITION bit. If the TRANSITION
3867  * bit is already set, then it is considered a recursion and the function
3868  * ends. Otherwise, the TRANSITION bit is set, and that bit is returned.
3869  *
3870  * On the trace_recursive_unlock(), the TRANSITION bit will be the first
3871  * to be cleared. Even if it wasn't the context that set it. That is,
3872  * if an interrupt comes in while NORMAL bit is set and the ring buffer
3873  * is called before preempt_count() is updated, since the check will
3874  * be on the NORMAL bit, the TRANSITION bit will then be set. If an
3875  * NMI then comes in, it will set the NMI bit, but when the NMI code
3876  * does the trace_recursive_unlock() it will clear the TRANSITION bit
3877  * and leave the NMI bit set. But this is fine, because the interrupt
3878  * code that set the TRANSITION bit will then clear the NMI bit when it
3879  * calls trace_recursive_unlock(). If another NMI comes in, it will
3880  * set the TRANSITION bit and continue.
3881  *
3882  * Note: The TRANSITION bit only handles a single transition between context.
3883  */
3884 
3885 static __always_inline bool
trace_recursive_lock(struct ring_buffer_per_cpu * cpu_buffer)3886 trace_recursive_lock(struct ring_buffer_per_cpu *cpu_buffer)
3887 {
3888 	unsigned int val = cpu_buffer->current_context;
3889 	int bit = interrupt_context_level();
3890 
3891 	bit = RB_CTX_NORMAL - bit;
3892 
3893 	if (unlikely(val & (1 << (bit + cpu_buffer->nest)))) {
3894 		/*
3895 		 * It is possible that this was called by transitioning
3896 		 * between interrupt context, and preempt_count() has not
3897 		 * been updated yet. In this case, use the TRANSITION bit.
3898 		 */
3899 		bit = RB_CTX_TRANSITION;
3900 		if (val & (1 << (bit + cpu_buffer->nest))) {
3901 			do_ring_buffer_record_recursion();
3902 			return true;
3903 		}
3904 	}
3905 
3906 	val |= (1 << (bit + cpu_buffer->nest));
3907 	cpu_buffer->current_context = val;
3908 
3909 	return false;
3910 }
3911 
3912 static __always_inline void
trace_recursive_unlock(struct ring_buffer_per_cpu * cpu_buffer)3913 trace_recursive_unlock(struct ring_buffer_per_cpu *cpu_buffer)
3914 {
3915 	cpu_buffer->current_context &=
3916 		cpu_buffer->current_context - (1 << cpu_buffer->nest);
3917 }
3918 
3919 /* The recursive locking above uses 5 bits */
3920 #define NESTED_BITS 5
3921 
3922 /**
3923  * ring_buffer_nest_start - Allow to trace while nested
3924  * @buffer: The ring buffer to modify
3925  *
3926  * The ring buffer has a safety mechanism to prevent recursion.
3927  * But there may be a case where a trace needs to be done while
3928  * tracing something else. In this case, calling this function
3929  * will allow this function to nest within a currently active
3930  * ring_buffer_lock_reserve().
3931  *
3932  * Call this function before calling another ring_buffer_lock_reserve() and
3933  * call ring_buffer_nest_end() after the nested ring_buffer_unlock_commit().
3934  */
ring_buffer_nest_start(struct trace_buffer * buffer)3935 void ring_buffer_nest_start(struct trace_buffer *buffer)
3936 {
3937 	struct ring_buffer_per_cpu *cpu_buffer;
3938 	int cpu;
3939 
3940 	/* Enabled by ring_buffer_nest_end() */
3941 	preempt_disable_notrace();
3942 	cpu = raw_smp_processor_id();
3943 	cpu_buffer = buffer->buffers[cpu];
3944 	/* This is the shift value for the above recursive locking */
3945 	cpu_buffer->nest += NESTED_BITS;
3946 }
3947 
3948 /**
3949  * ring_buffer_nest_end - Allow to trace while nested
3950  * @buffer: The ring buffer to modify
3951  *
3952  * Must be called after ring_buffer_nest_start() and after the
3953  * ring_buffer_unlock_commit().
3954  */
ring_buffer_nest_end(struct trace_buffer * buffer)3955 void ring_buffer_nest_end(struct trace_buffer *buffer)
3956 {
3957 	struct ring_buffer_per_cpu *cpu_buffer;
3958 	int cpu;
3959 
3960 	/* disabled by ring_buffer_nest_start() */
3961 	cpu = raw_smp_processor_id();
3962 	cpu_buffer = buffer->buffers[cpu];
3963 	/* This is the shift value for the above recursive locking */
3964 	cpu_buffer->nest -= NESTED_BITS;
3965 	preempt_enable_notrace();
3966 }
3967 
3968 /**
3969  * ring_buffer_unlock_commit - commit a reserved
3970  * @buffer: The buffer to commit to
3971  *
3972  * This commits the data to the ring buffer, and releases any locks held.
3973  *
3974  * Must be paired with ring_buffer_lock_reserve.
3975  */
ring_buffer_unlock_commit(struct trace_buffer * buffer)3976 int ring_buffer_unlock_commit(struct trace_buffer *buffer)
3977 {
3978 	struct ring_buffer_per_cpu *cpu_buffer;
3979 	int cpu = raw_smp_processor_id();
3980 
3981 	cpu_buffer = buffer->buffers[cpu];
3982 
3983 	rb_commit(cpu_buffer);
3984 
3985 	rb_wakeups(buffer, cpu_buffer);
3986 
3987 	trace_recursive_unlock(cpu_buffer);
3988 
3989 	preempt_enable_notrace();
3990 
3991 	return 0;
3992 }
3993 EXPORT_SYMBOL_GPL(ring_buffer_unlock_commit);
3994 
3995 /* Special value to validate all deltas on a page. */
3996 #define CHECK_FULL_PAGE		1L
3997 
3998 #ifdef CONFIG_RING_BUFFER_VALIDATE_TIME_DELTAS
3999 
show_irq_str(int bits)4000 static const char *show_irq_str(int bits)
4001 {
4002 	const char *type[] = {
4003 		".",	// 0
4004 		"s",	// 1
4005 		"h",	// 2
4006 		"Hs",	// 3
4007 		"n",	// 4
4008 		"Ns",	// 5
4009 		"Nh",	// 6
4010 		"NHs",	// 7
4011 	};
4012 
4013 	return type[bits];
4014 }
4015 
4016 /* Assume this is an trace event */
show_flags(struct ring_buffer_event * event)4017 static const char *show_flags(struct ring_buffer_event *event)
4018 {
4019 	struct trace_entry *entry;
4020 	int bits = 0;
4021 
4022 	if (rb_event_data_length(event) - RB_EVNT_HDR_SIZE < sizeof(*entry))
4023 		return "X";
4024 
4025 	entry = ring_buffer_event_data(event);
4026 
4027 	if (entry->flags & TRACE_FLAG_SOFTIRQ)
4028 		bits |= 1;
4029 
4030 	if (entry->flags & TRACE_FLAG_HARDIRQ)
4031 		bits |= 2;
4032 
4033 	if (entry->flags & TRACE_FLAG_NMI)
4034 		bits |= 4;
4035 
4036 	return show_irq_str(bits);
4037 }
4038 
show_irq(struct ring_buffer_event * event)4039 static const char *show_irq(struct ring_buffer_event *event)
4040 {
4041 	struct trace_entry *entry;
4042 
4043 	if (rb_event_data_length(event) - RB_EVNT_HDR_SIZE < sizeof(*entry))
4044 		return "";
4045 
4046 	entry = ring_buffer_event_data(event);
4047 	if (entry->flags & TRACE_FLAG_IRQS_OFF)
4048 		return "d";
4049 	return "";
4050 }
4051 
show_interrupt_level(void)4052 static const char *show_interrupt_level(void)
4053 {
4054 	unsigned long pc = preempt_count();
4055 	unsigned char level = 0;
4056 
4057 	if (pc & SOFTIRQ_OFFSET)
4058 		level |= 1;
4059 
4060 	if (pc & HARDIRQ_MASK)
4061 		level |= 2;
4062 
4063 	if (pc & NMI_MASK)
4064 		level |= 4;
4065 
4066 	return show_irq_str(level);
4067 }
4068 
dump_buffer_page(struct buffer_data_page * bpage,struct rb_event_info * info,unsigned long tail)4069 static void dump_buffer_page(struct buffer_data_page *bpage,
4070 			     struct rb_event_info *info,
4071 			     unsigned long tail)
4072 {
4073 	struct ring_buffer_event *event;
4074 	u64 ts, delta;
4075 	int e;
4076 
4077 	ts = bpage->time_stamp;
4078 	pr_warn("  [%lld] PAGE TIME STAMP\n", ts);
4079 
4080 	for (e = 0; e < tail; e += rb_event_length(event)) {
4081 
4082 		event = (struct ring_buffer_event *)(bpage->data + e);
4083 
4084 		switch (event->type_len) {
4085 
4086 		case RINGBUF_TYPE_TIME_EXTEND:
4087 			delta = rb_event_time_stamp(event);
4088 			ts += delta;
4089 			pr_warn(" 0x%x: [%lld] delta:%lld TIME EXTEND\n",
4090 				e, ts, delta);
4091 			break;
4092 
4093 		case RINGBUF_TYPE_TIME_STAMP:
4094 			delta = rb_event_time_stamp(event);
4095 			ts = rb_fix_abs_ts(delta, ts);
4096 			pr_warn(" 0x%x:  [%lld] absolute:%lld TIME STAMP\n",
4097 				e, ts, delta);
4098 			break;
4099 
4100 		case RINGBUF_TYPE_PADDING:
4101 			ts += event->time_delta;
4102 			pr_warn(" 0x%x:  [%lld] delta:%d PADDING\n",
4103 				e, ts, event->time_delta);
4104 			break;
4105 
4106 		case RINGBUF_TYPE_DATA:
4107 			ts += event->time_delta;
4108 			pr_warn(" 0x%x:  [%lld] delta:%d %s%s\n",
4109 				e, ts, event->time_delta,
4110 				show_flags(event), show_irq(event));
4111 			break;
4112 
4113 		default:
4114 			break;
4115 		}
4116 	}
4117 	pr_warn("expected end:0x%lx last event actually ended at:0x%x\n", tail, e);
4118 }
4119 
4120 static DEFINE_PER_CPU(atomic_t, checking);
4121 static atomic_t ts_dump;
4122 
4123 #define buffer_warn_return(fmt, ...)					\
4124 	do {								\
4125 		/* If another report is happening, ignore this one */	\
4126 		if (atomic_inc_return(&ts_dump) != 1) {			\
4127 			atomic_dec(&ts_dump);				\
4128 			goto out;					\
4129 		}							\
4130 		atomic_inc(&cpu_buffer->record_disabled);		\
4131 		pr_warn(fmt, ##__VA_ARGS__);				\
4132 		dump_buffer_page(bpage, info, tail);			\
4133 		atomic_dec(&ts_dump);					\
4134 		/* There's some cases in boot up that this can happen */ \
4135 		if (WARN_ON_ONCE(system_state != SYSTEM_BOOTING))	\
4136 			/* Do not re-enable checking */			\
4137 			return;						\
4138 	} while (0)
4139 
4140 /*
4141  * Check if the current event time stamp matches the deltas on
4142  * the buffer page.
4143  */
check_buffer(struct ring_buffer_per_cpu * cpu_buffer,struct rb_event_info * info,unsigned long tail)4144 static void check_buffer(struct ring_buffer_per_cpu *cpu_buffer,
4145 			 struct rb_event_info *info,
4146 			 unsigned long tail)
4147 {
4148 	struct buffer_data_page *bpage;
4149 	u64 ts, delta;
4150 	bool full = false;
4151 	int ret;
4152 
4153 	bpage = info->tail_page->page;
4154 
4155 	if (tail == CHECK_FULL_PAGE) {
4156 		full = true;
4157 		tail = local_read(&bpage->commit);
4158 	} else if (info->add_timestamp &
4159 		   (RB_ADD_STAMP_FORCE | RB_ADD_STAMP_ABSOLUTE)) {
4160 		/* Ignore events with absolute time stamps */
4161 		return;
4162 	}
4163 
4164 	/*
4165 	 * Do not check the first event (skip possible extends too).
4166 	 * Also do not check if previous events have not been committed.
4167 	 */
4168 	if (tail <= 8 || tail > local_read(&bpage->commit))
4169 		return;
4170 
4171 	/*
4172 	 * If this interrupted another event,
4173 	 */
4174 	if (atomic_inc_return(this_cpu_ptr(&checking)) != 1)
4175 		goto out;
4176 
4177 	ret = rb_read_data_buffer(bpage, tail, cpu_buffer->cpu, &ts, &delta);
4178 	if (ret < 0) {
4179 		if (delta < ts) {
4180 			buffer_warn_return("[CPU: %d]ABSOLUTE TIME WENT BACKWARDS: last ts: %lld absolute ts: %lld\n",
4181 					   cpu_buffer->cpu, ts, delta);
4182 			goto out;
4183 		}
4184 	}
4185 	if ((full && ts > info->ts) ||
4186 	    (!full && ts + info->delta != info->ts)) {
4187 		buffer_warn_return("[CPU: %d]TIME DOES NOT MATCH expected:%lld actual:%lld delta:%lld before:%lld after:%lld%s context:%s\n",
4188 				   cpu_buffer->cpu,
4189 				   ts + info->delta, info->ts, info->delta,
4190 				   info->before, info->after,
4191 				   full ? " (full)" : "", show_interrupt_level());
4192 	}
4193 out:
4194 	atomic_dec(this_cpu_ptr(&checking));
4195 }
4196 #else
check_buffer(struct ring_buffer_per_cpu * cpu_buffer,struct rb_event_info * info,unsigned long tail)4197 static inline void check_buffer(struct ring_buffer_per_cpu *cpu_buffer,
4198 			 struct rb_event_info *info,
4199 			 unsigned long tail)
4200 {
4201 }
4202 #endif /* CONFIG_RING_BUFFER_VALIDATE_TIME_DELTAS */
4203 
4204 static struct ring_buffer_event *
__rb_reserve_next(struct ring_buffer_per_cpu * cpu_buffer,struct rb_event_info * info)4205 __rb_reserve_next(struct ring_buffer_per_cpu *cpu_buffer,
4206 		  struct rb_event_info *info)
4207 {
4208 	struct ring_buffer_event *event;
4209 	struct buffer_page *tail_page;
4210 	unsigned long tail, write, w;
4211 
4212 	/* Don't let the compiler play games with cpu_buffer->tail_page */
4213 	tail_page = info->tail_page = READ_ONCE(cpu_buffer->tail_page);
4214 
4215  /*A*/	w = local_read(&tail_page->write) & RB_WRITE_MASK;
4216 	barrier();
4217 	rb_time_read(&cpu_buffer->before_stamp, &info->before);
4218 	rb_time_read(&cpu_buffer->write_stamp, &info->after);
4219 	barrier();
4220 	info->ts = rb_time_stamp(cpu_buffer->buffer);
4221 
4222 	if ((info->add_timestamp & RB_ADD_STAMP_ABSOLUTE)) {
4223 		info->delta = info->ts;
4224 	} else {
4225 		/*
4226 		 * If interrupting an event time update, we may need an
4227 		 * absolute timestamp.
4228 		 * Don't bother if this is the start of a new page (w == 0).
4229 		 */
4230 		if (!w) {
4231 			/* Use the sub-buffer timestamp */
4232 			info->delta = 0;
4233 		} else if (unlikely(info->before != info->after)) {
4234 			info->add_timestamp |= RB_ADD_STAMP_FORCE | RB_ADD_STAMP_EXTEND;
4235 			info->length += RB_LEN_TIME_EXTEND;
4236 		} else {
4237 			info->delta = info->ts - info->after;
4238 			if (unlikely(test_time_stamp(info->delta))) {
4239 				info->add_timestamp |= RB_ADD_STAMP_EXTEND;
4240 				info->length += RB_LEN_TIME_EXTEND;
4241 			}
4242 		}
4243 	}
4244 
4245  /*B*/	rb_time_set(&cpu_buffer->before_stamp, info->ts);
4246 
4247  /*C*/	write = local_add_return(info->length, &tail_page->write);
4248 
4249 	/* set write to only the index of the write */
4250 	write &= RB_WRITE_MASK;
4251 
4252 	tail = write - info->length;
4253 
4254 	/* See if we shot pass the end of this buffer page */
4255 	if (unlikely(write > cpu_buffer->buffer->subbuf_size)) {
4256 		check_buffer(cpu_buffer, info, CHECK_FULL_PAGE);
4257 		return rb_move_tail(cpu_buffer, tail, info);
4258 	}
4259 
4260 	if (likely(tail == w)) {
4261 		/* Nothing interrupted us between A and C */
4262  /*D*/		rb_time_set(&cpu_buffer->write_stamp, info->ts);
4263 		/*
4264 		 * If something came in between C and D, the write stamp
4265 		 * may now not be in sync. But that's fine as the before_stamp
4266 		 * will be different and then next event will just be forced
4267 		 * to use an absolute timestamp.
4268 		 */
4269 		if (likely(!(info->add_timestamp &
4270 			     (RB_ADD_STAMP_FORCE | RB_ADD_STAMP_ABSOLUTE))))
4271 			/* This did not interrupt any time update */
4272 			info->delta = info->ts - info->after;
4273 		else
4274 			/* Just use full timestamp for interrupting event */
4275 			info->delta = info->ts;
4276 		check_buffer(cpu_buffer, info, tail);
4277 	} else {
4278 		u64 ts;
4279 		/* SLOW PATH - Interrupted between A and C */
4280 
4281 		/* Save the old before_stamp */
4282 		rb_time_read(&cpu_buffer->before_stamp, &info->before);
4283 
4284 		/*
4285 		 * Read a new timestamp and update the before_stamp to make
4286 		 * the next event after this one force using an absolute
4287 		 * timestamp. This is in case an interrupt were to come in
4288 		 * between E and F.
4289 		 */
4290 		ts = rb_time_stamp(cpu_buffer->buffer);
4291 		rb_time_set(&cpu_buffer->before_stamp, ts);
4292 
4293 		barrier();
4294  /*E*/		rb_time_read(&cpu_buffer->write_stamp, &info->after);
4295 		barrier();
4296  /*F*/		if (write == (local_read(&tail_page->write) & RB_WRITE_MASK) &&
4297 		    info->after == info->before && info->after < ts) {
4298 			/*
4299 			 * Nothing came after this event between C and F, it is
4300 			 * safe to use info->after for the delta as it
4301 			 * matched info->before and is still valid.
4302 			 */
4303 			info->delta = ts - info->after;
4304 		} else {
4305 			/*
4306 			 * Interrupted between C and F:
4307 			 * Lost the previous events time stamp. Just set the
4308 			 * delta to zero, and this will be the same time as
4309 			 * the event this event interrupted. And the events that
4310 			 * came after this will still be correct (as they would
4311 			 * have built their delta on the previous event.
4312 			 */
4313 			info->delta = 0;
4314 		}
4315 		info->ts = ts;
4316 		info->add_timestamp &= ~RB_ADD_STAMP_FORCE;
4317 	}
4318 
4319 	/*
4320 	 * If this is the first commit on the page, then it has the same
4321 	 * timestamp as the page itself.
4322 	 */
4323 	if (unlikely(!tail && !(info->add_timestamp &
4324 				(RB_ADD_STAMP_FORCE | RB_ADD_STAMP_ABSOLUTE))))
4325 		info->delta = 0;
4326 
4327 	/* We reserved something on the buffer */
4328 
4329 	event = __rb_page_index(tail_page, tail);
4330 	rb_update_event(cpu_buffer, event, info);
4331 
4332 	local_inc(&tail_page->entries);
4333 
4334 	/*
4335 	 * If this is the first commit on the page, then update
4336 	 * its timestamp.
4337 	 */
4338 	if (unlikely(!tail))
4339 		tail_page->page->time_stamp = info->ts;
4340 
4341 	/* account for these added bytes */
4342 	local_add(info->length, &cpu_buffer->entries_bytes);
4343 
4344 	return event;
4345 }
4346 
4347 static __always_inline struct ring_buffer_event *
rb_reserve_next_event(struct trace_buffer * buffer,struct ring_buffer_per_cpu * cpu_buffer,unsigned long length)4348 rb_reserve_next_event(struct trace_buffer *buffer,
4349 		      struct ring_buffer_per_cpu *cpu_buffer,
4350 		      unsigned long length)
4351 {
4352 	struct ring_buffer_event *event;
4353 	struct rb_event_info info;
4354 	int nr_loops = 0;
4355 	int add_ts_default;
4356 
4357 	/* ring buffer does cmpxchg, make sure it is safe in NMI context */
4358 	if (!IS_ENABLED(CONFIG_ARCH_HAVE_NMI_SAFE_CMPXCHG) &&
4359 	    (unlikely(in_nmi()))) {
4360 		return NULL;
4361 	}
4362 
4363 	rb_start_commit(cpu_buffer);
4364 	/* The commit page can not change after this */
4365 
4366 #ifdef CONFIG_RING_BUFFER_ALLOW_SWAP
4367 	/*
4368 	 * Due to the ability to swap a cpu buffer from a buffer
4369 	 * it is possible it was swapped before we committed.
4370 	 * (committing stops a swap). We check for it here and
4371 	 * if it happened, we have to fail the write.
4372 	 */
4373 	barrier();
4374 	if (unlikely(READ_ONCE(cpu_buffer->buffer) != buffer)) {
4375 		local_dec(&cpu_buffer->committing);
4376 		local_dec(&cpu_buffer->commits);
4377 		return NULL;
4378 	}
4379 #endif
4380 
4381 	info.length = rb_calculate_event_length(length);
4382 
4383 	if (ring_buffer_time_stamp_abs(cpu_buffer->buffer)) {
4384 		add_ts_default = RB_ADD_STAMP_ABSOLUTE;
4385 		info.length += RB_LEN_TIME_EXTEND;
4386 		if (info.length > cpu_buffer->buffer->max_data_size)
4387 			goto out_fail;
4388 	} else {
4389 		add_ts_default = RB_ADD_STAMP_NONE;
4390 	}
4391 
4392  again:
4393 	info.add_timestamp = add_ts_default;
4394 	info.delta = 0;
4395 
4396 	/*
4397 	 * We allow for interrupts to reenter here and do a trace.
4398 	 * If one does, it will cause this original code to loop
4399 	 * back here. Even with heavy interrupts happening, this
4400 	 * should only happen a few times in a row. If this happens
4401 	 * 1000 times in a row, there must be either an interrupt
4402 	 * storm or we have something buggy.
4403 	 * Bail!
4404 	 */
4405 	if (RB_WARN_ON(cpu_buffer, ++nr_loops > 1000))
4406 		goto out_fail;
4407 
4408 	event = __rb_reserve_next(cpu_buffer, &info);
4409 
4410 	if (unlikely(PTR_ERR(event) == -EAGAIN)) {
4411 		if (info.add_timestamp & (RB_ADD_STAMP_FORCE | RB_ADD_STAMP_EXTEND))
4412 			info.length -= RB_LEN_TIME_EXTEND;
4413 		goto again;
4414 	}
4415 
4416 	if (likely(event))
4417 		return event;
4418  out_fail:
4419 	rb_end_commit(cpu_buffer);
4420 	return NULL;
4421 }
4422 
4423 /**
4424  * ring_buffer_lock_reserve - reserve a part of the buffer
4425  * @buffer: the ring buffer to reserve from
4426  * @length: the length of the data to reserve (excluding event header)
4427  *
4428  * Returns a reserved event on the ring buffer to copy directly to.
4429  * The user of this interface will need to get the body to write into
4430  * and can use the ring_buffer_event_data() interface.
4431  *
4432  * The length is the length of the data needed, not the event length
4433  * which also includes the event header.
4434  *
4435  * Must be paired with ring_buffer_unlock_commit, unless NULL is returned.
4436  * If NULL is returned, then nothing has been allocated or locked.
4437  */
4438 struct ring_buffer_event *
ring_buffer_lock_reserve(struct trace_buffer * buffer,unsigned long length)4439 ring_buffer_lock_reserve(struct trace_buffer *buffer, unsigned long length)
4440 {
4441 	struct ring_buffer_per_cpu *cpu_buffer;
4442 	struct ring_buffer_event *event;
4443 	int cpu;
4444 
4445 	/* If we are tracing schedule, we don't want to recurse */
4446 	preempt_disable_notrace();
4447 
4448 	if (unlikely(atomic_read(&buffer->record_disabled)))
4449 		goto out;
4450 
4451 	cpu = raw_smp_processor_id();
4452 
4453 	if (unlikely(!cpumask_test_cpu(cpu, buffer->cpumask)))
4454 		goto out;
4455 
4456 	cpu_buffer = buffer->buffers[cpu];
4457 
4458 	if (unlikely(atomic_read(&cpu_buffer->record_disabled)))
4459 		goto out;
4460 
4461 	if (unlikely(length > buffer->max_data_size))
4462 		goto out;
4463 
4464 	if (unlikely(trace_recursive_lock(cpu_buffer)))
4465 		goto out;
4466 
4467 	event = rb_reserve_next_event(buffer, cpu_buffer, length);
4468 	if (!event)
4469 		goto out_unlock;
4470 
4471 	return event;
4472 
4473  out_unlock:
4474 	trace_recursive_unlock(cpu_buffer);
4475  out:
4476 	preempt_enable_notrace();
4477 	return NULL;
4478 }
4479 EXPORT_SYMBOL_GPL(ring_buffer_lock_reserve);
4480 
4481 /*
4482  * Decrement the entries to the page that an event is on.
4483  * The event does not even need to exist, only the pointer
4484  * to the page it is on. This may only be called before the commit
4485  * takes place.
4486  */
4487 static inline void
rb_decrement_entry(struct ring_buffer_per_cpu * cpu_buffer,struct ring_buffer_event * event)4488 rb_decrement_entry(struct ring_buffer_per_cpu *cpu_buffer,
4489 		   struct ring_buffer_event *event)
4490 {
4491 	unsigned long addr = (unsigned long)event;
4492 	struct buffer_page *bpage = cpu_buffer->commit_page;
4493 	struct buffer_page *start;
4494 
4495 	addr &= ~((PAGE_SIZE << cpu_buffer->buffer->subbuf_order) - 1);
4496 
4497 	/* Do the likely case first */
4498 	if (likely(bpage->page == (void *)addr)) {
4499 		local_dec(&bpage->entries);
4500 		return;
4501 	}
4502 
4503 	/*
4504 	 * Because the commit page may be on the reader page we
4505 	 * start with the next page and check the end loop there.
4506 	 */
4507 	rb_inc_page(&bpage);
4508 	start = bpage;
4509 	do {
4510 		if (bpage->page == (void *)addr) {
4511 			local_dec(&bpage->entries);
4512 			return;
4513 		}
4514 		rb_inc_page(&bpage);
4515 	} while (bpage != start);
4516 
4517 	/* commit not part of this buffer?? */
4518 	RB_WARN_ON(cpu_buffer, 1);
4519 }
4520 
4521 /**
4522  * ring_buffer_discard_commit - discard an event that has not been committed
4523  * @buffer: the ring buffer
4524  * @event: non committed event to discard
4525  *
4526  * Sometimes an event that is in the ring buffer needs to be ignored.
4527  * This function lets the user discard an event in the ring buffer
4528  * and then that event will not be read later.
4529  *
4530  * This function only works if it is called before the item has been
4531  * committed. It will try to free the event from the ring buffer
4532  * if another event has not been added behind it.
4533  *
4534  * If another event has been added behind it, it will set the event
4535  * up as discarded, and perform the commit.
4536  *
4537  * If this function is called, do not call ring_buffer_unlock_commit on
4538  * the event.
4539  */
ring_buffer_discard_commit(struct trace_buffer * buffer,struct ring_buffer_event * event)4540 void ring_buffer_discard_commit(struct trace_buffer *buffer,
4541 				struct ring_buffer_event *event)
4542 {
4543 	struct ring_buffer_per_cpu *cpu_buffer;
4544 	int cpu;
4545 
4546 	/* The event is discarded regardless */
4547 	rb_event_discard(event);
4548 
4549 	cpu = smp_processor_id();
4550 	cpu_buffer = buffer->buffers[cpu];
4551 
4552 	/*
4553 	 * This must only be called if the event has not been
4554 	 * committed yet. Thus we can assume that preemption
4555 	 * is still disabled.
4556 	 */
4557 	RB_WARN_ON(buffer, !local_read(&cpu_buffer->committing));
4558 
4559 	rb_decrement_entry(cpu_buffer, event);
4560 	if (rb_try_to_discard(cpu_buffer, event))
4561 		goto out;
4562 
4563  out:
4564 	rb_end_commit(cpu_buffer);
4565 
4566 	trace_recursive_unlock(cpu_buffer);
4567 
4568 	preempt_enable_notrace();
4569 
4570 }
4571 EXPORT_SYMBOL_GPL(ring_buffer_discard_commit);
4572 
4573 /**
4574  * ring_buffer_write - write data to the buffer without reserving
4575  * @buffer: The ring buffer to write to.
4576  * @length: The length of the data being written (excluding the event header)
4577  * @data: The data to write to the buffer.
4578  *
4579  * This is like ring_buffer_lock_reserve and ring_buffer_unlock_commit as
4580  * one function. If you already have the data to write to the buffer, it
4581  * may be easier to simply call this function.
4582  *
4583  * Note, like ring_buffer_lock_reserve, the length is the length of the data
4584  * and not the length of the event which would hold the header.
4585  */
ring_buffer_write(struct trace_buffer * buffer,unsigned long length,void * data)4586 int ring_buffer_write(struct trace_buffer *buffer,
4587 		      unsigned long length,
4588 		      void *data)
4589 {
4590 	struct ring_buffer_per_cpu *cpu_buffer;
4591 	struct ring_buffer_event *event;
4592 	void *body;
4593 	int ret = -EBUSY;
4594 	int cpu;
4595 
4596 	preempt_disable_notrace();
4597 
4598 	if (atomic_read(&buffer->record_disabled))
4599 		goto out;
4600 
4601 	cpu = raw_smp_processor_id();
4602 
4603 	if (!cpumask_test_cpu(cpu, buffer->cpumask))
4604 		goto out;
4605 
4606 	cpu_buffer = buffer->buffers[cpu];
4607 
4608 	if (atomic_read(&cpu_buffer->record_disabled))
4609 		goto out;
4610 
4611 	if (length > buffer->max_data_size)
4612 		goto out;
4613 
4614 	if (unlikely(trace_recursive_lock(cpu_buffer)))
4615 		goto out;
4616 
4617 	event = rb_reserve_next_event(buffer, cpu_buffer, length);
4618 	if (!event)
4619 		goto out_unlock;
4620 
4621 	body = rb_event_data(event);
4622 
4623 	memcpy(body, data, length);
4624 
4625 	rb_commit(cpu_buffer);
4626 
4627 	rb_wakeups(buffer, cpu_buffer);
4628 
4629 	ret = 0;
4630 
4631  out_unlock:
4632 	trace_recursive_unlock(cpu_buffer);
4633 
4634  out:
4635 	preempt_enable_notrace();
4636 
4637 	return ret;
4638 }
4639 EXPORT_SYMBOL_GPL(ring_buffer_write);
4640 
rb_per_cpu_empty(struct ring_buffer_per_cpu * cpu_buffer)4641 static bool rb_per_cpu_empty(struct ring_buffer_per_cpu *cpu_buffer)
4642 {
4643 	struct buffer_page *reader = cpu_buffer->reader_page;
4644 	struct buffer_page *head = rb_set_head_page(cpu_buffer);
4645 	struct buffer_page *commit = cpu_buffer->commit_page;
4646 
4647 	/* In case of error, head will be NULL */
4648 	if (unlikely(!head))
4649 		return true;
4650 
4651 	/* Reader should exhaust content in reader page */
4652 	if (reader->read != rb_page_size(reader))
4653 		return false;
4654 
4655 	/*
4656 	 * If writers are committing on the reader page, knowing all
4657 	 * committed content has been read, the ring buffer is empty.
4658 	 */
4659 	if (commit == reader)
4660 		return true;
4661 
4662 	/*
4663 	 * If writers are committing on a page other than reader page
4664 	 * and head page, there should always be content to read.
4665 	 */
4666 	if (commit != head)
4667 		return false;
4668 
4669 	/*
4670 	 * Writers are committing on the head page, we just need
4671 	 * to care about there're committed data, and the reader will
4672 	 * swap reader page with head page when it is to read data.
4673 	 */
4674 	return rb_page_commit(commit) == 0;
4675 }
4676 
4677 /**
4678  * ring_buffer_record_disable - stop all writes into the buffer
4679  * @buffer: The ring buffer to stop writes to.
4680  *
4681  * This prevents all writes to the buffer. Any attempt to write
4682  * to the buffer after this will fail and return NULL.
4683  *
4684  * The caller should call synchronize_rcu() after this.
4685  */
ring_buffer_record_disable(struct trace_buffer * buffer)4686 void ring_buffer_record_disable(struct trace_buffer *buffer)
4687 {
4688 	atomic_inc(&buffer->record_disabled);
4689 }
4690 EXPORT_SYMBOL_GPL(ring_buffer_record_disable);
4691 
4692 /**
4693  * ring_buffer_record_enable - enable writes to the buffer
4694  * @buffer: The ring buffer to enable writes
4695  *
4696  * Note, multiple disables will need the same number of enables
4697  * to truly enable the writing (much like preempt_disable).
4698  */
ring_buffer_record_enable(struct trace_buffer * buffer)4699 void ring_buffer_record_enable(struct trace_buffer *buffer)
4700 {
4701 	atomic_dec(&buffer->record_disabled);
4702 }
4703 EXPORT_SYMBOL_GPL(ring_buffer_record_enable);
4704 
4705 /**
4706  * ring_buffer_record_off - stop all writes into the buffer
4707  * @buffer: The ring buffer to stop writes to.
4708  *
4709  * This prevents all writes to the buffer. Any attempt to write
4710  * to the buffer after this will fail and return NULL.
4711  *
4712  * This is different than ring_buffer_record_disable() as
4713  * it works like an on/off switch, where as the disable() version
4714  * must be paired with a enable().
4715  */
ring_buffer_record_off(struct trace_buffer * buffer)4716 void ring_buffer_record_off(struct trace_buffer *buffer)
4717 {
4718 	unsigned int rd;
4719 	unsigned int new_rd;
4720 
4721 	rd = atomic_read(&buffer->record_disabled);
4722 	do {
4723 		new_rd = rd | RB_BUFFER_OFF;
4724 	} while (!atomic_try_cmpxchg(&buffer->record_disabled, &rd, new_rd));
4725 }
4726 EXPORT_SYMBOL_GPL(ring_buffer_record_off);
4727 
4728 /**
4729  * ring_buffer_record_on - restart writes into the buffer
4730  * @buffer: The ring buffer to start writes to.
4731  *
4732  * This enables all writes to the buffer that was disabled by
4733  * ring_buffer_record_off().
4734  *
4735  * This is different than ring_buffer_record_enable() as
4736  * it works like an on/off switch, where as the enable() version
4737  * must be paired with a disable().
4738  */
ring_buffer_record_on(struct trace_buffer * buffer)4739 void ring_buffer_record_on(struct trace_buffer *buffer)
4740 {
4741 	unsigned int rd;
4742 	unsigned int new_rd;
4743 
4744 	rd = atomic_read(&buffer->record_disabled);
4745 	do {
4746 		new_rd = rd & ~RB_BUFFER_OFF;
4747 	} while (!atomic_try_cmpxchg(&buffer->record_disabled, &rd, new_rd));
4748 }
4749 EXPORT_SYMBOL_GPL(ring_buffer_record_on);
4750 
4751 /**
4752  * ring_buffer_record_is_on - return true if the ring buffer can write
4753  * @buffer: The ring buffer to see if write is enabled
4754  *
4755  * Returns true if the ring buffer is in a state that it accepts writes.
4756  */
ring_buffer_record_is_on(struct trace_buffer * buffer)4757 bool ring_buffer_record_is_on(struct trace_buffer *buffer)
4758 {
4759 	return !atomic_read(&buffer->record_disabled);
4760 }
4761 
4762 /**
4763  * ring_buffer_record_is_set_on - return true if the ring buffer is set writable
4764  * @buffer: The ring buffer to see if write is set enabled
4765  *
4766  * Returns true if the ring buffer is set writable by ring_buffer_record_on().
4767  * Note that this does NOT mean it is in a writable state.
4768  *
4769  * It may return true when the ring buffer has been disabled by
4770  * ring_buffer_record_disable(), as that is a temporary disabling of
4771  * the ring buffer.
4772  */
ring_buffer_record_is_set_on(struct trace_buffer * buffer)4773 bool ring_buffer_record_is_set_on(struct trace_buffer *buffer)
4774 {
4775 	return !(atomic_read(&buffer->record_disabled) & RB_BUFFER_OFF);
4776 }
4777 
4778 /**
4779  * ring_buffer_record_disable_cpu - stop all writes into the cpu_buffer
4780  * @buffer: The ring buffer to stop writes to.
4781  * @cpu: The CPU buffer to stop
4782  *
4783  * This prevents all writes to the buffer. Any attempt to write
4784  * to the buffer after this will fail and return NULL.
4785  *
4786  * The caller should call synchronize_rcu() after this.
4787  */
ring_buffer_record_disable_cpu(struct trace_buffer * buffer,int cpu)4788 void ring_buffer_record_disable_cpu(struct trace_buffer *buffer, int cpu)
4789 {
4790 	struct ring_buffer_per_cpu *cpu_buffer;
4791 
4792 	if (!cpumask_test_cpu(cpu, buffer->cpumask))
4793 		return;
4794 
4795 	cpu_buffer = buffer->buffers[cpu];
4796 	atomic_inc(&cpu_buffer->record_disabled);
4797 }
4798 EXPORT_SYMBOL_GPL(ring_buffer_record_disable_cpu);
4799 
4800 /**
4801  * ring_buffer_record_enable_cpu - enable writes to the buffer
4802  * @buffer: The ring buffer to enable writes
4803  * @cpu: The CPU to enable.
4804  *
4805  * Note, multiple disables will need the same number of enables
4806  * to truly enable the writing (much like preempt_disable).
4807  */
ring_buffer_record_enable_cpu(struct trace_buffer * buffer,int cpu)4808 void ring_buffer_record_enable_cpu(struct trace_buffer *buffer, int cpu)
4809 {
4810 	struct ring_buffer_per_cpu *cpu_buffer;
4811 
4812 	if (!cpumask_test_cpu(cpu, buffer->cpumask))
4813 		return;
4814 
4815 	cpu_buffer = buffer->buffers[cpu];
4816 	atomic_dec(&cpu_buffer->record_disabled);
4817 }
4818 EXPORT_SYMBOL_GPL(ring_buffer_record_enable_cpu);
4819 
4820 /*
4821  * The total entries in the ring buffer is the running counter
4822  * of entries entered into the ring buffer, minus the sum of
4823  * the entries read from the ring buffer and the number of
4824  * entries that were overwritten.
4825  */
4826 static inline unsigned long
rb_num_of_entries(struct ring_buffer_per_cpu * cpu_buffer)4827 rb_num_of_entries(struct ring_buffer_per_cpu *cpu_buffer)
4828 {
4829 	return local_read(&cpu_buffer->entries) -
4830 		(local_read(&cpu_buffer->overrun) + cpu_buffer->read);
4831 }
4832 
4833 /**
4834  * ring_buffer_oldest_event_ts - get the oldest event timestamp from the buffer
4835  * @buffer: The ring buffer
4836  * @cpu: The per CPU buffer to read from.
4837  */
ring_buffer_oldest_event_ts(struct trace_buffer * buffer,int cpu)4838 u64 ring_buffer_oldest_event_ts(struct trace_buffer *buffer, int cpu)
4839 {
4840 	unsigned long flags;
4841 	struct ring_buffer_per_cpu *cpu_buffer;
4842 	struct buffer_page *bpage;
4843 	u64 ret = 0;
4844 
4845 	if (!cpumask_test_cpu(cpu, buffer->cpumask))
4846 		return 0;
4847 
4848 	cpu_buffer = buffer->buffers[cpu];
4849 	raw_spin_lock_irqsave(&cpu_buffer->reader_lock, flags);
4850 	/*
4851 	 * if the tail is on reader_page, oldest time stamp is on the reader
4852 	 * page
4853 	 */
4854 	if (cpu_buffer->tail_page == cpu_buffer->reader_page)
4855 		bpage = cpu_buffer->reader_page;
4856 	else
4857 		bpage = rb_set_head_page(cpu_buffer);
4858 	if (bpage)
4859 		ret = bpage->page->time_stamp;
4860 	raw_spin_unlock_irqrestore(&cpu_buffer->reader_lock, flags);
4861 
4862 	return ret;
4863 }
4864 EXPORT_SYMBOL_GPL(ring_buffer_oldest_event_ts);
4865 
4866 /**
4867  * ring_buffer_bytes_cpu - get the number of bytes unconsumed in a cpu buffer
4868  * @buffer: The ring buffer
4869  * @cpu: The per CPU buffer to read from.
4870  */
ring_buffer_bytes_cpu(struct trace_buffer * buffer,int cpu)4871 unsigned long ring_buffer_bytes_cpu(struct trace_buffer *buffer, int cpu)
4872 {
4873 	struct ring_buffer_per_cpu *cpu_buffer;
4874 	unsigned long ret;
4875 
4876 	if (!cpumask_test_cpu(cpu, buffer->cpumask))
4877 		return 0;
4878 
4879 	cpu_buffer = buffer->buffers[cpu];
4880 	ret = local_read(&cpu_buffer->entries_bytes) - cpu_buffer->read_bytes;
4881 
4882 	return ret;
4883 }
4884 EXPORT_SYMBOL_GPL(ring_buffer_bytes_cpu);
4885 
4886 /**
4887  * ring_buffer_entries_cpu - get the number of entries in a cpu buffer
4888  * @buffer: The ring buffer
4889  * @cpu: The per CPU buffer to get the entries from.
4890  */
ring_buffer_entries_cpu(struct trace_buffer * buffer,int cpu)4891 unsigned long ring_buffer_entries_cpu(struct trace_buffer *buffer, int cpu)
4892 {
4893 	struct ring_buffer_per_cpu *cpu_buffer;
4894 
4895 	if (!cpumask_test_cpu(cpu, buffer->cpumask))
4896 		return 0;
4897 
4898 	cpu_buffer = buffer->buffers[cpu];
4899 
4900 	return rb_num_of_entries(cpu_buffer);
4901 }
4902 EXPORT_SYMBOL_GPL(ring_buffer_entries_cpu);
4903 
4904 /**
4905  * ring_buffer_overrun_cpu - get the number of overruns caused by the ring
4906  * buffer wrapping around (only if RB_FL_OVERWRITE is on).
4907  * @buffer: The ring buffer
4908  * @cpu: The per CPU buffer to get the number of overruns from
4909  */
ring_buffer_overrun_cpu(struct trace_buffer * buffer,int cpu)4910 unsigned long ring_buffer_overrun_cpu(struct trace_buffer *buffer, int cpu)
4911 {
4912 	struct ring_buffer_per_cpu *cpu_buffer;
4913 	unsigned long ret;
4914 
4915 	if (!cpumask_test_cpu(cpu, buffer->cpumask))
4916 		return 0;
4917 
4918 	cpu_buffer = buffer->buffers[cpu];
4919 	ret = local_read(&cpu_buffer->overrun);
4920 
4921 	return ret;
4922 }
4923 EXPORT_SYMBOL_GPL(ring_buffer_overrun_cpu);
4924 
4925 /**
4926  * ring_buffer_commit_overrun_cpu - get the number of overruns caused by
4927  * commits failing due to the buffer wrapping around while there are uncommitted
4928  * events, such as during an interrupt storm.
4929  * @buffer: The ring buffer
4930  * @cpu: The per CPU buffer to get the number of overruns from
4931  */
4932 unsigned long
ring_buffer_commit_overrun_cpu(struct trace_buffer * buffer,int cpu)4933 ring_buffer_commit_overrun_cpu(struct trace_buffer *buffer, int cpu)
4934 {
4935 	struct ring_buffer_per_cpu *cpu_buffer;
4936 	unsigned long ret;
4937 
4938 	if (!cpumask_test_cpu(cpu, buffer->cpumask))
4939 		return 0;
4940 
4941 	cpu_buffer = buffer->buffers[cpu];
4942 	ret = local_read(&cpu_buffer->commit_overrun);
4943 
4944 	return ret;
4945 }
4946 EXPORT_SYMBOL_GPL(ring_buffer_commit_overrun_cpu);
4947 
4948 /**
4949  * ring_buffer_dropped_events_cpu - get the number of dropped events caused by
4950  * the ring buffer filling up (only if RB_FL_OVERWRITE is off).
4951  * @buffer: The ring buffer
4952  * @cpu: The per CPU buffer to get the number of overruns from
4953  */
4954 unsigned long
ring_buffer_dropped_events_cpu(struct trace_buffer * buffer,int cpu)4955 ring_buffer_dropped_events_cpu(struct trace_buffer *buffer, int cpu)
4956 {
4957 	struct ring_buffer_per_cpu *cpu_buffer;
4958 	unsigned long ret;
4959 
4960 	if (!cpumask_test_cpu(cpu, buffer->cpumask))
4961 		return 0;
4962 
4963 	cpu_buffer = buffer->buffers[cpu];
4964 	ret = local_read(&cpu_buffer->dropped_events);
4965 
4966 	return ret;
4967 }
4968 EXPORT_SYMBOL_GPL(ring_buffer_dropped_events_cpu);
4969 
4970 /**
4971  * ring_buffer_read_events_cpu - get the number of events successfully read
4972  * @buffer: The ring buffer
4973  * @cpu: The per CPU buffer to get the number of events read
4974  */
4975 unsigned long
ring_buffer_read_events_cpu(struct trace_buffer * buffer,int cpu)4976 ring_buffer_read_events_cpu(struct trace_buffer *buffer, int cpu)
4977 {
4978 	struct ring_buffer_per_cpu *cpu_buffer;
4979 
4980 	if (!cpumask_test_cpu(cpu, buffer->cpumask))
4981 		return 0;
4982 
4983 	cpu_buffer = buffer->buffers[cpu];
4984 	return cpu_buffer->read;
4985 }
4986 EXPORT_SYMBOL_GPL(ring_buffer_read_events_cpu);
4987 
4988 /**
4989  * ring_buffer_entries - get the number of entries in a buffer
4990  * @buffer: The ring buffer
4991  *
4992  * Returns the total number of entries in the ring buffer
4993  * (all CPU entries)
4994  */
ring_buffer_entries(struct trace_buffer * buffer)4995 unsigned long ring_buffer_entries(struct trace_buffer *buffer)
4996 {
4997 	struct ring_buffer_per_cpu *cpu_buffer;
4998 	unsigned long entries = 0;
4999 	int cpu;
5000 
5001 	/* if you care about this being correct, lock the buffer */
5002 	for_each_buffer_cpu(buffer, cpu) {
5003 		cpu_buffer = buffer->buffers[cpu];
5004 		entries += rb_num_of_entries(cpu_buffer);
5005 	}
5006 
5007 	return entries;
5008 }
5009 EXPORT_SYMBOL_GPL(ring_buffer_entries);
5010 
5011 /**
5012  * ring_buffer_overruns - get the number of overruns in buffer
5013  * @buffer: The ring buffer
5014  *
5015  * Returns the total number of overruns in the ring buffer
5016  * (all CPU entries)
5017  */
ring_buffer_overruns(struct trace_buffer * buffer)5018 unsigned long ring_buffer_overruns(struct trace_buffer *buffer)
5019 {
5020 	struct ring_buffer_per_cpu *cpu_buffer;
5021 	unsigned long overruns = 0;
5022 	int cpu;
5023 
5024 	/* if you care about this being correct, lock the buffer */
5025 	for_each_buffer_cpu(buffer, cpu) {
5026 		cpu_buffer = buffer->buffers[cpu];
5027 		overruns += local_read(&cpu_buffer->overrun);
5028 	}
5029 
5030 	return overruns;
5031 }
5032 EXPORT_SYMBOL_GPL(ring_buffer_overruns);
5033 
rb_iter_reset(struct ring_buffer_iter * iter)5034 static void rb_iter_reset(struct ring_buffer_iter *iter)
5035 {
5036 	struct ring_buffer_per_cpu *cpu_buffer = iter->cpu_buffer;
5037 
5038 	/* Iterator usage is expected to have record disabled */
5039 	iter->head_page = cpu_buffer->reader_page;
5040 	iter->head = cpu_buffer->reader_page->read;
5041 	iter->next_event = iter->head;
5042 
5043 	iter->cache_reader_page = iter->head_page;
5044 	iter->cache_read = cpu_buffer->read;
5045 	iter->cache_pages_removed = cpu_buffer->pages_removed;
5046 
5047 	if (iter->head) {
5048 		iter->read_stamp = cpu_buffer->read_stamp;
5049 		iter->page_stamp = cpu_buffer->reader_page->page->time_stamp;
5050 	} else {
5051 		iter->read_stamp = iter->head_page->page->time_stamp;
5052 		iter->page_stamp = iter->read_stamp;
5053 	}
5054 }
5055 
5056 /**
5057  * ring_buffer_iter_reset - reset an iterator
5058  * @iter: The iterator to reset
5059  *
5060  * Resets the iterator, so that it will start from the beginning
5061  * again.
5062  */
ring_buffer_iter_reset(struct ring_buffer_iter * iter)5063 void ring_buffer_iter_reset(struct ring_buffer_iter *iter)
5064 {
5065 	struct ring_buffer_per_cpu *cpu_buffer;
5066 	unsigned long flags;
5067 
5068 	if (!iter)
5069 		return;
5070 
5071 	cpu_buffer = iter->cpu_buffer;
5072 
5073 	raw_spin_lock_irqsave(&cpu_buffer->reader_lock, flags);
5074 	rb_iter_reset(iter);
5075 	raw_spin_unlock_irqrestore(&cpu_buffer->reader_lock, flags);
5076 }
5077 EXPORT_SYMBOL_GPL(ring_buffer_iter_reset);
5078 
5079 /**
5080  * ring_buffer_iter_empty - check if an iterator has no more to read
5081  * @iter: The iterator to check
5082  */
ring_buffer_iter_empty(struct ring_buffer_iter * iter)5083 int ring_buffer_iter_empty(struct ring_buffer_iter *iter)
5084 {
5085 	struct ring_buffer_per_cpu *cpu_buffer;
5086 	struct buffer_page *reader;
5087 	struct buffer_page *head_page;
5088 	struct buffer_page *commit_page;
5089 	struct buffer_page *curr_commit_page;
5090 	unsigned commit;
5091 	u64 curr_commit_ts;
5092 	u64 commit_ts;
5093 
5094 	cpu_buffer = iter->cpu_buffer;
5095 	reader = cpu_buffer->reader_page;
5096 	head_page = cpu_buffer->head_page;
5097 	commit_page = READ_ONCE(cpu_buffer->commit_page);
5098 	commit_ts = commit_page->page->time_stamp;
5099 
5100 	/*
5101 	 * When the writer goes across pages, it issues a cmpxchg which
5102 	 * is a mb(), which will synchronize with the rmb here.
5103 	 * (see rb_tail_page_update())
5104 	 */
5105 	smp_rmb();
5106 	commit = rb_page_commit(commit_page);
5107 	/* We want to make sure that the commit page doesn't change */
5108 	smp_rmb();
5109 
5110 	/* Make sure commit page didn't change */
5111 	curr_commit_page = READ_ONCE(cpu_buffer->commit_page);
5112 	curr_commit_ts = READ_ONCE(curr_commit_page->page->time_stamp);
5113 
5114 	/* If the commit page changed, then there's more data */
5115 	if (curr_commit_page != commit_page ||
5116 	    curr_commit_ts != commit_ts)
5117 		return 0;
5118 
5119 	/* Still racy, as it may return a false positive, but that's OK */
5120 	return ((iter->head_page == commit_page && iter->head >= commit) ||
5121 		(iter->head_page == reader && commit_page == head_page &&
5122 		 head_page->read == commit &&
5123 		 iter->head == rb_page_size(cpu_buffer->reader_page)));
5124 }
5125 EXPORT_SYMBOL_GPL(ring_buffer_iter_empty);
5126 
5127 static void
rb_update_read_stamp(struct ring_buffer_per_cpu * cpu_buffer,struct ring_buffer_event * event)5128 rb_update_read_stamp(struct ring_buffer_per_cpu *cpu_buffer,
5129 		     struct ring_buffer_event *event)
5130 {
5131 	u64 delta;
5132 
5133 	switch (event->type_len) {
5134 	case RINGBUF_TYPE_PADDING:
5135 		return;
5136 
5137 	case RINGBUF_TYPE_TIME_EXTEND:
5138 		delta = rb_event_time_stamp(event);
5139 		cpu_buffer->read_stamp += delta;
5140 		return;
5141 
5142 	case RINGBUF_TYPE_TIME_STAMP:
5143 		delta = rb_event_time_stamp(event);
5144 		delta = rb_fix_abs_ts(delta, cpu_buffer->read_stamp);
5145 		cpu_buffer->read_stamp = delta;
5146 		return;
5147 
5148 	case RINGBUF_TYPE_DATA:
5149 		cpu_buffer->read_stamp += event->time_delta;
5150 		return;
5151 
5152 	default:
5153 		RB_WARN_ON(cpu_buffer, 1);
5154 	}
5155 }
5156 
5157 static void
rb_update_iter_read_stamp(struct ring_buffer_iter * iter,struct ring_buffer_event * event)5158 rb_update_iter_read_stamp(struct ring_buffer_iter *iter,
5159 			  struct ring_buffer_event *event)
5160 {
5161 	u64 delta;
5162 
5163 	switch (event->type_len) {
5164 	case RINGBUF_TYPE_PADDING:
5165 		return;
5166 
5167 	case RINGBUF_TYPE_TIME_EXTEND:
5168 		delta = rb_event_time_stamp(event);
5169 		iter->read_stamp += delta;
5170 		return;
5171 
5172 	case RINGBUF_TYPE_TIME_STAMP:
5173 		delta = rb_event_time_stamp(event);
5174 		delta = rb_fix_abs_ts(delta, iter->read_stamp);
5175 		iter->read_stamp = delta;
5176 		return;
5177 
5178 	case RINGBUF_TYPE_DATA:
5179 		iter->read_stamp += event->time_delta;
5180 		return;
5181 
5182 	default:
5183 		RB_WARN_ON(iter->cpu_buffer, 1);
5184 	}
5185 }
5186 
5187 static struct buffer_page *
rb_get_reader_page(struct ring_buffer_per_cpu * cpu_buffer)5188 rb_get_reader_page(struct ring_buffer_per_cpu *cpu_buffer)
5189 {
5190 	struct buffer_page *reader = NULL;
5191 	unsigned long bsize = READ_ONCE(cpu_buffer->buffer->subbuf_size);
5192 	unsigned long overwrite;
5193 	unsigned long flags;
5194 	int nr_loops = 0;
5195 	bool ret;
5196 
5197 	local_irq_save(flags);
5198 	arch_spin_lock(&cpu_buffer->lock);
5199 
5200  again:
5201 	/*
5202 	 * This should normally only loop twice. But because the
5203 	 * start of the reader inserts an empty page, it causes
5204 	 * a case where we will loop three times. There should be no
5205 	 * reason to loop four times (that I know of).
5206 	 */
5207 	if (RB_WARN_ON(cpu_buffer, ++nr_loops > 3)) {
5208 		reader = NULL;
5209 		goto out;
5210 	}
5211 
5212 	reader = cpu_buffer->reader_page;
5213 
5214 	/* If there's more to read, return this page */
5215 	if (cpu_buffer->reader_page->read < rb_page_size(reader))
5216 		goto out;
5217 
5218 	/* Never should we have an index greater than the size */
5219 	if (RB_WARN_ON(cpu_buffer,
5220 		       cpu_buffer->reader_page->read > rb_page_size(reader)))
5221 		goto out;
5222 
5223 	/* check if we caught up to the tail */
5224 	reader = NULL;
5225 	if (cpu_buffer->commit_page == cpu_buffer->reader_page)
5226 		goto out;
5227 
5228 	/* Don't bother swapping if the ring buffer is empty */
5229 	if (rb_num_of_entries(cpu_buffer) == 0)
5230 		goto out;
5231 
5232 	/*
5233 	 * Reset the reader page to size zero.
5234 	 */
5235 	local_set(&cpu_buffer->reader_page->write, 0);
5236 	local_set(&cpu_buffer->reader_page->entries, 0);
5237 	local_set(&cpu_buffer->reader_page->page->commit, 0);
5238 	cpu_buffer->reader_page->real_end = 0;
5239 
5240  spin:
5241 	/*
5242 	 * Splice the empty reader page into the list around the head.
5243 	 */
5244 	reader = rb_set_head_page(cpu_buffer);
5245 	if (!reader)
5246 		goto out;
5247 	cpu_buffer->reader_page->list.next = rb_list_head(reader->list.next);
5248 	cpu_buffer->reader_page->list.prev = reader->list.prev;
5249 
5250 	/*
5251 	 * cpu_buffer->pages just needs to point to the buffer, it
5252 	 *  has no specific buffer page to point to. Lets move it out
5253 	 *  of our way so we don't accidentally swap it.
5254 	 */
5255 	cpu_buffer->pages = reader->list.prev;
5256 
5257 	/* The reader page will be pointing to the new head */
5258 	rb_set_list_to_head(&cpu_buffer->reader_page->list);
5259 
5260 	/*
5261 	 * We want to make sure we read the overruns after we set up our
5262 	 * pointers to the next object. The writer side does a
5263 	 * cmpxchg to cross pages which acts as the mb on the writer
5264 	 * side. Note, the reader will constantly fail the swap
5265 	 * while the writer is updating the pointers, so this
5266 	 * guarantees that the overwrite recorded here is the one we
5267 	 * want to compare with the last_overrun.
5268 	 */
5269 	smp_mb();
5270 	overwrite = local_read(&(cpu_buffer->overrun));
5271 
5272 	/*
5273 	 * Here's the tricky part.
5274 	 *
5275 	 * We need to move the pointer past the header page.
5276 	 * But we can only do that if a writer is not currently
5277 	 * moving it. The page before the header page has the
5278 	 * flag bit '1' set if it is pointing to the page we want.
5279 	 * but if the writer is in the process of moving it
5280 	 * than it will be '2' or already moved '0'.
5281 	 */
5282 
5283 	ret = rb_head_page_replace(reader, cpu_buffer->reader_page);
5284 
5285 	/*
5286 	 * If we did not convert it, then we must try again.
5287 	 */
5288 	if (!ret)
5289 		goto spin;
5290 
5291 	if (cpu_buffer->ring_meta)
5292 		rb_update_meta_reader(cpu_buffer, reader);
5293 
5294 	/*
5295 	 * Yay! We succeeded in replacing the page.
5296 	 *
5297 	 * Now make the new head point back to the reader page.
5298 	 */
5299 	rb_list_head(reader->list.next)->prev = &cpu_buffer->reader_page->list;
5300 	rb_inc_page(&cpu_buffer->head_page);
5301 
5302 	local_inc(&cpu_buffer->pages_read);
5303 
5304 	/* Finally update the reader page to the new head */
5305 	cpu_buffer->reader_page = reader;
5306 	cpu_buffer->reader_page->read = 0;
5307 
5308 	if (overwrite != cpu_buffer->last_overrun) {
5309 		cpu_buffer->lost_events = overwrite - cpu_buffer->last_overrun;
5310 		cpu_buffer->last_overrun = overwrite;
5311 	}
5312 
5313 	goto again;
5314 
5315  out:
5316 	/* Update the read_stamp on the first event */
5317 	if (reader && reader->read == 0)
5318 		cpu_buffer->read_stamp = reader->page->time_stamp;
5319 
5320 	arch_spin_unlock(&cpu_buffer->lock);
5321 	local_irq_restore(flags);
5322 
5323 	/*
5324 	 * The writer has preempt disable, wait for it. But not forever
5325 	 * Although, 1 second is pretty much "forever"
5326 	 */
5327 #define USECS_WAIT	1000000
5328         for (nr_loops = 0; nr_loops < USECS_WAIT; nr_loops++) {
5329 		/* If the write is past the end of page, a writer is still updating it */
5330 		if (likely(!reader || rb_page_write(reader) <= bsize))
5331 			break;
5332 
5333 		udelay(1);
5334 
5335 		/* Get the latest version of the reader write value */
5336 		smp_rmb();
5337 	}
5338 
5339 	/* The writer is not moving forward? Something is wrong */
5340 	if (RB_WARN_ON(cpu_buffer, nr_loops == USECS_WAIT))
5341 		reader = NULL;
5342 
5343 	/*
5344 	 * Make sure we see any padding after the write update
5345 	 * (see rb_reset_tail()).
5346 	 *
5347 	 * In addition, a writer may be writing on the reader page
5348 	 * if the page has not been fully filled, so the read barrier
5349 	 * is also needed to make sure we see the content of what is
5350 	 * committed by the writer (see rb_set_commit_to_write()).
5351 	 */
5352 	smp_rmb();
5353 
5354 
5355 	return reader;
5356 }
5357 
rb_advance_reader(struct ring_buffer_per_cpu * cpu_buffer)5358 static void rb_advance_reader(struct ring_buffer_per_cpu *cpu_buffer)
5359 {
5360 	struct ring_buffer_event *event;
5361 	struct buffer_page *reader;
5362 	unsigned length;
5363 
5364 	reader = rb_get_reader_page(cpu_buffer);
5365 
5366 	/* This function should not be called when buffer is empty */
5367 	if (RB_WARN_ON(cpu_buffer, !reader))
5368 		return;
5369 
5370 	event = rb_reader_event(cpu_buffer);
5371 
5372 	if (event->type_len <= RINGBUF_TYPE_DATA_TYPE_LEN_MAX)
5373 		cpu_buffer->read++;
5374 
5375 	rb_update_read_stamp(cpu_buffer, event);
5376 
5377 	length = rb_event_length(event);
5378 	cpu_buffer->reader_page->read += length;
5379 	cpu_buffer->read_bytes += length;
5380 }
5381 
rb_advance_iter(struct ring_buffer_iter * iter)5382 static void rb_advance_iter(struct ring_buffer_iter *iter)
5383 {
5384 	struct ring_buffer_per_cpu *cpu_buffer;
5385 
5386 	cpu_buffer = iter->cpu_buffer;
5387 
5388 	/* If head == next_event then we need to jump to the next event */
5389 	if (iter->head == iter->next_event) {
5390 		/* If the event gets overwritten again, there's nothing to do */
5391 		if (rb_iter_head_event(iter) == NULL)
5392 			return;
5393 	}
5394 
5395 	iter->head = iter->next_event;
5396 
5397 	/*
5398 	 * Check if we are at the end of the buffer.
5399 	 */
5400 	if (iter->next_event >= rb_page_size(iter->head_page)) {
5401 		/* discarded commits can make the page empty */
5402 		if (iter->head_page == cpu_buffer->commit_page)
5403 			return;
5404 		rb_inc_iter(iter);
5405 		return;
5406 	}
5407 
5408 	rb_update_iter_read_stamp(iter, iter->event);
5409 }
5410 
rb_lost_events(struct ring_buffer_per_cpu * cpu_buffer)5411 static int rb_lost_events(struct ring_buffer_per_cpu *cpu_buffer)
5412 {
5413 	return cpu_buffer->lost_events;
5414 }
5415 
5416 static struct ring_buffer_event *
rb_buffer_peek(struct ring_buffer_per_cpu * cpu_buffer,u64 * ts,unsigned long * lost_events)5417 rb_buffer_peek(struct ring_buffer_per_cpu *cpu_buffer, u64 *ts,
5418 	       unsigned long *lost_events)
5419 {
5420 	struct ring_buffer_event *event;
5421 	struct buffer_page *reader;
5422 	int nr_loops = 0;
5423 
5424 	if (ts)
5425 		*ts = 0;
5426  again:
5427 	/*
5428 	 * We repeat when a time extend is encountered.
5429 	 * Since the time extend is always attached to a data event,
5430 	 * we should never loop more than once.
5431 	 * (We never hit the following condition more than twice).
5432 	 */
5433 	if (RB_WARN_ON(cpu_buffer, ++nr_loops > 2))
5434 		return NULL;
5435 
5436 	reader = rb_get_reader_page(cpu_buffer);
5437 	if (!reader)
5438 		return NULL;
5439 
5440 	event = rb_reader_event(cpu_buffer);
5441 
5442 	switch (event->type_len) {
5443 	case RINGBUF_TYPE_PADDING:
5444 		if (rb_null_event(event))
5445 			RB_WARN_ON(cpu_buffer, 1);
5446 		/*
5447 		 * Because the writer could be discarding every
5448 		 * event it creates (which would probably be bad)
5449 		 * if we were to go back to "again" then we may never
5450 		 * catch up, and will trigger the warn on, or lock
5451 		 * the box. Return the padding, and we will release
5452 		 * the current locks, and try again.
5453 		 */
5454 		return event;
5455 
5456 	case RINGBUF_TYPE_TIME_EXTEND:
5457 		/* Internal data, OK to advance */
5458 		rb_advance_reader(cpu_buffer);
5459 		goto again;
5460 
5461 	case RINGBUF_TYPE_TIME_STAMP:
5462 		if (ts) {
5463 			*ts = rb_event_time_stamp(event);
5464 			*ts = rb_fix_abs_ts(*ts, reader->page->time_stamp);
5465 			ring_buffer_normalize_time_stamp(cpu_buffer->buffer,
5466 							 cpu_buffer->cpu, ts);
5467 		}
5468 		/* Internal data, OK to advance */
5469 		rb_advance_reader(cpu_buffer);
5470 		goto again;
5471 
5472 	case RINGBUF_TYPE_DATA:
5473 		if (ts && !(*ts)) {
5474 			*ts = cpu_buffer->read_stamp + event->time_delta;
5475 			ring_buffer_normalize_time_stamp(cpu_buffer->buffer,
5476 							 cpu_buffer->cpu, ts);
5477 		}
5478 		if (lost_events)
5479 			*lost_events = rb_lost_events(cpu_buffer);
5480 		return event;
5481 
5482 	default:
5483 		RB_WARN_ON(cpu_buffer, 1);
5484 	}
5485 
5486 	return NULL;
5487 }
5488 EXPORT_SYMBOL_GPL(ring_buffer_peek);
5489 
5490 static struct ring_buffer_event *
rb_iter_peek(struct ring_buffer_iter * iter,u64 * ts)5491 rb_iter_peek(struct ring_buffer_iter *iter, u64 *ts)
5492 {
5493 	struct trace_buffer *buffer;
5494 	struct ring_buffer_per_cpu *cpu_buffer;
5495 	struct ring_buffer_event *event;
5496 	int nr_loops = 0;
5497 
5498 	if (ts)
5499 		*ts = 0;
5500 
5501 	cpu_buffer = iter->cpu_buffer;
5502 	buffer = cpu_buffer->buffer;
5503 
5504 	/*
5505 	 * Check if someone performed a consuming read to the buffer
5506 	 * or removed some pages from the buffer. In these cases,
5507 	 * iterator was invalidated and we need to reset it.
5508 	 */
5509 	if (unlikely(iter->cache_read != cpu_buffer->read ||
5510 		     iter->cache_reader_page != cpu_buffer->reader_page ||
5511 		     iter->cache_pages_removed != cpu_buffer->pages_removed))
5512 		rb_iter_reset(iter);
5513 
5514  again:
5515 	if (ring_buffer_iter_empty(iter))
5516 		return NULL;
5517 
5518 	/*
5519 	 * As the writer can mess with what the iterator is trying
5520 	 * to read, just give up if we fail to get an event after
5521 	 * three tries. The iterator is not as reliable when reading
5522 	 * the ring buffer with an active write as the consumer is.
5523 	 * Do not warn if the three failures is reached.
5524 	 */
5525 	if (++nr_loops > 3)
5526 		return NULL;
5527 
5528 	if (rb_per_cpu_empty(cpu_buffer))
5529 		return NULL;
5530 
5531 	if (iter->head >= rb_page_size(iter->head_page)) {
5532 		rb_inc_iter(iter);
5533 		goto again;
5534 	}
5535 
5536 	event = rb_iter_head_event(iter);
5537 	if (!event)
5538 		goto again;
5539 
5540 	switch (event->type_len) {
5541 	case RINGBUF_TYPE_PADDING:
5542 		if (rb_null_event(event)) {
5543 			rb_inc_iter(iter);
5544 			goto again;
5545 		}
5546 		rb_advance_iter(iter);
5547 		return event;
5548 
5549 	case RINGBUF_TYPE_TIME_EXTEND:
5550 		/* Internal data, OK to advance */
5551 		rb_advance_iter(iter);
5552 		goto again;
5553 
5554 	case RINGBUF_TYPE_TIME_STAMP:
5555 		if (ts) {
5556 			*ts = rb_event_time_stamp(event);
5557 			*ts = rb_fix_abs_ts(*ts, iter->head_page->page->time_stamp);
5558 			ring_buffer_normalize_time_stamp(cpu_buffer->buffer,
5559 							 cpu_buffer->cpu, ts);
5560 		}
5561 		/* Internal data, OK to advance */
5562 		rb_advance_iter(iter);
5563 		goto again;
5564 
5565 	case RINGBUF_TYPE_DATA:
5566 		if (ts && !(*ts)) {
5567 			*ts = iter->read_stamp + event->time_delta;
5568 			ring_buffer_normalize_time_stamp(buffer,
5569 							 cpu_buffer->cpu, ts);
5570 		}
5571 		return event;
5572 
5573 	default:
5574 		RB_WARN_ON(cpu_buffer, 1);
5575 	}
5576 
5577 	return NULL;
5578 }
5579 EXPORT_SYMBOL_GPL(ring_buffer_iter_peek);
5580 
rb_reader_lock(struct ring_buffer_per_cpu * cpu_buffer)5581 static inline bool rb_reader_lock(struct ring_buffer_per_cpu *cpu_buffer)
5582 {
5583 	if (likely(!in_nmi())) {
5584 		raw_spin_lock(&cpu_buffer->reader_lock);
5585 		return true;
5586 	}
5587 
5588 	/*
5589 	 * If an NMI die dumps out the content of the ring buffer
5590 	 * trylock must be used to prevent a deadlock if the NMI
5591 	 * preempted a task that holds the ring buffer locks. If
5592 	 * we get the lock then all is fine, if not, then continue
5593 	 * to do the read, but this can corrupt the ring buffer,
5594 	 * so it must be permanently disabled from future writes.
5595 	 * Reading from NMI is a oneshot deal.
5596 	 */
5597 	if (raw_spin_trylock(&cpu_buffer->reader_lock))
5598 		return true;
5599 
5600 	/* Continue without locking, but disable the ring buffer */
5601 	atomic_inc(&cpu_buffer->record_disabled);
5602 	return false;
5603 }
5604 
5605 static inline void
rb_reader_unlock(struct ring_buffer_per_cpu * cpu_buffer,bool locked)5606 rb_reader_unlock(struct ring_buffer_per_cpu *cpu_buffer, bool locked)
5607 {
5608 	if (likely(locked))
5609 		raw_spin_unlock(&cpu_buffer->reader_lock);
5610 }
5611 
5612 /**
5613  * ring_buffer_peek - peek at the next event to be read
5614  * @buffer: The ring buffer to read
5615  * @cpu: The cpu to peak at
5616  * @ts: The timestamp counter of this event.
5617  * @lost_events: a variable to store if events were lost (may be NULL)
5618  *
5619  * This will return the event that will be read next, but does
5620  * not consume the data.
5621  */
5622 struct ring_buffer_event *
ring_buffer_peek(struct trace_buffer * buffer,int cpu,u64 * ts,unsigned long * lost_events)5623 ring_buffer_peek(struct trace_buffer *buffer, int cpu, u64 *ts,
5624 		 unsigned long *lost_events)
5625 {
5626 	struct ring_buffer_per_cpu *cpu_buffer = buffer->buffers[cpu];
5627 	struct ring_buffer_event *event;
5628 	unsigned long flags;
5629 	bool dolock;
5630 
5631 	if (!cpumask_test_cpu(cpu, buffer->cpumask))
5632 		return NULL;
5633 
5634  again:
5635 	local_irq_save(flags);
5636 	dolock = rb_reader_lock(cpu_buffer);
5637 	event = rb_buffer_peek(cpu_buffer, ts, lost_events);
5638 	if (event && event->type_len == RINGBUF_TYPE_PADDING)
5639 		rb_advance_reader(cpu_buffer);
5640 	rb_reader_unlock(cpu_buffer, dolock);
5641 	local_irq_restore(flags);
5642 
5643 	if (event && event->type_len == RINGBUF_TYPE_PADDING)
5644 		goto again;
5645 
5646 	return event;
5647 }
5648 
5649 /** ring_buffer_iter_dropped - report if there are dropped events
5650  * @iter: The ring buffer iterator
5651  *
5652  * Returns true if there was dropped events since the last peek.
5653  */
ring_buffer_iter_dropped(struct ring_buffer_iter * iter)5654 bool ring_buffer_iter_dropped(struct ring_buffer_iter *iter)
5655 {
5656 	bool ret = iter->missed_events != 0;
5657 
5658 	iter->missed_events = 0;
5659 	return ret;
5660 }
5661 EXPORT_SYMBOL_GPL(ring_buffer_iter_dropped);
5662 
5663 /**
5664  * ring_buffer_iter_peek - peek at the next event to be read
5665  * @iter: The ring buffer iterator
5666  * @ts: The timestamp counter of this event.
5667  *
5668  * This will return the event that will be read next, but does
5669  * not increment the iterator.
5670  */
5671 struct ring_buffer_event *
ring_buffer_iter_peek(struct ring_buffer_iter * iter,u64 * ts)5672 ring_buffer_iter_peek(struct ring_buffer_iter *iter, u64 *ts)
5673 {
5674 	struct ring_buffer_per_cpu *cpu_buffer = iter->cpu_buffer;
5675 	struct ring_buffer_event *event;
5676 	unsigned long flags;
5677 
5678  again:
5679 	raw_spin_lock_irqsave(&cpu_buffer->reader_lock, flags);
5680 	event = rb_iter_peek(iter, ts);
5681 	raw_spin_unlock_irqrestore(&cpu_buffer->reader_lock, flags);
5682 
5683 	if (event && event->type_len == RINGBUF_TYPE_PADDING)
5684 		goto again;
5685 
5686 	return event;
5687 }
5688 
5689 /**
5690  * ring_buffer_consume - return an event and consume it
5691  * @buffer: The ring buffer to get the next event from
5692  * @cpu: the cpu to read the buffer from
5693  * @ts: a variable to store the timestamp (may be NULL)
5694  * @lost_events: a variable to store if events were lost (may be NULL)
5695  *
5696  * Returns the next event in the ring buffer, and that event is consumed.
5697  * Meaning, that sequential reads will keep returning a different event,
5698  * and eventually empty the ring buffer if the producer is slower.
5699  */
5700 struct ring_buffer_event *
ring_buffer_consume(struct trace_buffer * buffer,int cpu,u64 * ts,unsigned long * lost_events)5701 ring_buffer_consume(struct trace_buffer *buffer, int cpu, u64 *ts,
5702 		    unsigned long *lost_events)
5703 {
5704 	struct ring_buffer_per_cpu *cpu_buffer;
5705 	struct ring_buffer_event *event = NULL;
5706 	unsigned long flags;
5707 	bool dolock;
5708 
5709  again:
5710 	/* might be called in atomic */
5711 	preempt_disable();
5712 
5713 	if (!cpumask_test_cpu(cpu, buffer->cpumask))
5714 		goto out;
5715 
5716 	cpu_buffer = buffer->buffers[cpu];
5717 	local_irq_save(flags);
5718 	dolock = rb_reader_lock(cpu_buffer);
5719 
5720 	event = rb_buffer_peek(cpu_buffer, ts, lost_events);
5721 	if (event) {
5722 		cpu_buffer->lost_events = 0;
5723 		rb_advance_reader(cpu_buffer);
5724 	}
5725 
5726 	rb_reader_unlock(cpu_buffer, dolock);
5727 	local_irq_restore(flags);
5728 
5729  out:
5730 	preempt_enable();
5731 
5732 	if (event && event->type_len == RINGBUF_TYPE_PADDING)
5733 		goto again;
5734 
5735 	return event;
5736 }
5737 EXPORT_SYMBOL_GPL(ring_buffer_consume);
5738 
5739 /**
5740  * ring_buffer_read_prepare - Prepare for a non consuming read of the buffer
5741  * @buffer: The ring buffer to read from
5742  * @cpu: The cpu buffer to iterate over
5743  * @flags: gfp flags to use for memory allocation
5744  *
5745  * This performs the initial preparations necessary to iterate
5746  * through the buffer.  Memory is allocated, buffer resizing
5747  * is disabled, and the iterator pointer is returned to the caller.
5748  *
5749  * After a sequence of ring_buffer_read_prepare calls, the user is
5750  * expected to make at least one call to ring_buffer_read_prepare_sync.
5751  * Afterwards, ring_buffer_read_start is invoked to get things going
5752  * for real.
5753  *
5754  * This overall must be paired with ring_buffer_read_finish.
5755  */
5756 struct ring_buffer_iter *
ring_buffer_read_prepare(struct trace_buffer * buffer,int cpu,gfp_t flags)5757 ring_buffer_read_prepare(struct trace_buffer *buffer, int cpu, gfp_t flags)
5758 {
5759 	struct ring_buffer_per_cpu *cpu_buffer;
5760 	struct ring_buffer_iter *iter;
5761 
5762 	if (!cpumask_test_cpu(cpu, buffer->cpumask))
5763 		return NULL;
5764 
5765 	iter = kzalloc(sizeof(*iter), flags);
5766 	if (!iter)
5767 		return NULL;
5768 
5769 	/* Holds the entire event: data and meta data */
5770 	iter->event_size = buffer->subbuf_size;
5771 	iter->event = kmalloc(iter->event_size, flags);
5772 	if (!iter->event) {
5773 		kfree(iter);
5774 		return NULL;
5775 	}
5776 
5777 	cpu_buffer = buffer->buffers[cpu];
5778 
5779 	iter->cpu_buffer = cpu_buffer;
5780 
5781 	atomic_inc(&cpu_buffer->resize_disabled);
5782 
5783 	return iter;
5784 }
5785 EXPORT_SYMBOL_GPL(ring_buffer_read_prepare);
5786 
5787 /**
5788  * ring_buffer_read_prepare_sync - Synchronize a set of prepare calls
5789  *
5790  * All previously invoked ring_buffer_read_prepare calls to prepare
5791  * iterators will be synchronized.  Afterwards, read_buffer_read_start
5792  * calls on those iterators are allowed.
5793  */
5794 void
ring_buffer_read_prepare_sync(void)5795 ring_buffer_read_prepare_sync(void)
5796 {
5797 	synchronize_rcu();
5798 }
5799 EXPORT_SYMBOL_GPL(ring_buffer_read_prepare_sync);
5800 
5801 /**
5802  * ring_buffer_read_start - start a non consuming read of the buffer
5803  * @iter: The iterator returned by ring_buffer_read_prepare
5804  *
5805  * This finalizes the startup of an iteration through the buffer.
5806  * The iterator comes from a call to ring_buffer_read_prepare and
5807  * an intervening ring_buffer_read_prepare_sync must have been
5808  * performed.
5809  *
5810  * Must be paired with ring_buffer_read_finish.
5811  */
5812 void
ring_buffer_read_start(struct ring_buffer_iter * iter)5813 ring_buffer_read_start(struct ring_buffer_iter *iter)
5814 {
5815 	struct ring_buffer_per_cpu *cpu_buffer;
5816 	unsigned long flags;
5817 
5818 	if (!iter)
5819 		return;
5820 
5821 	cpu_buffer = iter->cpu_buffer;
5822 
5823 	raw_spin_lock_irqsave(&cpu_buffer->reader_lock, flags);
5824 	arch_spin_lock(&cpu_buffer->lock);
5825 	rb_iter_reset(iter);
5826 	arch_spin_unlock(&cpu_buffer->lock);
5827 	raw_spin_unlock_irqrestore(&cpu_buffer->reader_lock, flags);
5828 }
5829 EXPORT_SYMBOL_GPL(ring_buffer_read_start);
5830 
5831 /**
5832  * ring_buffer_read_finish - finish reading the iterator of the buffer
5833  * @iter: The iterator retrieved by ring_buffer_start
5834  *
5835  * This re-enables resizing of the buffer, and frees the iterator.
5836  */
5837 void
ring_buffer_read_finish(struct ring_buffer_iter * iter)5838 ring_buffer_read_finish(struct ring_buffer_iter *iter)
5839 {
5840 	struct ring_buffer_per_cpu *cpu_buffer = iter->cpu_buffer;
5841 	unsigned long flags;
5842 
5843 	/* Use this opportunity to check the integrity of the ring buffer. */
5844 	raw_spin_lock_irqsave(&cpu_buffer->reader_lock, flags);
5845 	rb_check_pages(cpu_buffer);
5846 	raw_spin_unlock_irqrestore(&cpu_buffer->reader_lock, flags);
5847 
5848 	atomic_dec(&cpu_buffer->resize_disabled);
5849 	kfree(iter->event);
5850 	kfree(iter);
5851 }
5852 EXPORT_SYMBOL_GPL(ring_buffer_read_finish);
5853 
5854 /**
5855  * ring_buffer_iter_advance - advance the iterator to the next location
5856  * @iter: The ring buffer iterator
5857  *
5858  * Move the location of the iterator such that the next read will
5859  * be the next location of the iterator.
5860  */
ring_buffer_iter_advance(struct ring_buffer_iter * iter)5861 void ring_buffer_iter_advance(struct ring_buffer_iter *iter)
5862 {
5863 	struct ring_buffer_per_cpu *cpu_buffer = iter->cpu_buffer;
5864 	unsigned long flags;
5865 
5866 	raw_spin_lock_irqsave(&cpu_buffer->reader_lock, flags);
5867 
5868 	rb_advance_iter(iter);
5869 
5870 	raw_spin_unlock_irqrestore(&cpu_buffer->reader_lock, flags);
5871 }
5872 EXPORT_SYMBOL_GPL(ring_buffer_iter_advance);
5873 
5874 /**
5875  * ring_buffer_size - return the size of the ring buffer (in bytes)
5876  * @buffer: The ring buffer.
5877  * @cpu: The CPU to get ring buffer size from.
5878  */
ring_buffer_size(struct trace_buffer * buffer,int cpu)5879 unsigned long ring_buffer_size(struct trace_buffer *buffer, int cpu)
5880 {
5881 	if (!cpumask_test_cpu(cpu, buffer->cpumask))
5882 		return 0;
5883 
5884 	return buffer->subbuf_size * buffer->buffers[cpu]->nr_pages;
5885 }
5886 EXPORT_SYMBOL_GPL(ring_buffer_size);
5887 
5888 /**
5889  * ring_buffer_max_event_size - return the max data size of an event
5890  * @buffer: The ring buffer.
5891  *
5892  * Returns the maximum size an event can be.
5893  */
ring_buffer_max_event_size(struct trace_buffer * buffer)5894 unsigned long ring_buffer_max_event_size(struct trace_buffer *buffer)
5895 {
5896 	/* If abs timestamp is requested, events have a timestamp too */
5897 	if (ring_buffer_time_stamp_abs(buffer))
5898 		return buffer->max_data_size - RB_LEN_TIME_EXTEND;
5899 	return buffer->max_data_size;
5900 }
5901 EXPORT_SYMBOL_GPL(ring_buffer_max_event_size);
5902 
rb_clear_buffer_page(struct buffer_page * page)5903 static void rb_clear_buffer_page(struct buffer_page *page)
5904 {
5905 	local_set(&page->write, 0);
5906 	local_set(&page->entries, 0);
5907 	rb_init_page(page->page);
5908 	page->read = 0;
5909 }
5910 
rb_update_meta_page(struct ring_buffer_per_cpu * cpu_buffer)5911 static void rb_update_meta_page(struct ring_buffer_per_cpu *cpu_buffer)
5912 {
5913 	struct trace_buffer_meta *meta = cpu_buffer->meta_page;
5914 
5915 	if (!meta)
5916 		return;
5917 
5918 	meta->reader.read = cpu_buffer->reader_page->read;
5919 	meta->reader.id = cpu_buffer->reader_page->id;
5920 	meta->reader.lost_events = cpu_buffer->lost_events;
5921 
5922 	meta->entries = local_read(&cpu_buffer->entries);
5923 	meta->overrun = local_read(&cpu_buffer->overrun);
5924 	meta->read = cpu_buffer->read;
5925 
5926 	/* Some archs do not have data cache coherency between kernel and user-space */
5927 	flush_dcache_folio(virt_to_folio(cpu_buffer->meta_page));
5928 }
5929 
5930 static void
rb_reset_cpu(struct ring_buffer_per_cpu * cpu_buffer)5931 rb_reset_cpu(struct ring_buffer_per_cpu *cpu_buffer)
5932 {
5933 	struct buffer_page *page;
5934 
5935 	rb_head_page_deactivate(cpu_buffer);
5936 
5937 	cpu_buffer->head_page
5938 		= list_entry(cpu_buffer->pages, struct buffer_page, list);
5939 	rb_clear_buffer_page(cpu_buffer->head_page);
5940 	list_for_each_entry(page, cpu_buffer->pages, list) {
5941 		rb_clear_buffer_page(page);
5942 	}
5943 
5944 	cpu_buffer->tail_page = cpu_buffer->head_page;
5945 	cpu_buffer->commit_page = cpu_buffer->head_page;
5946 
5947 	INIT_LIST_HEAD(&cpu_buffer->reader_page->list);
5948 	INIT_LIST_HEAD(&cpu_buffer->new_pages);
5949 	rb_clear_buffer_page(cpu_buffer->reader_page);
5950 
5951 	local_set(&cpu_buffer->entries_bytes, 0);
5952 	local_set(&cpu_buffer->overrun, 0);
5953 	local_set(&cpu_buffer->commit_overrun, 0);
5954 	local_set(&cpu_buffer->dropped_events, 0);
5955 	local_set(&cpu_buffer->entries, 0);
5956 	local_set(&cpu_buffer->committing, 0);
5957 	local_set(&cpu_buffer->commits, 0);
5958 	local_set(&cpu_buffer->pages_touched, 0);
5959 	local_set(&cpu_buffer->pages_lost, 0);
5960 	local_set(&cpu_buffer->pages_read, 0);
5961 	cpu_buffer->last_pages_touch = 0;
5962 	cpu_buffer->shortest_full = 0;
5963 	cpu_buffer->read = 0;
5964 	cpu_buffer->read_bytes = 0;
5965 
5966 	rb_time_set(&cpu_buffer->write_stamp, 0);
5967 	rb_time_set(&cpu_buffer->before_stamp, 0);
5968 
5969 	memset(cpu_buffer->event_stamp, 0, sizeof(cpu_buffer->event_stamp));
5970 
5971 	cpu_buffer->lost_events = 0;
5972 	cpu_buffer->last_overrun = 0;
5973 
5974 	rb_head_page_activate(cpu_buffer);
5975 	cpu_buffer->pages_removed = 0;
5976 
5977 	if (cpu_buffer->mapped) {
5978 		rb_update_meta_page(cpu_buffer);
5979 		if (cpu_buffer->ring_meta) {
5980 			struct ring_buffer_meta *meta = cpu_buffer->ring_meta;
5981 			meta->commit_buffer = meta->head_buffer;
5982 		}
5983 	}
5984 }
5985 
5986 /* Must have disabled the cpu buffer then done a synchronize_rcu */
reset_disabled_cpu_buffer(struct ring_buffer_per_cpu * cpu_buffer)5987 static void reset_disabled_cpu_buffer(struct ring_buffer_per_cpu *cpu_buffer)
5988 {
5989 	unsigned long flags;
5990 
5991 	raw_spin_lock_irqsave(&cpu_buffer->reader_lock, flags);
5992 
5993 	if (RB_WARN_ON(cpu_buffer, local_read(&cpu_buffer->committing)))
5994 		goto out;
5995 
5996 	arch_spin_lock(&cpu_buffer->lock);
5997 
5998 	rb_reset_cpu(cpu_buffer);
5999 
6000 	arch_spin_unlock(&cpu_buffer->lock);
6001 
6002  out:
6003 	raw_spin_unlock_irqrestore(&cpu_buffer->reader_lock, flags);
6004 }
6005 
6006 /**
6007  * ring_buffer_reset_cpu - reset a ring buffer per CPU buffer
6008  * @buffer: The ring buffer to reset a per cpu buffer of
6009  * @cpu: The CPU buffer to be reset
6010  */
ring_buffer_reset_cpu(struct trace_buffer * buffer,int cpu)6011 void ring_buffer_reset_cpu(struct trace_buffer *buffer, int cpu)
6012 {
6013 	struct ring_buffer_per_cpu *cpu_buffer = buffer->buffers[cpu];
6014 	struct ring_buffer_meta *meta;
6015 
6016 	if (!cpumask_test_cpu(cpu, buffer->cpumask))
6017 		return;
6018 
6019 	/* prevent another thread from changing buffer sizes */
6020 	mutex_lock(&buffer->mutex);
6021 
6022 	atomic_inc(&cpu_buffer->resize_disabled);
6023 	atomic_inc(&cpu_buffer->record_disabled);
6024 
6025 	/* Make sure all commits have finished */
6026 	synchronize_rcu();
6027 
6028 	reset_disabled_cpu_buffer(cpu_buffer);
6029 
6030 	atomic_dec(&cpu_buffer->record_disabled);
6031 	atomic_dec(&cpu_buffer->resize_disabled);
6032 
6033 	/* Make sure persistent meta now uses this buffer's addresses */
6034 	meta = rb_range_meta(buffer, 0, cpu_buffer->cpu);
6035 	if (meta)
6036 		rb_meta_init_text_addr(meta);
6037 
6038 	mutex_unlock(&buffer->mutex);
6039 }
6040 EXPORT_SYMBOL_GPL(ring_buffer_reset_cpu);
6041 
6042 /* Flag to ensure proper resetting of atomic variables */
6043 #define RESET_BIT	(1 << 30)
6044 
6045 /**
6046  * ring_buffer_reset_online_cpus - reset a ring buffer per CPU buffer
6047  * @buffer: The ring buffer to reset a per cpu buffer of
6048  */
ring_buffer_reset_online_cpus(struct trace_buffer * buffer)6049 void ring_buffer_reset_online_cpus(struct trace_buffer *buffer)
6050 {
6051 	struct ring_buffer_per_cpu *cpu_buffer;
6052 	struct ring_buffer_meta *meta;
6053 	int cpu;
6054 
6055 	/* prevent another thread from changing buffer sizes */
6056 	mutex_lock(&buffer->mutex);
6057 
6058 	for_each_online_buffer_cpu(buffer, cpu) {
6059 		cpu_buffer = buffer->buffers[cpu];
6060 
6061 		atomic_add(RESET_BIT, &cpu_buffer->resize_disabled);
6062 		atomic_inc(&cpu_buffer->record_disabled);
6063 	}
6064 
6065 	/* Make sure all commits have finished */
6066 	synchronize_rcu();
6067 
6068 	for_each_buffer_cpu(buffer, cpu) {
6069 		cpu_buffer = buffer->buffers[cpu];
6070 
6071 		/*
6072 		 * If a CPU came online during the synchronize_rcu(), then
6073 		 * ignore it.
6074 		 */
6075 		if (!(atomic_read(&cpu_buffer->resize_disabled) & RESET_BIT))
6076 			continue;
6077 
6078 		reset_disabled_cpu_buffer(cpu_buffer);
6079 
6080 		/* Make sure persistent meta now uses this buffer's addresses */
6081 		meta = rb_range_meta(buffer, 0, cpu_buffer->cpu);
6082 		if (meta)
6083 			rb_meta_init_text_addr(meta);
6084 
6085 		atomic_dec(&cpu_buffer->record_disabled);
6086 		atomic_sub(RESET_BIT, &cpu_buffer->resize_disabled);
6087 	}
6088 
6089 	mutex_unlock(&buffer->mutex);
6090 }
6091 
6092 /**
6093  * ring_buffer_reset - reset a ring buffer
6094  * @buffer: The ring buffer to reset all cpu buffers
6095  */
ring_buffer_reset(struct trace_buffer * buffer)6096 void ring_buffer_reset(struct trace_buffer *buffer)
6097 {
6098 	struct ring_buffer_per_cpu *cpu_buffer;
6099 	int cpu;
6100 
6101 	/* prevent another thread from changing buffer sizes */
6102 	mutex_lock(&buffer->mutex);
6103 
6104 	for_each_buffer_cpu(buffer, cpu) {
6105 		cpu_buffer = buffer->buffers[cpu];
6106 
6107 		atomic_inc(&cpu_buffer->resize_disabled);
6108 		atomic_inc(&cpu_buffer->record_disabled);
6109 	}
6110 
6111 	/* Make sure all commits have finished */
6112 	synchronize_rcu();
6113 
6114 	for_each_buffer_cpu(buffer, cpu) {
6115 		cpu_buffer = buffer->buffers[cpu];
6116 
6117 		reset_disabled_cpu_buffer(cpu_buffer);
6118 
6119 		atomic_dec(&cpu_buffer->record_disabled);
6120 		atomic_dec(&cpu_buffer->resize_disabled);
6121 	}
6122 
6123 	mutex_unlock(&buffer->mutex);
6124 }
6125 EXPORT_SYMBOL_GPL(ring_buffer_reset);
6126 
6127 /**
6128  * ring_buffer_empty - is the ring buffer empty?
6129  * @buffer: The ring buffer to test
6130  */
ring_buffer_empty(struct trace_buffer * buffer)6131 bool ring_buffer_empty(struct trace_buffer *buffer)
6132 {
6133 	struct ring_buffer_per_cpu *cpu_buffer;
6134 	unsigned long flags;
6135 	bool dolock;
6136 	bool ret;
6137 	int cpu;
6138 
6139 	/* yes this is racy, but if you don't like the race, lock the buffer */
6140 	for_each_buffer_cpu(buffer, cpu) {
6141 		cpu_buffer = buffer->buffers[cpu];
6142 		local_irq_save(flags);
6143 		dolock = rb_reader_lock(cpu_buffer);
6144 		ret = rb_per_cpu_empty(cpu_buffer);
6145 		rb_reader_unlock(cpu_buffer, dolock);
6146 		local_irq_restore(flags);
6147 
6148 		if (!ret)
6149 			return false;
6150 	}
6151 
6152 	return true;
6153 }
6154 EXPORT_SYMBOL_GPL(ring_buffer_empty);
6155 
6156 /**
6157  * ring_buffer_empty_cpu - is a cpu buffer of a ring buffer empty?
6158  * @buffer: The ring buffer
6159  * @cpu: The CPU buffer to test
6160  */
ring_buffer_empty_cpu(struct trace_buffer * buffer,int cpu)6161 bool ring_buffer_empty_cpu(struct trace_buffer *buffer, int cpu)
6162 {
6163 	struct ring_buffer_per_cpu *cpu_buffer;
6164 	unsigned long flags;
6165 	bool dolock;
6166 	bool ret;
6167 
6168 	if (!cpumask_test_cpu(cpu, buffer->cpumask))
6169 		return true;
6170 
6171 	cpu_buffer = buffer->buffers[cpu];
6172 	local_irq_save(flags);
6173 	dolock = rb_reader_lock(cpu_buffer);
6174 	ret = rb_per_cpu_empty(cpu_buffer);
6175 	rb_reader_unlock(cpu_buffer, dolock);
6176 	local_irq_restore(flags);
6177 
6178 	return ret;
6179 }
6180 EXPORT_SYMBOL_GPL(ring_buffer_empty_cpu);
6181 
6182 #ifdef CONFIG_RING_BUFFER_ALLOW_SWAP
6183 /**
6184  * ring_buffer_swap_cpu - swap a CPU buffer between two ring buffers
6185  * @buffer_a: One buffer to swap with
6186  * @buffer_b: The other buffer to swap with
6187  * @cpu: the CPU of the buffers to swap
6188  *
6189  * This function is useful for tracers that want to take a "snapshot"
6190  * of a CPU buffer and has another back up buffer lying around.
6191  * it is expected that the tracer handles the cpu buffer not being
6192  * used at the moment.
6193  */
ring_buffer_swap_cpu(struct trace_buffer * buffer_a,struct trace_buffer * buffer_b,int cpu)6194 int ring_buffer_swap_cpu(struct trace_buffer *buffer_a,
6195 			 struct trace_buffer *buffer_b, int cpu)
6196 {
6197 	struct ring_buffer_per_cpu *cpu_buffer_a;
6198 	struct ring_buffer_per_cpu *cpu_buffer_b;
6199 	int ret = -EINVAL;
6200 
6201 	if (!cpumask_test_cpu(cpu, buffer_a->cpumask) ||
6202 	    !cpumask_test_cpu(cpu, buffer_b->cpumask))
6203 		goto out;
6204 
6205 	cpu_buffer_a = buffer_a->buffers[cpu];
6206 	cpu_buffer_b = buffer_b->buffers[cpu];
6207 
6208 	/* It's up to the callers to not try to swap mapped buffers */
6209 	if (WARN_ON_ONCE(cpu_buffer_a->mapped || cpu_buffer_b->mapped)) {
6210 		ret = -EBUSY;
6211 		goto out;
6212 	}
6213 
6214 	/* At least make sure the two buffers are somewhat the same */
6215 	if (cpu_buffer_a->nr_pages != cpu_buffer_b->nr_pages)
6216 		goto out;
6217 
6218 	if (buffer_a->subbuf_order != buffer_b->subbuf_order)
6219 		goto out;
6220 
6221 	ret = -EAGAIN;
6222 
6223 	if (atomic_read(&buffer_a->record_disabled))
6224 		goto out;
6225 
6226 	if (atomic_read(&buffer_b->record_disabled))
6227 		goto out;
6228 
6229 	if (atomic_read(&cpu_buffer_a->record_disabled))
6230 		goto out;
6231 
6232 	if (atomic_read(&cpu_buffer_b->record_disabled))
6233 		goto out;
6234 
6235 	/*
6236 	 * We can't do a synchronize_rcu here because this
6237 	 * function can be called in atomic context.
6238 	 * Normally this will be called from the same CPU as cpu.
6239 	 * If not it's up to the caller to protect this.
6240 	 */
6241 	atomic_inc(&cpu_buffer_a->record_disabled);
6242 	atomic_inc(&cpu_buffer_b->record_disabled);
6243 
6244 	ret = -EBUSY;
6245 	if (local_read(&cpu_buffer_a->committing))
6246 		goto out_dec;
6247 	if (local_read(&cpu_buffer_b->committing))
6248 		goto out_dec;
6249 
6250 	/*
6251 	 * When resize is in progress, we cannot swap it because
6252 	 * it will mess the state of the cpu buffer.
6253 	 */
6254 	if (atomic_read(&buffer_a->resizing))
6255 		goto out_dec;
6256 	if (atomic_read(&buffer_b->resizing))
6257 		goto out_dec;
6258 
6259 	buffer_a->buffers[cpu] = cpu_buffer_b;
6260 	buffer_b->buffers[cpu] = cpu_buffer_a;
6261 
6262 	cpu_buffer_b->buffer = buffer_a;
6263 	cpu_buffer_a->buffer = buffer_b;
6264 
6265 	ret = 0;
6266 
6267 out_dec:
6268 	atomic_dec(&cpu_buffer_a->record_disabled);
6269 	atomic_dec(&cpu_buffer_b->record_disabled);
6270 out:
6271 	return ret;
6272 }
6273 EXPORT_SYMBOL_GPL(ring_buffer_swap_cpu);
6274 #endif /* CONFIG_RING_BUFFER_ALLOW_SWAP */
6275 
6276 /**
6277  * ring_buffer_alloc_read_page - allocate a page to read from buffer
6278  * @buffer: the buffer to allocate for.
6279  * @cpu: the cpu buffer to allocate.
6280  *
6281  * This function is used in conjunction with ring_buffer_read_page.
6282  * When reading a full page from the ring buffer, these functions
6283  * can be used to speed up the process. The calling function should
6284  * allocate a few pages first with this function. Then when it
6285  * needs to get pages from the ring buffer, it passes the result
6286  * of this function into ring_buffer_read_page, which will swap
6287  * the page that was allocated, with the read page of the buffer.
6288  *
6289  * Returns:
6290  *  The page allocated, or ERR_PTR
6291  */
6292 struct buffer_data_read_page *
ring_buffer_alloc_read_page(struct trace_buffer * buffer,int cpu)6293 ring_buffer_alloc_read_page(struct trace_buffer *buffer, int cpu)
6294 {
6295 	struct ring_buffer_per_cpu *cpu_buffer;
6296 	struct buffer_data_read_page *bpage = NULL;
6297 	unsigned long flags;
6298 	struct page *page;
6299 
6300 	if (!cpumask_test_cpu(cpu, buffer->cpumask))
6301 		return ERR_PTR(-ENODEV);
6302 
6303 	bpage = kzalloc(sizeof(*bpage), GFP_KERNEL);
6304 	if (!bpage)
6305 		return ERR_PTR(-ENOMEM);
6306 
6307 	bpage->order = buffer->subbuf_order;
6308 	cpu_buffer = buffer->buffers[cpu];
6309 	local_irq_save(flags);
6310 	arch_spin_lock(&cpu_buffer->lock);
6311 
6312 	if (cpu_buffer->free_page) {
6313 		bpage->data = cpu_buffer->free_page;
6314 		cpu_buffer->free_page = NULL;
6315 	}
6316 
6317 	arch_spin_unlock(&cpu_buffer->lock);
6318 	local_irq_restore(flags);
6319 
6320 	if (bpage->data)
6321 		goto out;
6322 
6323 	page = alloc_pages_node(cpu_to_node(cpu),
6324 				GFP_KERNEL | __GFP_NORETRY | __GFP_COMP | __GFP_ZERO,
6325 				cpu_buffer->buffer->subbuf_order);
6326 	if (!page) {
6327 		kfree(bpage);
6328 		return ERR_PTR(-ENOMEM);
6329 	}
6330 
6331 	bpage->data = page_address(page);
6332 
6333  out:
6334 	rb_init_page(bpage->data);
6335 
6336 	return bpage;
6337 }
6338 EXPORT_SYMBOL_GPL(ring_buffer_alloc_read_page);
6339 
6340 /**
6341  * ring_buffer_free_read_page - free an allocated read page
6342  * @buffer: the buffer the page was allocate for
6343  * @cpu: the cpu buffer the page came from
6344  * @data_page: the page to free
6345  *
6346  * Free a page allocated from ring_buffer_alloc_read_page.
6347  */
ring_buffer_free_read_page(struct trace_buffer * buffer,int cpu,struct buffer_data_read_page * data_page)6348 void ring_buffer_free_read_page(struct trace_buffer *buffer, int cpu,
6349 				struct buffer_data_read_page *data_page)
6350 {
6351 	struct ring_buffer_per_cpu *cpu_buffer;
6352 	struct buffer_data_page *bpage = data_page->data;
6353 	struct page *page = virt_to_page(bpage);
6354 	unsigned long flags;
6355 
6356 	if (!buffer || !buffer->buffers || !buffer->buffers[cpu])
6357 		return;
6358 
6359 	cpu_buffer = buffer->buffers[cpu];
6360 
6361 	/*
6362 	 * If the page is still in use someplace else, or order of the page
6363 	 * is different from the subbuffer order of the buffer -
6364 	 * we can't reuse it
6365 	 */
6366 	if (page_ref_count(page) > 1 || data_page->order != buffer->subbuf_order)
6367 		goto out;
6368 
6369 	local_irq_save(flags);
6370 	arch_spin_lock(&cpu_buffer->lock);
6371 
6372 	if (!cpu_buffer->free_page) {
6373 		cpu_buffer->free_page = bpage;
6374 		bpage = NULL;
6375 	}
6376 
6377 	arch_spin_unlock(&cpu_buffer->lock);
6378 	local_irq_restore(flags);
6379 
6380  out:
6381 	free_pages((unsigned long)bpage, data_page->order);
6382 	kfree(data_page);
6383 }
6384 EXPORT_SYMBOL_GPL(ring_buffer_free_read_page);
6385 
6386 /**
6387  * ring_buffer_read_page - extract a page from the ring buffer
6388  * @buffer: buffer to extract from
6389  * @data_page: the page to use allocated from ring_buffer_alloc_read_page
6390  * @len: amount to extract
6391  * @cpu: the cpu of the buffer to extract
6392  * @full: should the extraction only happen when the page is full.
6393  *
6394  * This function will pull out a page from the ring buffer and consume it.
6395  * @data_page must be the address of the variable that was returned
6396  * from ring_buffer_alloc_read_page. This is because the page might be used
6397  * to swap with a page in the ring buffer.
6398  *
6399  * for example:
6400  *	rpage = ring_buffer_alloc_read_page(buffer, cpu);
6401  *	if (IS_ERR(rpage))
6402  *		return PTR_ERR(rpage);
6403  *	ret = ring_buffer_read_page(buffer, rpage, len, cpu, 0);
6404  *	if (ret >= 0)
6405  *		process_page(ring_buffer_read_page_data(rpage), ret);
6406  *	ring_buffer_free_read_page(buffer, cpu, rpage);
6407  *
6408  * When @full is set, the function will not return true unless
6409  * the writer is off the reader page.
6410  *
6411  * Note: it is up to the calling functions to handle sleeps and wakeups.
6412  *  The ring buffer can be used anywhere in the kernel and can not
6413  *  blindly call wake_up. The layer that uses the ring buffer must be
6414  *  responsible for that.
6415  *
6416  * Returns:
6417  *  >=0 if data has been transferred, returns the offset of consumed data.
6418  *  <0 if no data has been transferred.
6419  */
ring_buffer_read_page(struct trace_buffer * buffer,struct buffer_data_read_page * data_page,size_t len,int cpu,int full)6420 int ring_buffer_read_page(struct trace_buffer *buffer,
6421 			  struct buffer_data_read_page *data_page,
6422 			  size_t len, int cpu, int full)
6423 {
6424 	struct ring_buffer_per_cpu *cpu_buffer = buffer->buffers[cpu];
6425 	struct ring_buffer_event *event;
6426 	struct buffer_data_page *bpage;
6427 	struct buffer_page *reader;
6428 	unsigned long missed_events;
6429 	unsigned long flags;
6430 	unsigned int commit;
6431 	unsigned int read;
6432 	u64 save_timestamp;
6433 	int ret = -1;
6434 
6435 	if (!cpumask_test_cpu(cpu, buffer->cpumask))
6436 		goto out;
6437 
6438 	/*
6439 	 * If len is not big enough to hold the page header, then
6440 	 * we can not copy anything.
6441 	 */
6442 	if (len <= BUF_PAGE_HDR_SIZE)
6443 		goto out;
6444 
6445 	len -= BUF_PAGE_HDR_SIZE;
6446 
6447 	if (!data_page || !data_page->data)
6448 		goto out;
6449 	if (data_page->order != buffer->subbuf_order)
6450 		goto out;
6451 
6452 	bpage = data_page->data;
6453 	if (!bpage)
6454 		goto out;
6455 
6456 	raw_spin_lock_irqsave(&cpu_buffer->reader_lock, flags);
6457 
6458 	reader = rb_get_reader_page(cpu_buffer);
6459 	if (!reader)
6460 		goto out_unlock;
6461 
6462 	event = rb_reader_event(cpu_buffer);
6463 
6464 	read = reader->read;
6465 	commit = rb_page_size(reader);
6466 
6467 	/* Check if any events were dropped */
6468 	missed_events = cpu_buffer->lost_events;
6469 
6470 	/*
6471 	 * If this page has been partially read or
6472 	 * if len is not big enough to read the rest of the page or
6473 	 * a writer is still on the page, then
6474 	 * we must copy the data from the page to the buffer.
6475 	 * Otherwise, we can simply swap the page with the one passed in.
6476 	 */
6477 	if (read || (len < (commit - read)) ||
6478 	    cpu_buffer->reader_page == cpu_buffer->commit_page ||
6479 	    cpu_buffer->mapped) {
6480 		struct buffer_data_page *rpage = cpu_buffer->reader_page->page;
6481 		unsigned int rpos = read;
6482 		unsigned int pos = 0;
6483 		unsigned int size;
6484 
6485 		/*
6486 		 * If a full page is expected, this can still be returned
6487 		 * if there's been a previous partial read and the
6488 		 * rest of the page can be read and the commit page is off
6489 		 * the reader page.
6490 		 */
6491 		if (full &&
6492 		    (!read || (len < (commit - read)) ||
6493 		     cpu_buffer->reader_page == cpu_buffer->commit_page))
6494 			goto out_unlock;
6495 
6496 		if (len > (commit - read))
6497 			len = (commit - read);
6498 
6499 		/* Always keep the time extend and data together */
6500 		size = rb_event_ts_length(event);
6501 
6502 		if (len < size)
6503 			goto out_unlock;
6504 
6505 		/* save the current timestamp, since the user will need it */
6506 		save_timestamp = cpu_buffer->read_stamp;
6507 
6508 		/* Need to copy one event at a time */
6509 		do {
6510 			/* We need the size of one event, because
6511 			 * rb_advance_reader only advances by one event,
6512 			 * whereas rb_event_ts_length may include the size of
6513 			 * one or two events.
6514 			 * We have already ensured there's enough space if this
6515 			 * is a time extend. */
6516 			size = rb_event_length(event);
6517 			memcpy(bpage->data + pos, rpage->data + rpos, size);
6518 
6519 			len -= size;
6520 
6521 			rb_advance_reader(cpu_buffer);
6522 			rpos = reader->read;
6523 			pos += size;
6524 
6525 			if (rpos >= commit)
6526 				break;
6527 
6528 			event = rb_reader_event(cpu_buffer);
6529 			/* Always keep the time extend and data together */
6530 			size = rb_event_ts_length(event);
6531 		} while (len >= size);
6532 
6533 		/* update bpage */
6534 		local_set(&bpage->commit, pos);
6535 		bpage->time_stamp = save_timestamp;
6536 
6537 		/* we copied everything to the beginning */
6538 		read = 0;
6539 	} else {
6540 		/* update the entry counter */
6541 		cpu_buffer->read += rb_page_entries(reader);
6542 		cpu_buffer->read_bytes += rb_page_size(reader);
6543 
6544 		/* swap the pages */
6545 		rb_init_page(bpage);
6546 		bpage = reader->page;
6547 		reader->page = data_page->data;
6548 		local_set(&reader->write, 0);
6549 		local_set(&reader->entries, 0);
6550 		reader->read = 0;
6551 		data_page->data = bpage;
6552 
6553 		/*
6554 		 * Use the real_end for the data size,
6555 		 * This gives us a chance to store the lost events
6556 		 * on the page.
6557 		 */
6558 		if (reader->real_end)
6559 			local_set(&bpage->commit, reader->real_end);
6560 	}
6561 	ret = read;
6562 
6563 	cpu_buffer->lost_events = 0;
6564 
6565 	commit = local_read(&bpage->commit);
6566 	/*
6567 	 * Set a flag in the commit field if we lost events
6568 	 */
6569 	if (missed_events) {
6570 		/* If there is room at the end of the page to save the
6571 		 * missed events, then record it there.
6572 		 */
6573 		if (buffer->subbuf_size - commit >= sizeof(missed_events)) {
6574 			memcpy(&bpage->data[commit], &missed_events,
6575 			       sizeof(missed_events));
6576 			local_add(RB_MISSED_STORED, &bpage->commit);
6577 			commit += sizeof(missed_events);
6578 		}
6579 		local_add(RB_MISSED_EVENTS, &bpage->commit);
6580 	}
6581 
6582 	/*
6583 	 * This page may be off to user land. Zero it out here.
6584 	 */
6585 	if (commit < buffer->subbuf_size)
6586 		memset(&bpage->data[commit], 0, buffer->subbuf_size - commit);
6587 
6588  out_unlock:
6589 	raw_spin_unlock_irqrestore(&cpu_buffer->reader_lock, flags);
6590 
6591  out:
6592 	return ret;
6593 }
6594 EXPORT_SYMBOL_GPL(ring_buffer_read_page);
6595 
6596 /**
6597  * ring_buffer_read_page_data - get pointer to the data in the page.
6598  * @page:  the page to get the data from
6599  *
6600  * Returns pointer to the actual data in this page.
6601  */
ring_buffer_read_page_data(struct buffer_data_read_page * page)6602 void *ring_buffer_read_page_data(struct buffer_data_read_page *page)
6603 {
6604 	return page->data;
6605 }
6606 EXPORT_SYMBOL_GPL(ring_buffer_read_page_data);
6607 
6608 /**
6609  * ring_buffer_subbuf_size_get - get size of the sub buffer.
6610  * @buffer: the buffer to get the sub buffer size from
6611  *
6612  * Returns size of the sub buffer, in bytes.
6613  */
ring_buffer_subbuf_size_get(struct trace_buffer * buffer)6614 int ring_buffer_subbuf_size_get(struct trace_buffer *buffer)
6615 {
6616 	return buffer->subbuf_size + BUF_PAGE_HDR_SIZE;
6617 }
6618 EXPORT_SYMBOL_GPL(ring_buffer_subbuf_size_get);
6619 
6620 /**
6621  * ring_buffer_subbuf_order_get - get order of system sub pages in one buffer page.
6622  * @buffer: The ring_buffer to get the system sub page order from
6623  *
6624  * By default, one ring buffer sub page equals to one system page. This parameter
6625  * is configurable, per ring buffer. The size of the ring buffer sub page can be
6626  * extended, but must be an order of system page size.
6627  *
6628  * Returns the order of buffer sub page size, in system pages:
6629  * 0 means the sub buffer size is 1 system page and so forth.
6630  * In case of an error < 0 is returned.
6631  */
ring_buffer_subbuf_order_get(struct trace_buffer * buffer)6632 int ring_buffer_subbuf_order_get(struct trace_buffer *buffer)
6633 {
6634 	if (!buffer)
6635 		return -EINVAL;
6636 
6637 	return buffer->subbuf_order;
6638 }
6639 EXPORT_SYMBOL_GPL(ring_buffer_subbuf_order_get);
6640 
6641 /**
6642  * ring_buffer_subbuf_order_set - set the size of ring buffer sub page.
6643  * @buffer: The ring_buffer to set the new page size.
6644  * @order: Order of the system pages in one sub buffer page
6645  *
6646  * By default, one ring buffer pages equals to one system page. This API can be
6647  * used to set new size of the ring buffer page. The size must be order of
6648  * system page size, that's why the input parameter @order is the order of
6649  * system pages that are allocated for one ring buffer page:
6650  *  0 - 1 system page
6651  *  1 - 2 system pages
6652  *  3 - 4 system pages
6653  *  ...
6654  *
6655  * Returns 0 on success or < 0 in case of an error.
6656  */
ring_buffer_subbuf_order_set(struct trace_buffer * buffer,int order)6657 int ring_buffer_subbuf_order_set(struct trace_buffer *buffer, int order)
6658 {
6659 	struct ring_buffer_per_cpu *cpu_buffer;
6660 	struct buffer_page *bpage, *tmp;
6661 	int old_order, old_size;
6662 	int nr_pages;
6663 	int psize;
6664 	int err;
6665 	int cpu;
6666 
6667 	if (!buffer || order < 0)
6668 		return -EINVAL;
6669 
6670 	if (buffer->subbuf_order == order)
6671 		return 0;
6672 
6673 	psize = (1 << order) * PAGE_SIZE;
6674 	if (psize <= BUF_PAGE_HDR_SIZE)
6675 		return -EINVAL;
6676 
6677 	/* Size of a subbuf cannot be greater than the write counter */
6678 	if (psize > RB_WRITE_MASK + 1)
6679 		return -EINVAL;
6680 
6681 	old_order = buffer->subbuf_order;
6682 	old_size = buffer->subbuf_size;
6683 
6684 	/* prevent another thread from changing buffer sizes */
6685 	mutex_lock(&buffer->mutex);
6686 	atomic_inc(&buffer->record_disabled);
6687 
6688 	/* Make sure all commits have finished */
6689 	synchronize_rcu();
6690 
6691 	buffer->subbuf_order = order;
6692 	buffer->subbuf_size = psize - BUF_PAGE_HDR_SIZE;
6693 
6694 	/* Make sure all new buffers are allocated, before deleting the old ones */
6695 	for_each_buffer_cpu(buffer, cpu) {
6696 
6697 		if (!cpumask_test_cpu(cpu, buffer->cpumask))
6698 			continue;
6699 
6700 		cpu_buffer = buffer->buffers[cpu];
6701 
6702 		if (cpu_buffer->mapped) {
6703 			err = -EBUSY;
6704 			goto error;
6705 		}
6706 
6707 		/* Update the number of pages to match the new size */
6708 		nr_pages = old_size * buffer->buffers[cpu]->nr_pages;
6709 		nr_pages = DIV_ROUND_UP(nr_pages, buffer->subbuf_size);
6710 
6711 		/* we need a minimum of two pages */
6712 		if (nr_pages < 2)
6713 			nr_pages = 2;
6714 
6715 		cpu_buffer->nr_pages_to_update = nr_pages;
6716 
6717 		/* Include the reader page */
6718 		nr_pages++;
6719 
6720 		/* Allocate the new size buffer */
6721 		INIT_LIST_HEAD(&cpu_buffer->new_pages);
6722 		if (__rb_allocate_pages(cpu_buffer, nr_pages,
6723 					&cpu_buffer->new_pages)) {
6724 			/* not enough memory for new pages */
6725 			err = -ENOMEM;
6726 			goto error;
6727 		}
6728 	}
6729 
6730 	for_each_buffer_cpu(buffer, cpu) {
6731 		struct buffer_data_page *old_free_data_page;
6732 		struct list_head old_pages;
6733 		unsigned long flags;
6734 
6735 		if (!cpumask_test_cpu(cpu, buffer->cpumask))
6736 			continue;
6737 
6738 		cpu_buffer = buffer->buffers[cpu];
6739 
6740 		raw_spin_lock_irqsave(&cpu_buffer->reader_lock, flags);
6741 
6742 		/* Clear the head bit to make the link list normal to read */
6743 		rb_head_page_deactivate(cpu_buffer);
6744 
6745 		/*
6746 		 * Collect buffers from the cpu_buffer pages list and the
6747 		 * reader_page on old_pages, so they can be freed later when not
6748 		 * under a spinlock. The pages list is a linked list with no
6749 		 * head, adding old_pages turns it into a regular list with
6750 		 * old_pages being the head.
6751 		 */
6752 		list_add(&old_pages, cpu_buffer->pages);
6753 		list_add(&cpu_buffer->reader_page->list, &old_pages);
6754 
6755 		/* One page was allocated for the reader page */
6756 		cpu_buffer->reader_page = list_entry(cpu_buffer->new_pages.next,
6757 						     struct buffer_page, list);
6758 		list_del_init(&cpu_buffer->reader_page->list);
6759 
6760 		/* Install the new pages, remove the head from the list */
6761 		cpu_buffer->pages = cpu_buffer->new_pages.next;
6762 		list_del_init(&cpu_buffer->new_pages);
6763 
6764 		cpu_buffer->head_page
6765 			= list_entry(cpu_buffer->pages, struct buffer_page, list);
6766 		cpu_buffer->tail_page = cpu_buffer->commit_page = cpu_buffer->head_page;
6767 
6768 		cpu_buffer->nr_pages = cpu_buffer->nr_pages_to_update;
6769 		cpu_buffer->nr_pages_to_update = 0;
6770 
6771 		old_free_data_page = cpu_buffer->free_page;
6772 		cpu_buffer->free_page = NULL;
6773 
6774 		rb_head_page_activate(cpu_buffer);
6775 
6776 		raw_spin_unlock_irqrestore(&cpu_buffer->reader_lock, flags);
6777 
6778 		/* Free old sub buffers */
6779 		list_for_each_entry_safe(bpage, tmp, &old_pages, list) {
6780 			list_del_init(&bpage->list);
6781 			free_buffer_page(bpage);
6782 		}
6783 		free_pages((unsigned long)old_free_data_page, old_order);
6784 
6785 		rb_check_pages(cpu_buffer);
6786 	}
6787 
6788 	atomic_dec(&buffer->record_disabled);
6789 	mutex_unlock(&buffer->mutex);
6790 
6791 	return 0;
6792 
6793 error:
6794 	buffer->subbuf_order = old_order;
6795 	buffer->subbuf_size = old_size;
6796 
6797 	atomic_dec(&buffer->record_disabled);
6798 	mutex_unlock(&buffer->mutex);
6799 
6800 	for_each_buffer_cpu(buffer, cpu) {
6801 		cpu_buffer = buffer->buffers[cpu];
6802 
6803 		if (!cpu_buffer->nr_pages_to_update)
6804 			continue;
6805 
6806 		list_for_each_entry_safe(bpage, tmp, &cpu_buffer->new_pages, list) {
6807 			list_del_init(&bpage->list);
6808 			free_buffer_page(bpage);
6809 		}
6810 	}
6811 
6812 	return err;
6813 }
6814 EXPORT_SYMBOL_GPL(ring_buffer_subbuf_order_set);
6815 
rb_alloc_meta_page(struct ring_buffer_per_cpu * cpu_buffer)6816 static int rb_alloc_meta_page(struct ring_buffer_per_cpu *cpu_buffer)
6817 {
6818 	struct page *page;
6819 
6820 	if (cpu_buffer->meta_page)
6821 		return 0;
6822 
6823 	page = alloc_page(GFP_USER | __GFP_ZERO);
6824 	if (!page)
6825 		return -ENOMEM;
6826 
6827 	cpu_buffer->meta_page = page_to_virt(page);
6828 
6829 	return 0;
6830 }
6831 
rb_free_meta_page(struct ring_buffer_per_cpu * cpu_buffer)6832 static void rb_free_meta_page(struct ring_buffer_per_cpu *cpu_buffer)
6833 {
6834 	unsigned long addr = (unsigned long)cpu_buffer->meta_page;
6835 
6836 	free_page(addr);
6837 	cpu_buffer->meta_page = NULL;
6838 }
6839 
rb_setup_ids_meta_page(struct ring_buffer_per_cpu * cpu_buffer,unsigned long * subbuf_ids)6840 static void rb_setup_ids_meta_page(struct ring_buffer_per_cpu *cpu_buffer,
6841 				   unsigned long *subbuf_ids)
6842 {
6843 	struct trace_buffer_meta *meta = cpu_buffer->meta_page;
6844 	unsigned int nr_subbufs = cpu_buffer->nr_pages + 1;
6845 	struct buffer_page *first_subbuf, *subbuf;
6846 	int id = 0;
6847 
6848 	subbuf_ids[id] = (unsigned long)cpu_buffer->reader_page->page;
6849 	cpu_buffer->reader_page->id = id++;
6850 
6851 	first_subbuf = subbuf = rb_set_head_page(cpu_buffer);
6852 	do {
6853 		if (WARN_ON(id >= nr_subbufs))
6854 			break;
6855 
6856 		subbuf_ids[id] = (unsigned long)subbuf->page;
6857 		subbuf->id = id;
6858 
6859 		rb_inc_page(&subbuf);
6860 		id++;
6861 	} while (subbuf != first_subbuf);
6862 
6863 	/* install subbuf ID to kern VA translation */
6864 	cpu_buffer->subbuf_ids = subbuf_ids;
6865 
6866 	meta->meta_struct_len = sizeof(*meta);
6867 	meta->nr_subbufs = nr_subbufs;
6868 	meta->subbuf_size = cpu_buffer->buffer->subbuf_size + BUF_PAGE_HDR_SIZE;
6869 	meta->meta_page_size = meta->subbuf_size;
6870 
6871 	rb_update_meta_page(cpu_buffer);
6872 }
6873 
6874 static struct ring_buffer_per_cpu *
rb_get_mapped_buffer(struct trace_buffer * buffer,int cpu)6875 rb_get_mapped_buffer(struct trace_buffer *buffer, int cpu)
6876 {
6877 	struct ring_buffer_per_cpu *cpu_buffer;
6878 
6879 	if (!cpumask_test_cpu(cpu, buffer->cpumask))
6880 		return ERR_PTR(-EINVAL);
6881 
6882 	cpu_buffer = buffer->buffers[cpu];
6883 
6884 	mutex_lock(&cpu_buffer->mapping_lock);
6885 
6886 	if (!cpu_buffer->user_mapped) {
6887 		mutex_unlock(&cpu_buffer->mapping_lock);
6888 		return ERR_PTR(-ENODEV);
6889 	}
6890 
6891 	return cpu_buffer;
6892 }
6893 
rb_put_mapped_buffer(struct ring_buffer_per_cpu * cpu_buffer)6894 static void rb_put_mapped_buffer(struct ring_buffer_per_cpu *cpu_buffer)
6895 {
6896 	mutex_unlock(&cpu_buffer->mapping_lock);
6897 }
6898 
6899 /*
6900  * Fast-path for rb_buffer_(un)map(). Called whenever the meta-page doesn't need
6901  * to be set-up or torn-down.
6902  */
__rb_inc_dec_mapped(struct ring_buffer_per_cpu * cpu_buffer,bool inc)6903 static int __rb_inc_dec_mapped(struct ring_buffer_per_cpu *cpu_buffer,
6904 			       bool inc)
6905 {
6906 	unsigned long flags;
6907 
6908 	lockdep_assert_held(&cpu_buffer->mapping_lock);
6909 
6910 	/* mapped is always greater or equal to user_mapped */
6911 	if (WARN_ON(cpu_buffer->mapped < cpu_buffer->user_mapped))
6912 		return -EINVAL;
6913 
6914 	if (inc && cpu_buffer->mapped == UINT_MAX)
6915 		return -EBUSY;
6916 
6917 	if (WARN_ON(!inc && cpu_buffer->user_mapped == 0))
6918 		return -EINVAL;
6919 
6920 	mutex_lock(&cpu_buffer->buffer->mutex);
6921 	raw_spin_lock_irqsave(&cpu_buffer->reader_lock, flags);
6922 
6923 	if (inc) {
6924 		cpu_buffer->user_mapped++;
6925 		cpu_buffer->mapped++;
6926 	} else {
6927 		cpu_buffer->user_mapped--;
6928 		cpu_buffer->mapped--;
6929 	}
6930 
6931 	raw_spin_unlock_irqrestore(&cpu_buffer->reader_lock, flags);
6932 	mutex_unlock(&cpu_buffer->buffer->mutex);
6933 
6934 	return 0;
6935 }
6936 
6937 /*
6938  *   +--------------+  pgoff == 0
6939  *   |   meta page  |
6940  *   +--------------+  pgoff == 1
6941  *   | subbuffer 0  |
6942  *   |              |
6943  *   +--------------+  pgoff == (1 + (1 << subbuf_order))
6944  *   | subbuffer 1  |
6945  *   |              |
6946  *         ...
6947  */
6948 #ifdef CONFIG_MMU
__rb_map_vma(struct ring_buffer_per_cpu * cpu_buffer,struct vm_area_struct * vma)6949 static int __rb_map_vma(struct ring_buffer_per_cpu *cpu_buffer,
6950 			struct vm_area_struct *vma)
6951 {
6952 	unsigned long nr_subbufs, nr_pages, nr_vma_pages, pgoff = vma->vm_pgoff;
6953 	unsigned int subbuf_pages, subbuf_order;
6954 	struct page **pages;
6955 	int p = 0, s = 0;
6956 	int err;
6957 
6958 	/* Refuse MP_PRIVATE or writable mappings */
6959 	if (vma->vm_flags & VM_WRITE || vma->vm_flags & VM_EXEC ||
6960 	    !(vma->vm_flags & VM_MAYSHARE))
6961 		return -EPERM;
6962 
6963 	subbuf_order = cpu_buffer->buffer->subbuf_order;
6964 	subbuf_pages = 1 << subbuf_order;
6965 
6966 	if (subbuf_order && pgoff % subbuf_pages)
6967 		return -EINVAL;
6968 
6969 	/*
6970 	 * Make sure the mapping cannot become writable later. Also tell the VM
6971 	 * to not touch these pages (VM_DONTCOPY | VM_DONTEXPAND).
6972 	 */
6973 	vm_flags_mod(vma, VM_DONTCOPY | VM_DONTEXPAND | VM_DONTDUMP,
6974 		     VM_MAYWRITE);
6975 
6976 	lockdep_assert_held(&cpu_buffer->mapping_lock);
6977 
6978 	nr_subbufs = cpu_buffer->nr_pages + 1; /* + reader-subbuf */
6979 	nr_pages = ((nr_subbufs + 1) << subbuf_order) - pgoff; /* + meta-page */
6980 
6981 	nr_vma_pages = vma_pages(vma);
6982 	if (!nr_vma_pages || nr_vma_pages > nr_pages)
6983 		return -EINVAL;
6984 
6985 	nr_pages = nr_vma_pages;
6986 
6987 	pages = kcalloc(nr_pages, sizeof(*pages), GFP_KERNEL);
6988 	if (!pages)
6989 		return -ENOMEM;
6990 
6991 	if (!pgoff) {
6992 		unsigned long meta_page_padding;
6993 
6994 		pages[p++] = virt_to_page(cpu_buffer->meta_page);
6995 
6996 		/*
6997 		 * Pad with the zero-page to align the meta-page with the
6998 		 * sub-buffers.
6999 		 */
7000 		meta_page_padding = subbuf_pages - 1;
7001 		while (meta_page_padding-- && p < nr_pages) {
7002 			unsigned long __maybe_unused zero_addr =
7003 				vma->vm_start + (PAGE_SIZE * p);
7004 
7005 			pages[p++] = ZERO_PAGE(zero_addr);
7006 		}
7007 	} else {
7008 		/* Skip the meta-page */
7009 		pgoff -= subbuf_pages;
7010 
7011 		s += pgoff / subbuf_pages;
7012 	}
7013 
7014 	while (p < nr_pages) {
7015 		struct page *page = virt_to_page((void *)cpu_buffer->subbuf_ids[s]);
7016 		int off = 0;
7017 
7018 		if (WARN_ON_ONCE(s >= nr_subbufs)) {
7019 			err = -EINVAL;
7020 			goto out;
7021 		}
7022 
7023 		for (; off < (1 << (subbuf_order)); off++, page++) {
7024 			if (p >= nr_pages)
7025 				break;
7026 
7027 			pages[p++] = page;
7028 		}
7029 		s++;
7030 	}
7031 
7032 	err = vm_insert_pages(vma, vma->vm_start, pages, &nr_pages);
7033 
7034 out:
7035 	kfree(pages);
7036 
7037 	return err;
7038 }
7039 #else
__rb_map_vma(struct ring_buffer_per_cpu * cpu_buffer,struct vm_area_struct * vma)7040 static int __rb_map_vma(struct ring_buffer_per_cpu *cpu_buffer,
7041 			struct vm_area_struct *vma)
7042 {
7043 	return -EOPNOTSUPP;
7044 }
7045 #endif
7046 
ring_buffer_map(struct trace_buffer * buffer,int cpu,struct vm_area_struct * vma)7047 int ring_buffer_map(struct trace_buffer *buffer, int cpu,
7048 		    struct vm_area_struct *vma)
7049 {
7050 	struct ring_buffer_per_cpu *cpu_buffer;
7051 	unsigned long flags, *subbuf_ids;
7052 	int err = 0;
7053 
7054 	if (!cpumask_test_cpu(cpu, buffer->cpumask))
7055 		return -EINVAL;
7056 
7057 	cpu_buffer = buffer->buffers[cpu];
7058 
7059 	mutex_lock(&cpu_buffer->mapping_lock);
7060 
7061 	if (cpu_buffer->user_mapped) {
7062 		err = __rb_map_vma(cpu_buffer, vma);
7063 		if (!err)
7064 			err = __rb_inc_dec_mapped(cpu_buffer, true);
7065 		mutex_unlock(&cpu_buffer->mapping_lock);
7066 		return err;
7067 	}
7068 
7069 	/* prevent another thread from changing buffer/sub-buffer sizes */
7070 	mutex_lock(&buffer->mutex);
7071 
7072 	err = rb_alloc_meta_page(cpu_buffer);
7073 	if (err)
7074 		goto unlock;
7075 
7076 	/* subbuf_ids include the reader while nr_pages does not */
7077 	subbuf_ids = kcalloc(cpu_buffer->nr_pages + 1, sizeof(*subbuf_ids), GFP_KERNEL);
7078 	if (!subbuf_ids) {
7079 		rb_free_meta_page(cpu_buffer);
7080 		err = -ENOMEM;
7081 		goto unlock;
7082 	}
7083 
7084 	atomic_inc(&cpu_buffer->resize_disabled);
7085 
7086 	/*
7087 	 * Lock all readers to block any subbuf swap until the subbuf IDs are
7088 	 * assigned.
7089 	 */
7090 	raw_spin_lock_irqsave(&cpu_buffer->reader_lock, flags);
7091 	rb_setup_ids_meta_page(cpu_buffer, subbuf_ids);
7092 
7093 	raw_spin_unlock_irqrestore(&cpu_buffer->reader_lock, flags);
7094 
7095 	err = __rb_map_vma(cpu_buffer, vma);
7096 	if (!err) {
7097 		raw_spin_lock_irqsave(&cpu_buffer->reader_lock, flags);
7098 		/* This is the first time it is mapped by user */
7099 		cpu_buffer->mapped++;
7100 		cpu_buffer->user_mapped = 1;
7101 		raw_spin_unlock_irqrestore(&cpu_buffer->reader_lock, flags);
7102 	} else {
7103 		kfree(cpu_buffer->subbuf_ids);
7104 		cpu_buffer->subbuf_ids = NULL;
7105 		rb_free_meta_page(cpu_buffer);
7106 	}
7107 
7108 unlock:
7109 	mutex_unlock(&buffer->mutex);
7110 	mutex_unlock(&cpu_buffer->mapping_lock);
7111 
7112 	return err;
7113 }
7114 
ring_buffer_unmap(struct trace_buffer * buffer,int cpu)7115 int ring_buffer_unmap(struct trace_buffer *buffer, int cpu)
7116 {
7117 	struct ring_buffer_per_cpu *cpu_buffer;
7118 	unsigned long flags;
7119 	int err = 0;
7120 
7121 	if (!cpumask_test_cpu(cpu, buffer->cpumask))
7122 		return -EINVAL;
7123 
7124 	cpu_buffer = buffer->buffers[cpu];
7125 
7126 	mutex_lock(&cpu_buffer->mapping_lock);
7127 
7128 	if (!cpu_buffer->user_mapped) {
7129 		err = -ENODEV;
7130 		goto out;
7131 	} else if (cpu_buffer->user_mapped > 1) {
7132 		__rb_inc_dec_mapped(cpu_buffer, false);
7133 		goto out;
7134 	}
7135 
7136 	mutex_lock(&buffer->mutex);
7137 	raw_spin_lock_irqsave(&cpu_buffer->reader_lock, flags);
7138 
7139 	/* This is the last user space mapping */
7140 	if (!WARN_ON_ONCE(cpu_buffer->mapped < cpu_buffer->user_mapped))
7141 		cpu_buffer->mapped--;
7142 	cpu_buffer->user_mapped = 0;
7143 
7144 	raw_spin_unlock_irqrestore(&cpu_buffer->reader_lock, flags);
7145 
7146 	kfree(cpu_buffer->subbuf_ids);
7147 	cpu_buffer->subbuf_ids = NULL;
7148 	rb_free_meta_page(cpu_buffer);
7149 	atomic_dec(&cpu_buffer->resize_disabled);
7150 
7151 	mutex_unlock(&buffer->mutex);
7152 
7153 out:
7154 	mutex_unlock(&cpu_buffer->mapping_lock);
7155 
7156 	return err;
7157 }
7158 
ring_buffer_map_get_reader(struct trace_buffer * buffer,int cpu)7159 int ring_buffer_map_get_reader(struct trace_buffer *buffer, int cpu)
7160 {
7161 	struct ring_buffer_per_cpu *cpu_buffer;
7162 	struct buffer_page *reader;
7163 	unsigned long missed_events;
7164 	unsigned long reader_size;
7165 	unsigned long flags;
7166 
7167 	cpu_buffer = rb_get_mapped_buffer(buffer, cpu);
7168 	if (IS_ERR(cpu_buffer))
7169 		return (int)PTR_ERR(cpu_buffer);
7170 
7171 	raw_spin_lock_irqsave(&cpu_buffer->reader_lock, flags);
7172 
7173 consume:
7174 	if (rb_per_cpu_empty(cpu_buffer))
7175 		goto out;
7176 
7177 	reader_size = rb_page_size(cpu_buffer->reader_page);
7178 
7179 	/*
7180 	 * There are data to be read on the current reader page, we can
7181 	 * return to the caller. But before that, we assume the latter will read
7182 	 * everything. Let's update the kernel reader accordingly.
7183 	 */
7184 	if (cpu_buffer->reader_page->read < reader_size) {
7185 		while (cpu_buffer->reader_page->read < reader_size)
7186 			rb_advance_reader(cpu_buffer);
7187 		goto out;
7188 	}
7189 
7190 	reader = rb_get_reader_page(cpu_buffer);
7191 	if (WARN_ON(!reader))
7192 		goto out;
7193 
7194 	/* Check if any events were dropped */
7195 	missed_events = cpu_buffer->lost_events;
7196 
7197 	if (cpu_buffer->reader_page != cpu_buffer->commit_page) {
7198 		if (missed_events) {
7199 			struct buffer_data_page *bpage = reader->page;
7200 			unsigned int commit;
7201 			/*
7202 			 * Use the real_end for the data size,
7203 			 * This gives us a chance to store the lost events
7204 			 * on the page.
7205 			 */
7206 			if (reader->real_end)
7207 				local_set(&bpage->commit, reader->real_end);
7208 			/*
7209 			 * If there is room at the end of the page to save the
7210 			 * missed events, then record it there.
7211 			 */
7212 			commit = rb_page_size(reader);
7213 			if (buffer->subbuf_size - commit >= sizeof(missed_events)) {
7214 				memcpy(&bpage->data[commit], &missed_events,
7215 				       sizeof(missed_events));
7216 				local_add(RB_MISSED_STORED, &bpage->commit);
7217 			}
7218 			local_add(RB_MISSED_EVENTS, &bpage->commit);
7219 		}
7220 	} else {
7221 		/*
7222 		 * There really shouldn't be any missed events if the commit
7223 		 * is on the reader page.
7224 		 */
7225 		WARN_ON_ONCE(missed_events);
7226 	}
7227 
7228 	cpu_buffer->lost_events = 0;
7229 
7230 	goto consume;
7231 
7232 out:
7233 	/* Some archs do not have data cache coherency between kernel and user-space */
7234 	flush_dcache_folio(virt_to_folio(cpu_buffer->reader_page->page));
7235 
7236 	rb_update_meta_page(cpu_buffer);
7237 
7238 	raw_spin_unlock_irqrestore(&cpu_buffer->reader_lock, flags);
7239 	rb_put_mapped_buffer(cpu_buffer);
7240 
7241 	return 0;
7242 }
7243 
7244 /*
7245  * We only allocate new buffers, never free them if the CPU goes down.
7246  * If we were to free the buffer, then the user would lose any trace that was in
7247  * the buffer.
7248  */
trace_rb_cpu_prepare(unsigned int cpu,struct hlist_node * node)7249 int trace_rb_cpu_prepare(unsigned int cpu, struct hlist_node *node)
7250 {
7251 	struct trace_buffer *buffer;
7252 	long nr_pages_same;
7253 	int cpu_i;
7254 	unsigned long nr_pages;
7255 
7256 	buffer = container_of(node, struct trace_buffer, node);
7257 	if (cpumask_test_cpu(cpu, buffer->cpumask))
7258 		return 0;
7259 
7260 	nr_pages = 0;
7261 	nr_pages_same = 1;
7262 	/* check if all cpu sizes are same */
7263 	for_each_buffer_cpu(buffer, cpu_i) {
7264 		/* fill in the size from first enabled cpu */
7265 		if (nr_pages == 0)
7266 			nr_pages = buffer->buffers[cpu_i]->nr_pages;
7267 		if (nr_pages != buffer->buffers[cpu_i]->nr_pages) {
7268 			nr_pages_same = 0;
7269 			break;
7270 		}
7271 	}
7272 	/* allocate minimum pages, user can later expand it */
7273 	if (!nr_pages_same)
7274 		nr_pages = 2;
7275 	buffer->buffers[cpu] =
7276 		rb_allocate_cpu_buffer(buffer, nr_pages, cpu);
7277 	if (!buffer->buffers[cpu]) {
7278 		WARN(1, "failed to allocate ring buffer on CPU %u\n",
7279 		     cpu);
7280 		return -ENOMEM;
7281 	}
7282 	smp_wmb();
7283 	cpumask_set_cpu(cpu, buffer->cpumask);
7284 	return 0;
7285 }
7286 
7287 #ifdef CONFIG_RING_BUFFER_STARTUP_TEST
7288 /*
7289  * This is a basic integrity check of the ring buffer.
7290  * Late in the boot cycle this test will run when configured in.
7291  * It will kick off a thread per CPU that will go into a loop
7292  * writing to the per cpu ring buffer various sizes of data.
7293  * Some of the data will be large items, some small.
7294  *
7295  * Another thread is created that goes into a spin, sending out
7296  * IPIs to the other CPUs to also write into the ring buffer.
7297  * this is to test the nesting ability of the buffer.
7298  *
7299  * Basic stats are recorded and reported. If something in the
7300  * ring buffer should happen that's not expected, a big warning
7301  * is displayed and all ring buffers are disabled.
7302  */
7303 static struct task_struct *rb_threads[NR_CPUS] __initdata;
7304 
7305 struct rb_test_data {
7306 	struct trace_buffer *buffer;
7307 	unsigned long		events;
7308 	unsigned long		bytes_written;
7309 	unsigned long		bytes_alloc;
7310 	unsigned long		bytes_dropped;
7311 	unsigned long		events_nested;
7312 	unsigned long		bytes_written_nested;
7313 	unsigned long		bytes_alloc_nested;
7314 	unsigned long		bytes_dropped_nested;
7315 	int			min_size_nested;
7316 	int			max_size_nested;
7317 	int			max_size;
7318 	int			min_size;
7319 	int			cpu;
7320 	int			cnt;
7321 };
7322 
7323 static struct rb_test_data rb_data[NR_CPUS] __initdata;
7324 
7325 /* 1 meg per cpu */
7326 #define RB_TEST_BUFFER_SIZE	1048576
7327 
7328 static char rb_string[] __initdata =
7329 	"abcdefghijklmnopqrstuvwxyz1234567890!@#$%^&*()?+\\"
7330 	"?+|:';\",.<>/?abcdefghijklmnopqrstuvwxyz1234567890"
7331 	"!@#$%^&*()?+\\?+|:';\",.<>/?abcdefghijklmnopqrstuv";
7332 
7333 static bool rb_test_started __initdata;
7334 
7335 struct rb_item {
7336 	int size;
7337 	char str[];
7338 };
7339 
rb_write_something(struct rb_test_data * data,bool nested)7340 static __init int rb_write_something(struct rb_test_data *data, bool nested)
7341 {
7342 	struct ring_buffer_event *event;
7343 	struct rb_item *item;
7344 	bool started;
7345 	int event_len;
7346 	int size;
7347 	int len;
7348 	int cnt;
7349 
7350 	/* Have nested writes different that what is written */
7351 	cnt = data->cnt + (nested ? 27 : 0);
7352 
7353 	/* Multiply cnt by ~e, to make some unique increment */
7354 	size = (cnt * 68 / 25) % (sizeof(rb_string) - 1);
7355 
7356 	len = size + sizeof(struct rb_item);
7357 
7358 	started = rb_test_started;
7359 	/* read rb_test_started before checking buffer enabled */
7360 	smp_rmb();
7361 
7362 	event = ring_buffer_lock_reserve(data->buffer, len);
7363 	if (!event) {
7364 		/* Ignore dropped events before test starts. */
7365 		if (started) {
7366 			if (nested)
7367 				data->bytes_dropped += len;
7368 			else
7369 				data->bytes_dropped_nested += len;
7370 		}
7371 		return len;
7372 	}
7373 
7374 	event_len = ring_buffer_event_length(event);
7375 
7376 	if (RB_WARN_ON(data->buffer, event_len < len))
7377 		goto out;
7378 
7379 	item = ring_buffer_event_data(event);
7380 	item->size = size;
7381 	memcpy(item->str, rb_string, size);
7382 
7383 	if (nested) {
7384 		data->bytes_alloc_nested += event_len;
7385 		data->bytes_written_nested += len;
7386 		data->events_nested++;
7387 		if (!data->min_size_nested || len < data->min_size_nested)
7388 			data->min_size_nested = len;
7389 		if (len > data->max_size_nested)
7390 			data->max_size_nested = len;
7391 	} else {
7392 		data->bytes_alloc += event_len;
7393 		data->bytes_written += len;
7394 		data->events++;
7395 		if (!data->min_size || len < data->min_size)
7396 			data->max_size = len;
7397 		if (len > data->max_size)
7398 			data->max_size = len;
7399 	}
7400 
7401  out:
7402 	ring_buffer_unlock_commit(data->buffer);
7403 
7404 	return 0;
7405 }
7406 
rb_test(void * arg)7407 static __init int rb_test(void *arg)
7408 {
7409 	struct rb_test_data *data = arg;
7410 
7411 	while (!kthread_should_stop()) {
7412 		rb_write_something(data, false);
7413 		data->cnt++;
7414 
7415 		set_current_state(TASK_INTERRUPTIBLE);
7416 		/* Now sleep between a min of 100-300us and a max of 1ms */
7417 		usleep_range(((data->cnt % 3) + 1) * 100, 1000);
7418 	}
7419 
7420 	return 0;
7421 }
7422 
rb_ipi(void * ignore)7423 static __init void rb_ipi(void *ignore)
7424 {
7425 	struct rb_test_data *data;
7426 	int cpu = smp_processor_id();
7427 
7428 	data = &rb_data[cpu];
7429 	rb_write_something(data, true);
7430 }
7431 
rb_hammer_test(void * arg)7432 static __init int rb_hammer_test(void *arg)
7433 {
7434 	while (!kthread_should_stop()) {
7435 
7436 		/* Send an IPI to all cpus to write data! */
7437 		smp_call_function(rb_ipi, NULL, 1);
7438 		/* No sleep, but for non preempt, let others run */
7439 		schedule();
7440 	}
7441 
7442 	return 0;
7443 }
7444 
test_ringbuffer(void)7445 static __init int test_ringbuffer(void)
7446 {
7447 	struct task_struct *rb_hammer;
7448 	struct trace_buffer *buffer;
7449 	int cpu;
7450 	int ret = 0;
7451 
7452 	if (security_locked_down(LOCKDOWN_TRACEFS)) {
7453 		pr_warn("Lockdown is enabled, skipping ring buffer tests\n");
7454 		return 0;
7455 	}
7456 
7457 	pr_info("Running ring buffer tests...\n");
7458 
7459 	buffer = ring_buffer_alloc(RB_TEST_BUFFER_SIZE, RB_FL_OVERWRITE);
7460 	if (WARN_ON(!buffer))
7461 		return 0;
7462 
7463 	/* Disable buffer so that threads can't write to it yet */
7464 	ring_buffer_record_off(buffer);
7465 
7466 	for_each_online_cpu(cpu) {
7467 		rb_data[cpu].buffer = buffer;
7468 		rb_data[cpu].cpu = cpu;
7469 		rb_data[cpu].cnt = cpu;
7470 		rb_threads[cpu] = kthread_run_on_cpu(rb_test, &rb_data[cpu],
7471 						     cpu, "rbtester/%u");
7472 		if (WARN_ON(IS_ERR(rb_threads[cpu]))) {
7473 			pr_cont("FAILED\n");
7474 			ret = PTR_ERR(rb_threads[cpu]);
7475 			goto out_free;
7476 		}
7477 	}
7478 
7479 	/* Now create the rb hammer! */
7480 	rb_hammer = kthread_run(rb_hammer_test, NULL, "rbhammer");
7481 	if (WARN_ON(IS_ERR(rb_hammer))) {
7482 		pr_cont("FAILED\n");
7483 		ret = PTR_ERR(rb_hammer);
7484 		goto out_free;
7485 	}
7486 
7487 	ring_buffer_record_on(buffer);
7488 	/*
7489 	 * Show buffer is enabled before setting rb_test_started.
7490 	 * Yes there's a small race window where events could be
7491 	 * dropped and the thread wont catch it. But when a ring
7492 	 * buffer gets enabled, there will always be some kind of
7493 	 * delay before other CPUs see it. Thus, we don't care about
7494 	 * those dropped events. We care about events dropped after
7495 	 * the threads see that the buffer is active.
7496 	 */
7497 	smp_wmb();
7498 	rb_test_started = true;
7499 
7500 	set_current_state(TASK_INTERRUPTIBLE);
7501 	/* Just run for 10 seconds */;
7502 	schedule_timeout(10 * HZ);
7503 
7504 	kthread_stop(rb_hammer);
7505 
7506  out_free:
7507 	for_each_online_cpu(cpu) {
7508 		if (!rb_threads[cpu])
7509 			break;
7510 		kthread_stop(rb_threads[cpu]);
7511 	}
7512 	if (ret) {
7513 		ring_buffer_free(buffer);
7514 		return ret;
7515 	}
7516 
7517 	/* Report! */
7518 	pr_info("finished\n");
7519 	for_each_online_cpu(cpu) {
7520 		struct ring_buffer_event *event;
7521 		struct rb_test_data *data = &rb_data[cpu];
7522 		struct rb_item *item;
7523 		unsigned long total_events;
7524 		unsigned long total_dropped;
7525 		unsigned long total_written;
7526 		unsigned long total_alloc;
7527 		unsigned long total_read = 0;
7528 		unsigned long total_size = 0;
7529 		unsigned long total_len = 0;
7530 		unsigned long total_lost = 0;
7531 		unsigned long lost;
7532 		int big_event_size;
7533 		int small_event_size;
7534 
7535 		ret = -1;
7536 
7537 		total_events = data->events + data->events_nested;
7538 		total_written = data->bytes_written + data->bytes_written_nested;
7539 		total_alloc = data->bytes_alloc + data->bytes_alloc_nested;
7540 		total_dropped = data->bytes_dropped + data->bytes_dropped_nested;
7541 
7542 		big_event_size = data->max_size + data->max_size_nested;
7543 		small_event_size = data->min_size + data->min_size_nested;
7544 
7545 		pr_info("CPU %d:\n", cpu);
7546 		pr_info("              events:    %ld\n", total_events);
7547 		pr_info("       dropped bytes:    %ld\n", total_dropped);
7548 		pr_info("       alloced bytes:    %ld\n", total_alloc);
7549 		pr_info("       written bytes:    %ld\n", total_written);
7550 		pr_info("       biggest event:    %d\n", big_event_size);
7551 		pr_info("      smallest event:    %d\n", small_event_size);
7552 
7553 		if (RB_WARN_ON(buffer, total_dropped))
7554 			break;
7555 
7556 		ret = 0;
7557 
7558 		while ((event = ring_buffer_consume(buffer, cpu, NULL, &lost))) {
7559 			total_lost += lost;
7560 			item = ring_buffer_event_data(event);
7561 			total_len += ring_buffer_event_length(event);
7562 			total_size += item->size + sizeof(struct rb_item);
7563 			if (memcmp(&item->str[0], rb_string, item->size) != 0) {
7564 				pr_info("FAILED!\n");
7565 				pr_info("buffer had: %.*s\n", item->size, item->str);
7566 				pr_info("expected:   %.*s\n", item->size, rb_string);
7567 				RB_WARN_ON(buffer, 1);
7568 				ret = -1;
7569 				break;
7570 			}
7571 			total_read++;
7572 		}
7573 		if (ret)
7574 			break;
7575 
7576 		ret = -1;
7577 
7578 		pr_info("         read events:   %ld\n", total_read);
7579 		pr_info("         lost events:   %ld\n", total_lost);
7580 		pr_info("        total events:   %ld\n", total_lost + total_read);
7581 		pr_info("  recorded len bytes:   %ld\n", total_len);
7582 		pr_info(" recorded size bytes:   %ld\n", total_size);
7583 		if (total_lost) {
7584 			pr_info(" With dropped events, record len and size may not match\n"
7585 				" alloced and written from above\n");
7586 		} else {
7587 			if (RB_WARN_ON(buffer, total_len != total_alloc ||
7588 				       total_size != total_written))
7589 				break;
7590 		}
7591 		if (RB_WARN_ON(buffer, total_lost + total_read != total_events))
7592 			break;
7593 
7594 		ret = 0;
7595 	}
7596 	if (!ret)
7597 		pr_info("Ring buffer PASSED!\n");
7598 
7599 	ring_buffer_free(buffer);
7600 	return 0;
7601 }
7602 
7603 late_initcall(test_ringbuffer);
7604 #endif /* CONFIG_RING_BUFFER_STARTUP_TEST */
7605