• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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_events.h>
8 #include <linux/ring_buffer.h>
9 #include <linux/trace_clock.h>
10 #include <linux/sched/clock.h>
11 #include <linux/trace_seq.h>
12 #include <linux/spinlock.h>
13 #include <linux/irq_work.h>
14 #include <linux/security.h>
15 #include <linux/uaccess.h>
16 #include <linux/hardirq.h>
17 #include <linux/kthread.h>	/* for self test */
18 #include <linux/module.h>
19 #include <linux/percpu.h>
20 #include <linux/mutex.h>
21 #include <linux/delay.h>
22 #include <linux/slab.h>
23 #include <linux/init.h>
24 #include <linux/hash.h>
25 #include <linux/list.h>
26 #include <linux/cpu.h>
27 #include <linux/oom.h>
28 
29 #include <asm/local.h>
30 
31 static void update_pages_handler(struct work_struct *work);
32 
33 /*
34  * The ring buffer header is special. We must manually up keep it.
35  */
ring_buffer_print_entry_header(struct trace_seq * s)36 int ring_buffer_print_entry_header(struct trace_seq *s)
37 {
38 	trace_seq_puts(s, "# compressed entry header\n");
39 	trace_seq_puts(s, "\ttype_len    :    5 bits\n");
40 	trace_seq_puts(s, "\ttime_delta  :   27 bits\n");
41 	trace_seq_puts(s, "\tarray       :   32 bits\n");
42 	trace_seq_putc(s, '\n');
43 	trace_seq_printf(s, "\tpadding     : type == %d\n",
44 			 RINGBUF_TYPE_PADDING);
45 	trace_seq_printf(s, "\ttime_extend : type == %d\n",
46 			 RINGBUF_TYPE_TIME_EXTEND);
47 	trace_seq_printf(s, "\ttime_stamp : type == %d\n",
48 			 RINGBUF_TYPE_TIME_STAMP);
49 	trace_seq_printf(s, "\tdata max type_len  == %d\n",
50 			 RINGBUF_TYPE_DATA_TYPE_LEN_MAX);
51 
52 	return !trace_seq_has_overflowed(s);
53 }
54 
55 /*
56  * The ring buffer is made up of a list of pages. A separate list of pages is
57  * allocated for each CPU. A writer may only write to a buffer that is
58  * associated with the CPU it is currently executing on.  A reader may read
59  * from any per cpu buffer.
60  *
61  * The reader is special. For each per cpu buffer, the reader has its own
62  * reader page. When a reader has read the entire reader page, this reader
63  * page is swapped with another page in the ring buffer.
64  *
65  * Now, as long as the writer is off the reader page, the reader can do what
66  * ever it wants with that page. The writer will never write to that page
67  * again (as long as it is out of the ring buffer).
68  *
69  * Here's some silly ASCII art.
70  *
71  *   +------+
72  *   |reader|          RING BUFFER
73  *   |page  |
74  *   +------+        +---+   +---+   +---+
75  *                   |   |-->|   |-->|   |
76  *                   +---+   +---+   +---+
77  *                     ^               |
78  *                     |               |
79  *                     +---------------+
80  *
81  *
82  *   +------+
83  *   |reader|          RING BUFFER
84  *   |page  |------------------v
85  *   +------+        +---+   +---+   +---+
86  *                   |   |-->|   |-->|   |
87  *                   +---+   +---+   +---+
88  *                     ^               |
89  *                     |               |
90  *                     +---------------+
91  *
92  *
93  *   +------+
94  *   |reader|          RING BUFFER
95  *   |page  |------------------v
96  *   +------+        +---+   +---+   +---+
97  *      ^            |   |-->|   |-->|   |
98  *      |            +---+   +---+   +---+
99  *      |                              |
100  *      |                              |
101  *      +------------------------------+
102  *
103  *
104  *   +------+
105  *   |buffer|          RING BUFFER
106  *   |page  |------------------v
107  *   +------+        +---+   +---+   +---+
108  *      ^            |   |   |   |-->|   |
109  *      |   New      +---+   +---+   +---+
110  *      |  Reader------^               |
111  *      |   page                       |
112  *      +------------------------------+
113  *
114  *
115  * After we make this swap, the reader can hand this page off to the splice
116  * code and be done with it. It can even allocate a new page if it needs to
117  * and swap that into the ring buffer.
118  *
119  * We will be using cmpxchg soon to make all this lockless.
120  *
121  */
122 
123 /* Used for individual buffers (after the counter) */
124 #define RB_BUFFER_OFF		(1 << 20)
125 
126 #define BUF_PAGE_HDR_SIZE offsetof(struct buffer_data_page, data)
127 
128 #define RB_EVNT_HDR_SIZE (offsetof(struct ring_buffer_event, array))
129 #define RB_ALIGNMENT		4U
130 #define RB_MAX_SMALL_DATA	(RB_ALIGNMENT * RINGBUF_TYPE_DATA_TYPE_LEN_MAX)
131 #define RB_EVNT_MIN_SIZE	8U	/* two 32bit words */
132 
133 #ifndef CONFIG_HAVE_64BIT_ALIGNED_ACCESS
134 # define RB_FORCE_8BYTE_ALIGNMENT	0
135 # define RB_ARCH_ALIGNMENT		RB_ALIGNMENT
136 #else
137 # define RB_FORCE_8BYTE_ALIGNMENT	1
138 # define RB_ARCH_ALIGNMENT		8U
139 #endif
140 
141 #define RB_ALIGN_DATA		__aligned(RB_ARCH_ALIGNMENT)
142 
143 /* define RINGBUF_TYPE_DATA for 'case RINGBUF_TYPE_DATA:' */
144 #define RINGBUF_TYPE_DATA 0 ... RINGBUF_TYPE_DATA_TYPE_LEN_MAX
145 
146 enum {
147 	RB_LEN_TIME_EXTEND = 8,
148 	RB_LEN_TIME_STAMP =  8,
149 };
150 
151 #define skip_time_extend(event) \
152 	((struct ring_buffer_event *)((char *)event + RB_LEN_TIME_EXTEND))
153 
154 #define extended_time(event) \
155 	(event->type_len >= RINGBUF_TYPE_TIME_EXTEND)
156 
rb_null_event(struct ring_buffer_event * event)157 static inline int rb_null_event(struct ring_buffer_event *event)
158 {
159 	return event->type_len == RINGBUF_TYPE_PADDING && !event->time_delta;
160 }
161 
rb_event_set_padding(struct ring_buffer_event * event)162 static void rb_event_set_padding(struct ring_buffer_event *event)
163 {
164 	/* padding has a NULL time_delta */
165 	event->type_len = RINGBUF_TYPE_PADDING;
166 	event->time_delta = 0;
167 }
168 
169 static unsigned
rb_event_data_length(struct ring_buffer_event * event)170 rb_event_data_length(struct ring_buffer_event *event)
171 {
172 	unsigned length;
173 
174 	if (event->type_len)
175 		length = event->type_len * RB_ALIGNMENT;
176 	else
177 		length = event->array[0];
178 	return length + RB_EVNT_HDR_SIZE;
179 }
180 
181 /*
182  * Return the length of the given event. Will return
183  * the length of the time extend if the event is a
184  * time extend.
185  */
186 static inline unsigned
rb_event_length(struct ring_buffer_event * event)187 rb_event_length(struct ring_buffer_event *event)
188 {
189 	switch (event->type_len) {
190 	case RINGBUF_TYPE_PADDING:
191 		if (rb_null_event(event))
192 			/* undefined */
193 			return -1;
194 		return  event->array[0] + RB_EVNT_HDR_SIZE;
195 
196 	case RINGBUF_TYPE_TIME_EXTEND:
197 		return RB_LEN_TIME_EXTEND;
198 
199 	case RINGBUF_TYPE_TIME_STAMP:
200 		return RB_LEN_TIME_STAMP;
201 
202 	case RINGBUF_TYPE_DATA:
203 		return rb_event_data_length(event);
204 	default:
205 		WARN_ON_ONCE(1);
206 	}
207 	/* not hit */
208 	return 0;
209 }
210 
211 /*
212  * Return total length of time extend and data,
213  *   or just the event length for all other events.
214  */
215 static inline unsigned
rb_event_ts_length(struct ring_buffer_event * event)216 rb_event_ts_length(struct ring_buffer_event *event)
217 {
218 	unsigned len = 0;
219 
220 	if (extended_time(event)) {
221 		/* time extends include the data event after it */
222 		len = RB_LEN_TIME_EXTEND;
223 		event = skip_time_extend(event);
224 	}
225 	return len + rb_event_length(event);
226 }
227 
228 /**
229  * ring_buffer_event_length - return the length of the event
230  * @event: the event to get the length of
231  *
232  * Returns the size of the data load of a data event.
233  * If the event is something other than a data event, it
234  * returns the size of the event itself. With the exception
235  * of a TIME EXTEND, where it still returns the size of the
236  * data load of the data event after it.
237  */
ring_buffer_event_length(struct ring_buffer_event * event)238 unsigned ring_buffer_event_length(struct ring_buffer_event *event)
239 {
240 	unsigned length;
241 
242 	if (extended_time(event))
243 		event = skip_time_extend(event);
244 
245 	length = rb_event_length(event);
246 	if (event->type_len > RINGBUF_TYPE_DATA_TYPE_LEN_MAX)
247 		return length;
248 	length -= RB_EVNT_HDR_SIZE;
249 	if (length > RB_MAX_SMALL_DATA + sizeof(event->array[0]))
250                 length -= sizeof(event->array[0]);
251 	return length;
252 }
253 EXPORT_SYMBOL_GPL(ring_buffer_event_length);
254 
255 /* inline for ring buffer fast paths */
256 static __always_inline void *
rb_event_data(struct ring_buffer_event * event)257 rb_event_data(struct ring_buffer_event *event)
258 {
259 	if (extended_time(event))
260 		event = skip_time_extend(event);
261 	WARN_ON_ONCE(event->type_len > RINGBUF_TYPE_DATA_TYPE_LEN_MAX);
262 	/* If length is in len field, then array[0] has the data */
263 	if (event->type_len)
264 		return (void *)&event->array[0];
265 	/* Otherwise length is in array[0] and array[1] has the data */
266 	return (void *)&event->array[1];
267 }
268 
269 /**
270  * ring_buffer_event_data - return the data of the event
271  * @event: the event to get the data from
272  */
ring_buffer_event_data(struct ring_buffer_event * event)273 void *ring_buffer_event_data(struct ring_buffer_event *event)
274 {
275 	return rb_event_data(event);
276 }
277 EXPORT_SYMBOL_GPL(ring_buffer_event_data);
278 
279 #define for_each_buffer_cpu(buffer, cpu)		\
280 	for_each_cpu(cpu, buffer->cpumask)
281 
282 #define for_each_online_buffer_cpu(buffer, cpu)		\
283 	for_each_cpu_and(cpu, buffer->cpumask, cpu_online_mask)
284 
285 #define TS_SHIFT	27
286 #define TS_MASK		((1ULL << TS_SHIFT) - 1)
287 #define TS_DELTA_TEST	(~TS_MASK)
288 
289 /**
290  * ring_buffer_event_time_stamp - return the event's extended timestamp
291  * @event: the event to get the timestamp of
292  *
293  * Returns the extended timestamp associated with a data event.
294  * An extended time_stamp is a 64-bit timestamp represented
295  * internally in a special way that makes the best use of space
296  * contained within a ring buffer event.  This function decodes
297  * it and maps it to a straight u64 value.
298  */
ring_buffer_event_time_stamp(struct ring_buffer_event * event)299 u64 ring_buffer_event_time_stamp(struct ring_buffer_event *event)
300 {
301 	u64 ts;
302 
303 	ts = event->array[0];
304 	ts <<= TS_SHIFT;
305 	ts += event->time_delta;
306 
307 	return ts;
308 }
309 
310 /* Flag when events were overwritten */
311 #define RB_MISSED_EVENTS	(1 << 31)
312 /* Missed count stored at end */
313 #define RB_MISSED_STORED	(1 << 30)
314 
315 struct buffer_data_page {
316 	u64		 time_stamp;	/* page time stamp */
317 	local_t		 commit;	/* write committed index */
318 	unsigned char	 data[] RB_ALIGN_DATA;	/* data of buffer page */
319 };
320 
321 /*
322  * Note, the buffer_page list must be first. The buffer pages
323  * are allocated in cache lines, which means that each buffer
324  * page will be at the beginning of a cache line, and thus
325  * the least significant bits will be zero. We use this to
326  * add flags in the list struct pointers, to make the ring buffer
327  * lockless.
328  */
329 struct buffer_page {
330 	struct list_head list;		/* list of buffer pages */
331 	local_t		 write;		/* index for next write */
332 	unsigned	 read;		/* index for next read */
333 	local_t		 entries;	/* entries on this page */
334 	unsigned long	 real_end;	/* real end of data */
335 	struct buffer_data_page *page;	/* Actual data page */
336 };
337 
338 /*
339  * The buffer page counters, write and entries, must be reset
340  * atomically when crossing page boundaries. To synchronize this
341  * update, two counters are inserted into the number. One is
342  * the actual counter for the write position or count on the page.
343  *
344  * The other is a counter of updaters. Before an update happens
345  * the update partition of the counter is incremented. This will
346  * allow the updater to update the counter atomically.
347  *
348  * The counter is 20 bits, and the state data is 12.
349  */
350 #define RB_WRITE_MASK		0xfffff
351 #define RB_WRITE_INTCNT		(1 << 20)
352 
rb_init_page(struct buffer_data_page * bpage)353 static void rb_init_page(struct buffer_data_page *bpage)
354 {
355 	local_set(&bpage->commit, 0);
356 }
357 
rb_page_commit(struct buffer_page * bpage)358 static __always_inline unsigned int rb_page_commit(struct buffer_page *bpage)
359 {
360 	return local_read(&bpage->page->commit);
361 }
362 
free_buffer_page(struct buffer_page * bpage)363 static void free_buffer_page(struct buffer_page *bpage)
364 {
365 	free_page((unsigned long)bpage->page);
366 	kfree(bpage);
367 }
368 
369 /*
370  * We need to fit the time_stamp delta into 27 bits.
371  */
test_time_stamp(u64 delta)372 static inline int test_time_stamp(u64 delta)
373 {
374 	if (delta & TS_DELTA_TEST)
375 		return 1;
376 	return 0;
377 }
378 
379 #define BUF_PAGE_SIZE (PAGE_SIZE - BUF_PAGE_HDR_SIZE)
380 
381 /* Max payload is BUF_PAGE_SIZE - header (8bytes) */
382 #define BUF_MAX_DATA_SIZE (BUF_PAGE_SIZE - (sizeof(u32) * 2))
383 
ring_buffer_print_page_header(struct trace_seq * s)384 int ring_buffer_print_page_header(struct trace_seq *s)
385 {
386 	struct buffer_data_page field;
387 
388 	trace_seq_printf(s, "\tfield: u64 timestamp;\t"
389 			 "offset:0;\tsize:%u;\tsigned:%u;\n",
390 			 (unsigned int)sizeof(field.time_stamp),
391 			 (unsigned int)is_signed_type(u64));
392 
393 	trace_seq_printf(s, "\tfield: local_t commit;\t"
394 			 "offset:%u;\tsize:%u;\tsigned:%u;\n",
395 			 (unsigned int)offsetof(typeof(field), commit),
396 			 (unsigned int)sizeof(field.commit),
397 			 (unsigned int)is_signed_type(long));
398 
399 	trace_seq_printf(s, "\tfield: int overwrite;\t"
400 			 "offset:%u;\tsize:%u;\tsigned:%u;\n",
401 			 (unsigned int)offsetof(typeof(field), commit),
402 			 1,
403 			 (unsigned int)is_signed_type(long));
404 
405 	trace_seq_printf(s, "\tfield: char data;\t"
406 			 "offset:%u;\tsize:%u;\tsigned:%u;\n",
407 			 (unsigned int)offsetof(typeof(field), data),
408 			 (unsigned int)BUF_PAGE_SIZE,
409 			 (unsigned int)is_signed_type(char));
410 
411 	return !trace_seq_has_overflowed(s);
412 }
413 
414 struct rb_irq_work {
415 	struct irq_work			work;
416 	wait_queue_head_t		waiters;
417 	wait_queue_head_t		full_waiters;
418 	long				wait_index;
419 	bool				waiters_pending;
420 	bool				full_waiters_pending;
421 	bool				wakeup_full;
422 };
423 
424 /*
425  * Structure to hold event state and handle nested events.
426  */
427 struct rb_event_info {
428 	u64			ts;
429 	u64			delta;
430 	u64			before;
431 	u64			after;
432 	unsigned long		length;
433 	struct buffer_page	*tail_page;
434 	int			add_timestamp;
435 };
436 
437 /*
438  * Used for the add_timestamp
439  *  NONE
440  *  EXTEND - wants a time extend
441  *  ABSOLUTE - the buffer requests all events to have absolute time stamps
442  *  FORCE - force a full time stamp.
443  */
444 enum {
445 	RB_ADD_STAMP_NONE		= 0,
446 	RB_ADD_STAMP_EXTEND		= BIT(1),
447 	RB_ADD_STAMP_ABSOLUTE		= BIT(2),
448 	RB_ADD_STAMP_FORCE		= BIT(3)
449 };
450 /*
451  * Used for which event context the event is in.
452  *  TRANSITION = 0
453  *  NMI     = 1
454  *  IRQ     = 2
455  *  SOFTIRQ = 3
456  *  NORMAL  = 4
457  *
458  * See trace_recursive_lock() comment below for more details.
459  */
460 enum {
461 	RB_CTX_TRANSITION,
462 	RB_CTX_NMI,
463 	RB_CTX_IRQ,
464 	RB_CTX_SOFTIRQ,
465 	RB_CTX_NORMAL,
466 	RB_CTX_MAX
467 };
468 
469 #if BITS_PER_LONG == 32
470 #define RB_TIME_32
471 #endif
472 
473 /* To test on 64 bit machines */
474 //#define RB_TIME_32
475 
476 #ifdef RB_TIME_32
477 
478 struct rb_time_struct {
479 	local_t		cnt;
480 	local_t		top;
481 	local_t		bottom;
482 };
483 #else
484 #include <asm/local64.h>
485 struct rb_time_struct {
486 	local64_t	time;
487 };
488 #endif
489 typedef struct rb_time_struct rb_time_t;
490 
491 /*
492  * head_page == tail_page && head == tail then buffer is empty.
493  */
494 struct ring_buffer_per_cpu {
495 	int				cpu;
496 	atomic_t			record_disabled;
497 	atomic_t			resize_disabled;
498 	struct trace_buffer	*buffer;
499 	raw_spinlock_t			reader_lock;	/* serialize readers */
500 	arch_spinlock_t			lock;
501 	struct lock_class_key		lock_key;
502 	struct buffer_data_page		*free_page;
503 	unsigned long			nr_pages;
504 	unsigned int			current_context;
505 	struct list_head		*pages;
506 	struct buffer_page		*head_page;	/* read from head */
507 	struct buffer_page		*tail_page;	/* write to tail */
508 	struct buffer_page		*commit_page;	/* committed pages */
509 	struct buffer_page		*reader_page;
510 	unsigned long			lost_events;
511 	unsigned long			last_overrun;
512 	unsigned long			nest;
513 	local_t				entries_bytes;
514 	local_t				entries;
515 	local_t				overrun;
516 	local_t				commit_overrun;
517 	local_t				dropped_events;
518 	local_t				committing;
519 	local_t				commits;
520 	local_t				pages_touched;
521 	local_t				pages_lost;
522 	local_t				pages_read;
523 	long				last_pages_touch;
524 	size_t				shortest_full;
525 	unsigned long			read;
526 	unsigned long			read_bytes;
527 	rb_time_t			write_stamp;
528 	rb_time_t			before_stamp;
529 	u64				read_stamp;
530 	/* pages removed since last reset */
531 	unsigned long			pages_removed;
532 	/* ring buffer pages to update, > 0 to add, < 0 to remove */
533 	long				nr_pages_to_update;
534 	struct list_head		new_pages; /* new pages to add */
535 	struct work_struct		update_pages_work;
536 	struct completion		update_done;
537 
538 	struct rb_irq_work		irq_work;
539 };
540 
541 struct trace_buffer {
542 	unsigned			flags;
543 	int				cpus;
544 	atomic_t			record_disabled;
545 	atomic_t			resizing;
546 	cpumask_var_t			cpumask;
547 
548 	struct lock_class_key		*reader_lock_key;
549 
550 	struct mutex			mutex;
551 
552 	struct ring_buffer_per_cpu	**buffers;
553 
554 	struct hlist_node		node;
555 	u64				(*clock)(void);
556 
557 	struct rb_irq_work		irq_work;
558 	bool				time_stamp_abs;
559 };
560 
561 struct ring_buffer_iter {
562 	struct ring_buffer_per_cpu	*cpu_buffer;
563 	unsigned long			head;
564 	unsigned long			next_event;
565 	struct buffer_page		*head_page;
566 	struct buffer_page		*cache_reader_page;
567 	unsigned long			cache_read;
568 	unsigned long			cache_pages_removed;
569 	u64				read_stamp;
570 	u64				page_stamp;
571 	struct ring_buffer_event	*event;
572 	int				missed_events;
573 };
574 
575 #ifdef RB_TIME_32
576 
577 /*
578  * On 32 bit machines, local64_t is very expensive. As the ring
579  * buffer doesn't need all the features of a true 64 bit atomic,
580  * on 32 bit, it uses these functions (64 still uses local64_t).
581  *
582  * For the ring buffer, 64 bit required operations for the time is
583  * the following:
584  *
585  *  - Only need 59 bits (uses 60 to make it even).
586  *  - Reads may fail if it interrupted a modification of the time stamp.
587  *      It will succeed if it did not interrupt another write even if
588  *      the read itself is interrupted by a write.
589  *      It returns whether it was successful or not.
590  *
591  *  - Writes always succeed and will overwrite other writes and writes
592  *      that were done by events interrupting the current write.
593  *
594  *  - A write followed by a read of the same time stamp will always succeed,
595  *      but may not contain the same value.
596  *
597  *  - A cmpxchg will fail if it interrupted another write or cmpxchg.
598  *      Other than that, it acts like a normal cmpxchg.
599  *
600  * The 60 bit time stamp is broken up by 30 bits in a top and bottom half
601  *  (bottom being the least significant 30 bits of the 60 bit time stamp).
602  *
603  * The two most significant bits of each half holds a 2 bit counter (0-3).
604  * Each update will increment this counter by one.
605  * When reading the top and bottom, if the two counter bits match then the
606  *  top and bottom together make a valid 60 bit number.
607  */
608 #define RB_TIME_SHIFT	30
609 #define RB_TIME_VAL_MASK ((1 << RB_TIME_SHIFT) - 1)
610 
rb_time_cnt(unsigned long val)611 static inline int rb_time_cnt(unsigned long val)
612 {
613 	return (val >> RB_TIME_SHIFT) & 3;
614 }
615 
rb_time_val(unsigned long top,unsigned long bottom)616 static inline u64 rb_time_val(unsigned long top, unsigned long bottom)
617 {
618 	u64 val;
619 
620 	val = top & RB_TIME_VAL_MASK;
621 	val <<= RB_TIME_SHIFT;
622 	val |= bottom & RB_TIME_VAL_MASK;
623 
624 	return val;
625 }
626 
__rb_time_read(rb_time_t * t,u64 * ret,unsigned long * cnt)627 static inline bool __rb_time_read(rb_time_t *t, u64 *ret, unsigned long *cnt)
628 {
629 	unsigned long top, bottom;
630 	unsigned long c;
631 
632 	/*
633 	 * If the read is interrupted by a write, then the cnt will
634 	 * be different. Loop until both top and bottom have been read
635 	 * without interruption.
636 	 */
637 	do {
638 		c = local_read(&t->cnt);
639 		top = local_read(&t->top);
640 		bottom = local_read(&t->bottom);
641 	} while (c != local_read(&t->cnt));
642 
643 	*cnt = rb_time_cnt(top);
644 
645 	/* If top and bottom counts don't match, this interrupted a write */
646 	if (*cnt != rb_time_cnt(bottom))
647 		return false;
648 
649 	*ret = rb_time_val(top, bottom);
650 	return true;
651 }
652 
rb_time_read(rb_time_t * t,u64 * ret)653 static bool rb_time_read(rb_time_t *t, u64 *ret)
654 {
655 	unsigned long cnt;
656 
657 	return __rb_time_read(t, ret, &cnt);
658 }
659 
rb_time_val_cnt(unsigned long val,unsigned long cnt)660 static inline unsigned long rb_time_val_cnt(unsigned long val, unsigned long cnt)
661 {
662 	return (val & RB_TIME_VAL_MASK) | ((cnt & 3) << RB_TIME_SHIFT);
663 }
664 
rb_time_split(u64 val,unsigned long * top,unsigned long * bottom)665 static inline void rb_time_split(u64 val, unsigned long *top, unsigned long *bottom)
666 {
667 	*top = (unsigned long)((val >> RB_TIME_SHIFT) & RB_TIME_VAL_MASK);
668 	*bottom = (unsigned long)(val & RB_TIME_VAL_MASK);
669 }
670 
rb_time_val_set(local_t * t,unsigned long val,unsigned long cnt)671 static inline void rb_time_val_set(local_t *t, unsigned long val, unsigned long cnt)
672 {
673 	val = rb_time_val_cnt(val, cnt);
674 	local_set(t, val);
675 }
676 
rb_time_set(rb_time_t * t,u64 val)677 static void rb_time_set(rb_time_t *t, u64 val)
678 {
679 	unsigned long cnt, top, bottom;
680 
681 	rb_time_split(val, &top, &bottom);
682 
683 	/* Writes always succeed with a valid number even if it gets interrupted. */
684 	do {
685 		cnt = local_inc_return(&t->cnt);
686 		rb_time_val_set(&t->top, top, cnt);
687 		rb_time_val_set(&t->bottom, bottom, cnt);
688 	} while (cnt != local_read(&t->cnt));
689 }
690 
691 static inline bool
rb_time_read_cmpxchg(local_t * l,unsigned long expect,unsigned long set)692 rb_time_read_cmpxchg(local_t *l, unsigned long expect, unsigned long set)
693 {
694 	unsigned long ret;
695 
696 	ret = local_cmpxchg(l, expect, set);
697 	return ret == expect;
698 }
699 
rb_time_cmpxchg(rb_time_t * t,u64 expect,u64 set)700 static int rb_time_cmpxchg(rb_time_t *t, u64 expect, u64 set)
701 {
702 	unsigned long cnt, top, bottom;
703 	unsigned long cnt2, top2, bottom2;
704 	u64 val;
705 
706 	/* Any interruptions in this function should cause a failure */
707 	cnt = local_read(&t->cnt);
708 
709 	/* The cmpxchg always fails if it interrupted an update */
710 	 if (!__rb_time_read(t, &val, &cnt2))
711 		 return false;
712 
713 	 if (val != expect)
714 		 return false;
715 
716 	 if ((cnt & 3) != cnt2)
717 		 return false;
718 
719 	 cnt2 = cnt + 1;
720 
721 	 rb_time_split(val, &top, &bottom);
722 	 top = rb_time_val_cnt(top, cnt);
723 	 bottom = rb_time_val_cnt(bottom, cnt);
724 
725 	 rb_time_split(set, &top2, &bottom2);
726 	 top2 = rb_time_val_cnt(top2, cnt2);
727 	 bottom2 = rb_time_val_cnt(bottom2, cnt2);
728 
729 	if (!rb_time_read_cmpxchg(&t->cnt, cnt, cnt2))
730 		return false;
731 	if (!rb_time_read_cmpxchg(&t->top, top, top2))
732 		return false;
733 	if (!rb_time_read_cmpxchg(&t->bottom, bottom, bottom2))
734 		return false;
735 	return true;
736 }
737 
738 #else /* 64 bits */
739 
740 /* local64_t always succeeds */
741 
rb_time_read(rb_time_t * t,u64 * ret)742 static inline bool rb_time_read(rb_time_t *t, u64 *ret)
743 {
744 	*ret = local64_read(&t->time);
745 	return true;
746 }
rb_time_set(rb_time_t * t,u64 val)747 static void rb_time_set(rb_time_t *t, u64 val)
748 {
749 	local64_set(&t->time, val);
750 }
751 
rb_time_cmpxchg(rb_time_t * t,u64 expect,u64 set)752 static bool rb_time_cmpxchg(rb_time_t *t, u64 expect, u64 set)
753 {
754 	u64 val;
755 	val = local64_cmpxchg(&t->time, expect, set);
756 	return val == expect;
757 }
758 #endif
759 
760 /**
761  * ring_buffer_nr_pages - get the number of buffer pages in the ring buffer
762  * @buffer: The ring_buffer to get the number of pages from
763  * @cpu: The cpu of the ring_buffer to get the number of pages from
764  *
765  * Returns the number of pages used by a per_cpu buffer of the ring buffer.
766  */
ring_buffer_nr_pages(struct trace_buffer * buffer,int cpu)767 size_t ring_buffer_nr_pages(struct trace_buffer *buffer, int cpu)
768 {
769 	return buffer->buffers[cpu]->nr_pages;
770 }
771 
772 /**
773  * ring_buffer_nr_pages_dirty - get the number of used pages in the ring buffer
774  * @buffer: The ring_buffer to get the number of pages from
775  * @cpu: The cpu of the ring_buffer to get the number of pages from
776  *
777  * Returns the number of pages that have content in the ring buffer.
778  */
ring_buffer_nr_dirty_pages(struct trace_buffer * buffer,int cpu)779 size_t ring_buffer_nr_dirty_pages(struct trace_buffer *buffer, int cpu)
780 {
781 	size_t read;
782 	size_t lost;
783 	size_t cnt;
784 
785 	read = local_read(&buffer->buffers[cpu]->pages_read);
786 	lost = local_read(&buffer->buffers[cpu]->pages_lost);
787 	cnt = local_read(&buffer->buffers[cpu]->pages_touched);
788 
789 	if (WARN_ON_ONCE(cnt < lost))
790 		return 0;
791 
792 	cnt -= lost;
793 
794 	/* The reader can read an empty page, but not more than that */
795 	if (cnt < read) {
796 		WARN_ON_ONCE(read > cnt + 1);
797 		return 0;
798 	}
799 
800 	return cnt - read;
801 }
802 
full_hit(struct trace_buffer * buffer,int cpu,int full)803 static __always_inline bool full_hit(struct trace_buffer *buffer, int cpu, int full)
804 {
805 	struct ring_buffer_per_cpu *cpu_buffer = buffer->buffers[cpu];
806 	size_t nr_pages;
807 	size_t dirty;
808 
809 	nr_pages = cpu_buffer->nr_pages;
810 	if (!nr_pages || !full)
811 		return true;
812 
813 	/*
814 	 * Add one as dirty will never equal nr_pages, as the sub-buffer
815 	 * that the writer is on is not counted as dirty.
816 	 * This is needed if "buffer_percent" is set to 100.
817 	 */
818 	dirty = ring_buffer_nr_dirty_pages(buffer, cpu) + 1;
819 
820 	return (dirty * 100) >= (full * nr_pages);
821 }
822 
823 /*
824  * rb_wake_up_waiters - wake up tasks waiting for ring buffer input
825  *
826  * Schedules a delayed work to wake up any task that is blocked on the
827  * ring buffer waiters queue.
828  */
rb_wake_up_waiters(struct irq_work * work)829 static void rb_wake_up_waiters(struct irq_work *work)
830 {
831 	struct rb_irq_work *rbwork = container_of(work, struct rb_irq_work, work);
832 
833 	wake_up_all(&rbwork->waiters);
834 	if (rbwork->full_waiters_pending || rbwork->wakeup_full) {
835 		rbwork->wakeup_full = false;
836 		rbwork->full_waiters_pending = false;
837 		wake_up_all(&rbwork->full_waiters);
838 	}
839 }
840 
841 /**
842  * ring_buffer_wake_waiters - wake up any waiters on this ring buffer
843  * @buffer: The ring buffer to wake waiters on
844  *
845  * In the case of a file that represents a ring buffer is closing,
846  * it is prudent to wake up any waiters that are on this.
847  */
ring_buffer_wake_waiters(struct trace_buffer * buffer,int cpu)848 void ring_buffer_wake_waiters(struct trace_buffer *buffer, int cpu)
849 {
850 	struct ring_buffer_per_cpu *cpu_buffer;
851 	struct rb_irq_work *rbwork;
852 
853 	if (cpu == RING_BUFFER_ALL_CPUS) {
854 
855 		/* Wake up individual ones too. One level recursion */
856 		for_each_buffer_cpu(buffer, cpu)
857 			ring_buffer_wake_waiters(buffer, cpu);
858 
859 		rbwork = &buffer->irq_work;
860 	} else {
861 		cpu_buffer = buffer->buffers[cpu];
862 		rbwork = &cpu_buffer->irq_work;
863 	}
864 
865 	rbwork->wait_index++;
866 	/* make sure the waiters see the new index */
867 	smp_wmb();
868 
869 	/* This can be called in any context */
870 	irq_work_queue(&rbwork->work);
871 }
872 
873 /**
874  * ring_buffer_wait - wait for input to the ring buffer
875  * @buffer: buffer to wait on
876  * @cpu: the cpu buffer to wait on
877  * @full: wait until the percentage of pages are available, if @cpu != RING_BUFFER_ALL_CPUS
878  *
879  * If @cpu == RING_BUFFER_ALL_CPUS then the task will wake up as soon
880  * as data is added to any of the @buffer's cpu buffers. Otherwise
881  * it will wait for data to be added to a specific cpu buffer.
882  */
ring_buffer_wait(struct trace_buffer * buffer,int cpu,int full)883 int ring_buffer_wait(struct trace_buffer *buffer, int cpu, int full)
884 {
885 	struct ring_buffer_per_cpu *cpu_buffer;
886 	DEFINE_WAIT(wait);
887 	struct rb_irq_work *work;
888 	long wait_index;
889 	int ret = 0;
890 
891 	/*
892 	 * Depending on what the caller is waiting for, either any
893 	 * data in any cpu buffer, or a specific buffer, put the
894 	 * caller on the appropriate wait queue.
895 	 */
896 	if (cpu == RING_BUFFER_ALL_CPUS) {
897 		work = &buffer->irq_work;
898 		/* Full only makes sense on per cpu reads */
899 		full = 0;
900 	} else {
901 		if (!cpumask_test_cpu(cpu, buffer->cpumask))
902 			return -ENODEV;
903 		cpu_buffer = buffer->buffers[cpu];
904 		work = &cpu_buffer->irq_work;
905 	}
906 
907 	wait_index = READ_ONCE(work->wait_index);
908 
909 	while (true) {
910 		if (full)
911 			prepare_to_wait(&work->full_waiters, &wait, TASK_INTERRUPTIBLE);
912 		else
913 			prepare_to_wait(&work->waiters, &wait, TASK_INTERRUPTIBLE);
914 
915 		/*
916 		 * The events can happen in critical sections where
917 		 * checking a work queue can cause deadlocks.
918 		 * After adding a task to the queue, this flag is set
919 		 * only to notify events to try to wake up the queue
920 		 * using irq_work.
921 		 *
922 		 * We don't clear it even if the buffer is no longer
923 		 * empty. The flag only causes the next event to run
924 		 * irq_work to do the work queue wake up. The worse
925 		 * that can happen if we race with !trace_empty() is that
926 		 * an event will cause an irq_work to try to wake up
927 		 * an empty queue.
928 		 *
929 		 * There's no reason to protect this flag either, as
930 		 * the work queue and irq_work logic will do the necessary
931 		 * synchronization for the wake ups. The only thing
932 		 * that is necessary is that the wake up happens after
933 		 * a task has been queued. It's OK for spurious wake ups.
934 		 */
935 		if (full)
936 			work->full_waiters_pending = true;
937 		else
938 			work->waiters_pending = true;
939 
940 		if (signal_pending(current)) {
941 			ret = -EINTR;
942 			break;
943 		}
944 
945 		if (cpu == RING_BUFFER_ALL_CPUS && !ring_buffer_empty(buffer))
946 			break;
947 
948 		if (cpu != RING_BUFFER_ALL_CPUS &&
949 		    !ring_buffer_empty_cpu(buffer, cpu)) {
950 			unsigned long flags;
951 			bool pagebusy;
952 			bool done;
953 
954 			if (!full)
955 				break;
956 
957 			raw_spin_lock_irqsave(&cpu_buffer->reader_lock, flags);
958 			pagebusy = cpu_buffer->reader_page == cpu_buffer->commit_page;
959 			done = !pagebusy && full_hit(buffer, cpu, full);
960 
961 			if (!cpu_buffer->shortest_full ||
962 			    cpu_buffer->shortest_full > full)
963 				cpu_buffer->shortest_full = full;
964 			raw_spin_unlock_irqrestore(&cpu_buffer->reader_lock, flags);
965 			if (done)
966 				break;
967 		}
968 
969 		schedule();
970 
971 		/* Make sure to see the new wait index */
972 		smp_rmb();
973 		if (wait_index != work->wait_index)
974 			break;
975 	}
976 
977 	if (full)
978 		finish_wait(&work->full_waiters, &wait);
979 	else
980 		finish_wait(&work->waiters, &wait);
981 
982 	return ret;
983 }
984 
985 /**
986  * ring_buffer_poll_wait - poll on buffer input
987  * @buffer: buffer to wait on
988  * @cpu: the cpu buffer to wait on
989  * @filp: the file descriptor
990  * @poll_table: The poll descriptor
991  * @full: wait until the percentage of pages are available, if @cpu != RING_BUFFER_ALL_CPUS
992  *
993  * If @cpu == RING_BUFFER_ALL_CPUS then the task will wake up as soon
994  * as data is added to any of the @buffer's cpu buffers. Otherwise
995  * it will wait for data to be added to a specific cpu buffer.
996  *
997  * Returns EPOLLIN | EPOLLRDNORM if data exists in the buffers,
998  * zero otherwise.
999  */
ring_buffer_poll_wait(struct trace_buffer * buffer,int cpu,struct file * filp,poll_table * poll_table,int full)1000 __poll_t ring_buffer_poll_wait(struct trace_buffer *buffer, int cpu,
1001 			  struct file *filp, poll_table *poll_table, int full)
1002 {
1003 	struct ring_buffer_per_cpu *cpu_buffer;
1004 	struct rb_irq_work *work;
1005 
1006 	if (cpu == RING_BUFFER_ALL_CPUS) {
1007 		work = &buffer->irq_work;
1008 		full = 0;
1009 	} else {
1010 		if (!cpumask_test_cpu(cpu, buffer->cpumask))
1011 			return -EINVAL;
1012 
1013 		cpu_buffer = buffer->buffers[cpu];
1014 		work = &cpu_buffer->irq_work;
1015 	}
1016 
1017 	if (full) {
1018 		poll_wait(filp, &work->full_waiters, poll_table);
1019 		work->full_waiters_pending = true;
1020 		if (!cpu_buffer->shortest_full ||
1021 		    cpu_buffer->shortest_full > full)
1022 			cpu_buffer->shortest_full = full;
1023 	} else {
1024 		poll_wait(filp, &work->waiters, poll_table);
1025 		work->waiters_pending = true;
1026 	}
1027 
1028 	/*
1029 	 * There's a tight race between setting the waiters_pending and
1030 	 * checking if the ring buffer is empty.  Once the waiters_pending bit
1031 	 * is set, the next event will wake the task up, but we can get stuck
1032 	 * if there's only a single event in.
1033 	 *
1034 	 * FIXME: Ideally, we need a memory barrier on the writer side as well,
1035 	 * but adding a memory barrier to all events will cause too much of a
1036 	 * performance hit in the fast path.  We only need a memory barrier when
1037 	 * the buffer goes from empty to having content.  But as this race is
1038 	 * extremely small, and it's not a problem if another event comes in, we
1039 	 * will fix it later.
1040 	 */
1041 	smp_mb();
1042 
1043 	if (full)
1044 		return full_hit(buffer, cpu, full) ? EPOLLIN | EPOLLRDNORM : 0;
1045 
1046 	if ((cpu == RING_BUFFER_ALL_CPUS && !ring_buffer_empty(buffer)) ||
1047 	    (cpu != RING_BUFFER_ALL_CPUS && !ring_buffer_empty_cpu(buffer, cpu)))
1048 		return EPOLLIN | EPOLLRDNORM;
1049 	return 0;
1050 }
1051 
1052 /* buffer may be either ring_buffer or ring_buffer_per_cpu */
1053 #define RB_WARN_ON(b, cond)						\
1054 	({								\
1055 		int _____ret = unlikely(cond);				\
1056 		if (_____ret) {						\
1057 			if (__same_type(*(b), struct ring_buffer_per_cpu)) { \
1058 				struct ring_buffer_per_cpu *__b =	\
1059 					(void *)b;			\
1060 				atomic_inc(&__b->buffer->record_disabled); \
1061 			} else						\
1062 				atomic_inc(&b->record_disabled);	\
1063 			WARN_ON(1);					\
1064 		}							\
1065 		_____ret;						\
1066 	})
1067 
1068 /* Up this if you want to test the TIME_EXTENTS and normalization */
1069 #define DEBUG_SHIFT 0
1070 
rb_time_stamp(struct trace_buffer * buffer)1071 static inline u64 rb_time_stamp(struct trace_buffer *buffer)
1072 {
1073 	u64 ts;
1074 
1075 	/* Skip retpolines :-( */
1076 	if (IS_ENABLED(CONFIG_RETPOLINE) && likely(buffer->clock == trace_clock_local))
1077 		ts = trace_clock_local();
1078 	else
1079 		ts = buffer->clock();
1080 
1081 	/* shift to debug/test normalization and TIME_EXTENTS */
1082 	return ts << DEBUG_SHIFT;
1083 }
1084 
ring_buffer_time_stamp(struct trace_buffer * buffer,int cpu)1085 u64 ring_buffer_time_stamp(struct trace_buffer *buffer, int cpu)
1086 {
1087 	u64 time;
1088 
1089 	preempt_disable_notrace();
1090 	time = rb_time_stamp(buffer);
1091 	preempt_enable_notrace();
1092 
1093 	return time;
1094 }
1095 EXPORT_SYMBOL_GPL(ring_buffer_time_stamp);
1096 
ring_buffer_normalize_time_stamp(struct trace_buffer * buffer,int cpu,u64 * ts)1097 void ring_buffer_normalize_time_stamp(struct trace_buffer *buffer,
1098 				      int cpu, u64 *ts)
1099 {
1100 	/* Just stupid testing the normalize function and deltas */
1101 	*ts >>= DEBUG_SHIFT;
1102 }
1103 EXPORT_SYMBOL_GPL(ring_buffer_normalize_time_stamp);
1104 
1105 /*
1106  * Making the ring buffer lockless makes things tricky.
1107  * Although writes only happen on the CPU that they are on,
1108  * and they only need to worry about interrupts. Reads can
1109  * happen on any CPU.
1110  *
1111  * The reader page is always off the ring buffer, but when the
1112  * reader finishes with a page, it needs to swap its page with
1113  * a new one from the buffer. The reader needs to take from
1114  * the head (writes go to the tail). But if a writer is in overwrite
1115  * mode and wraps, it must push the head page forward.
1116  *
1117  * Here lies the problem.
1118  *
1119  * The reader must be careful to replace only the head page, and
1120  * not another one. As described at the top of the file in the
1121  * ASCII art, the reader sets its old page to point to the next
1122  * page after head. It then sets the page after head to point to
1123  * the old reader page. But if the writer moves the head page
1124  * during this operation, the reader could end up with the tail.
1125  *
1126  * We use cmpxchg to help prevent this race. We also do something
1127  * special with the page before head. We set the LSB to 1.
1128  *
1129  * When the writer must push the page forward, it will clear the
1130  * bit that points to the head page, move the head, and then set
1131  * the bit that points to the new head page.
1132  *
1133  * We also don't want an interrupt coming in and moving the head
1134  * page on another writer. Thus we use the second LSB to catch
1135  * that too. Thus:
1136  *
1137  * head->list->prev->next        bit 1          bit 0
1138  *                              -------        -------
1139  * Normal page                     0              0
1140  * Points to head page             0              1
1141  * New head page                   1              0
1142  *
1143  * Note we can not trust the prev pointer of the head page, because:
1144  *
1145  * +----+       +-----+        +-----+
1146  * |    |------>|  T  |---X--->|  N  |
1147  * |    |<------|     |        |     |
1148  * +----+       +-----+        +-----+
1149  *   ^                           ^ |
1150  *   |          +-----+          | |
1151  *   +----------|  R  |----------+ |
1152  *              |     |<-----------+
1153  *              +-----+
1154  *
1155  * Key:  ---X-->  HEAD flag set in pointer
1156  *         T      Tail page
1157  *         R      Reader page
1158  *         N      Next page
1159  *
1160  * (see __rb_reserve_next() to see where this happens)
1161  *
1162  *  What the above shows is that the reader just swapped out
1163  *  the reader page with a page in the buffer, but before it
1164  *  could make the new header point back to the new page added
1165  *  it was preempted by a writer. The writer moved forward onto
1166  *  the new page added by the reader and is about to move forward
1167  *  again.
1168  *
1169  *  You can see, it is legitimate for the previous pointer of
1170  *  the head (or any page) not to point back to itself. But only
1171  *  temporarily.
1172  */
1173 
1174 #define RB_PAGE_NORMAL		0UL
1175 #define RB_PAGE_HEAD		1UL
1176 #define RB_PAGE_UPDATE		2UL
1177 
1178 
1179 #define RB_FLAG_MASK		3UL
1180 
1181 /* PAGE_MOVED is not part of the mask */
1182 #define RB_PAGE_MOVED		4UL
1183 
1184 /*
1185  * rb_list_head - remove any bit
1186  */
rb_list_head(struct list_head * list)1187 static struct list_head *rb_list_head(struct list_head *list)
1188 {
1189 	unsigned long val = (unsigned long)list;
1190 
1191 	return (struct list_head *)(val & ~RB_FLAG_MASK);
1192 }
1193 
1194 /*
1195  * rb_is_head_page - test if the given page is the head page
1196  *
1197  * Because the reader may move the head_page pointer, we can
1198  * not trust what the head page is (it may be pointing to
1199  * the reader page). But if the next page is a header page,
1200  * its flags will be non zero.
1201  */
1202 static inline int
rb_is_head_page(struct ring_buffer_per_cpu * cpu_buffer,struct buffer_page * page,struct list_head * list)1203 rb_is_head_page(struct ring_buffer_per_cpu *cpu_buffer,
1204 		struct buffer_page *page, struct list_head *list)
1205 {
1206 	unsigned long val;
1207 
1208 	val = (unsigned long)list->next;
1209 
1210 	if ((val & ~RB_FLAG_MASK) != (unsigned long)&page->list)
1211 		return RB_PAGE_MOVED;
1212 
1213 	return val & RB_FLAG_MASK;
1214 }
1215 
1216 /*
1217  * rb_is_reader_page
1218  *
1219  * The unique thing about the reader page, is that, if the
1220  * writer is ever on it, the previous pointer never points
1221  * back to the reader page.
1222  */
rb_is_reader_page(struct buffer_page * page)1223 static bool rb_is_reader_page(struct buffer_page *page)
1224 {
1225 	struct list_head *list = page->list.prev;
1226 
1227 	return rb_list_head(list->next) != &page->list;
1228 }
1229 
1230 /*
1231  * rb_set_list_to_head - set a list_head to be pointing to head.
1232  */
rb_set_list_to_head(struct ring_buffer_per_cpu * cpu_buffer,struct list_head * list)1233 static void rb_set_list_to_head(struct ring_buffer_per_cpu *cpu_buffer,
1234 				struct list_head *list)
1235 {
1236 	unsigned long *ptr;
1237 
1238 	ptr = (unsigned long *)&list->next;
1239 	*ptr |= RB_PAGE_HEAD;
1240 	*ptr &= ~RB_PAGE_UPDATE;
1241 }
1242 
1243 /*
1244  * rb_head_page_activate - sets up head page
1245  */
rb_head_page_activate(struct ring_buffer_per_cpu * cpu_buffer)1246 static void rb_head_page_activate(struct ring_buffer_per_cpu *cpu_buffer)
1247 {
1248 	struct buffer_page *head;
1249 
1250 	head = cpu_buffer->head_page;
1251 	if (!head)
1252 		return;
1253 
1254 	/*
1255 	 * Set the previous list pointer to have the HEAD flag.
1256 	 */
1257 	rb_set_list_to_head(cpu_buffer, head->list.prev);
1258 }
1259 
rb_list_head_clear(struct list_head * list)1260 static void rb_list_head_clear(struct list_head *list)
1261 {
1262 	unsigned long *ptr = (unsigned long *)&list->next;
1263 
1264 	*ptr &= ~RB_FLAG_MASK;
1265 }
1266 
1267 /*
1268  * rb_head_page_deactivate - clears head page ptr (for free list)
1269  */
1270 static void
rb_head_page_deactivate(struct ring_buffer_per_cpu * cpu_buffer)1271 rb_head_page_deactivate(struct ring_buffer_per_cpu *cpu_buffer)
1272 {
1273 	struct list_head *hd;
1274 
1275 	/* Go through the whole list and clear any pointers found. */
1276 	rb_list_head_clear(cpu_buffer->pages);
1277 
1278 	list_for_each(hd, cpu_buffer->pages)
1279 		rb_list_head_clear(hd);
1280 }
1281 
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)1282 static int rb_head_page_set(struct ring_buffer_per_cpu *cpu_buffer,
1283 			    struct buffer_page *head,
1284 			    struct buffer_page *prev,
1285 			    int old_flag, int new_flag)
1286 {
1287 	struct list_head *list;
1288 	unsigned long val = (unsigned long)&head->list;
1289 	unsigned long ret;
1290 
1291 	list = &prev->list;
1292 
1293 	val &= ~RB_FLAG_MASK;
1294 
1295 	ret = cmpxchg((unsigned long *)&list->next,
1296 		      val | old_flag, val | new_flag);
1297 
1298 	/* check if the reader took the page */
1299 	if ((ret & ~RB_FLAG_MASK) != val)
1300 		return RB_PAGE_MOVED;
1301 
1302 	return ret & RB_FLAG_MASK;
1303 }
1304 
rb_head_page_set_update(struct ring_buffer_per_cpu * cpu_buffer,struct buffer_page * head,struct buffer_page * prev,int old_flag)1305 static int rb_head_page_set_update(struct ring_buffer_per_cpu *cpu_buffer,
1306 				   struct buffer_page *head,
1307 				   struct buffer_page *prev,
1308 				   int old_flag)
1309 {
1310 	return rb_head_page_set(cpu_buffer, head, prev,
1311 				old_flag, RB_PAGE_UPDATE);
1312 }
1313 
rb_head_page_set_head(struct ring_buffer_per_cpu * cpu_buffer,struct buffer_page * head,struct buffer_page * prev,int old_flag)1314 static int rb_head_page_set_head(struct ring_buffer_per_cpu *cpu_buffer,
1315 				 struct buffer_page *head,
1316 				 struct buffer_page *prev,
1317 				 int old_flag)
1318 {
1319 	return rb_head_page_set(cpu_buffer, head, prev,
1320 				old_flag, RB_PAGE_HEAD);
1321 }
1322 
rb_head_page_set_normal(struct ring_buffer_per_cpu * cpu_buffer,struct buffer_page * head,struct buffer_page * prev,int old_flag)1323 static int rb_head_page_set_normal(struct ring_buffer_per_cpu *cpu_buffer,
1324 				   struct buffer_page *head,
1325 				   struct buffer_page *prev,
1326 				   int old_flag)
1327 {
1328 	return rb_head_page_set(cpu_buffer, head, prev,
1329 				old_flag, RB_PAGE_NORMAL);
1330 }
1331 
rb_inc_page(struct ring_buffer_per_cpu * cpu_buffer,struct buffer_page ** bpage)1332 static inline void rb_inc_page(struct ring_buffer_per_cpu *cpu_buffer,
1333 			       struct buffer_page **bpage)
1334 {
1335 	struct list_head *p = rb_list_head((*bpage)->list.next);
1336 
1337 	*bpage = list_entry(p, struct buffer_page, list);
1338 }
1339 
1340 static struct buffer_page *
rb_set_head_page(struct ring_buffer_per_cpu * cpu_buffer)1341 rb_set_head_page(struct ring_buffer_per_cpu *cpu_buffer)
1342 {
1343 	struct buffer_page *head;
1344 	struct buffer_page *page;
1345 	struct list_head *list;
1346 	int i;
1347 
1348 	if (RB_WARN_ON(cpu_buffer, !cpu_buffer->head_page))
1349 		return NULL;
1350 
1351 	/* sanity check */
1352 	list = cpu_buffer->pages;
1353 	if (RB_WARN_ON(cpu_buffer, rb_list_head(list->prev->next) != list))
1354 		return NULL;
1355 
1356 	page = head = cpu_buffer->head_page;
1357 	/*
1358 	 * It is possible that the writer moves the header behind
1359 	 * where we started, and we miss in one loop.
1360 	 * A second loop should grab the header, but we'll do
1361 	 * three loops just because I'm paranoid.
1362 	 */
1363 	for (i = 0; i < 3; i++) {
1364 		do {
1365 			if (rb_is_head_page(cpu_buffer, page, page->list.prev)) {
1366 				cpu_buffer->head_page = page;
1367 				return page;
1368 			}
1369 			rb_inc_page(cpu_buffer, &page);
1370 		} while (page != head);
1371 	}
1372 
1373 	RB_WARN_ON(cpu_buffer, 1);
1374 
1375 	return NULL;
1376 }
1377 
rb_head_page_replace(struct buffer_page * old,struct buffer_page * new)1378 static int rb_head_page_replace(struct buffer_page *old,
1379 				struct buffer_page *new)
1380 {
1381 	unsigned long *ptr = (unsigned long *)&old->list.prev->next;
1382 	unsigned long val;
1383 	unsigned long ret;
1384 
1385 	val = *ptr & ~RB_FLAG_MASK;
1386 	val |= RB_PAGE_HEAD;
1387 
1388 	ret = cmpxchg(ptr, val, (unsigned long)&new->list);
1389 
1390 	return ret == val;
1391 }
1392 
1393 /*
1394  * rb_tail_page_update - move the tail page forward
1395  */
rb_tail_page_update(struct ring_buffer_per_cpu * cpu_buffer,struct buffer_page * tail_page,struct buffer_page * next_page)1396 static void rb_tail_page_update(struct ring_buffer_per_cpu *cpu_buffer,
1397 			       struct buffer_page *tail_page,
1398 			       struct buffer_page *next_page)
1399 {
1400 	unsigned long old_entries;
1401 	unsigned long old_write;
1402 
1403 	/*
1404 	 * The tail page now needs to be moved forward.
1405 	 *
1406 	 * We need to reset the tail page, but without messing
1407 	 * with possible erasing of data brought in by interrupts
1408 	 * that have moved the tail page and are currently on it.
1409 	 *
1410 	 * We add a counter to the write field to denote this.
1411 	 */
1412 	old_write = local_add_return(RB_WRITE_INTCNT, &next_page->write);
1413 	old_entries = local_add_return(RB_WRITE_INTCNT, &next_page->entries);
1414 
1415 	local_inc(&cpu_buffer->pages_touched);
1416 	/*
1417 	 * Just make sure we have seen our old_write and synchronize
1418 	 * with any interrupts that come in.
1419 	 */
1420 	barrier();
1421 
1422 	/*
1423 	 * If the tail page is still the same as what we think
1424 	 * it is, then it is up to us to update the tail
1425 	 * pointer.
1426 	 */
1427 	if (tail_page == READ_ONCE(cpu_buffer->tail_page)) {
1428 		/* Zero the write counter */
1429 		unsigned long val = old_write & ~RB_WRITE_MASK;
1430 		unsigned long eval = old_entries & ~RB_WRITE_MASK;
1431 
1432 		/*
1433 		 * This will only succeed if an interrupt did
1434 		 * not come in and change it. In which case, we
1435 		 * do not want to modify it.
1436 		 *
1437 		 * We add (void) to let the compiler know that we do not care
1438 		 * about the return value of these functions. We use the
1439 		 * cmpxchg to only update if an interrupt did not already
1440 		 * do it for us. If the cmpxchg fails, we don't care.
1441 		 */
1442 		(void)local_cmpxchg(&next_page->write, old_write, val);
1443 		(void)local_cmpxchg(&next_page->entries, old_entries, eval);
1444 
1445 		/*
1446 		 * No need to worry about races with clearing out the commit.
1447 		 * it only can increment when a commit takes place. But that
1448 		 * only happens in the outer most nested commit.
1449 		 */
1450 		local_set(&next_page->page->commit, 0);
1451 
1452 		/* Again, either we update tail_page or an interrupt does */
1453 		(void)cmpxchg(&cpu_buffer->tail_page, tail_page, next_page);
1454 	}
1455 }
1456 
rb_check_bpage(struct ring_buffer_per_cpu * cpu_buffer,struct buffer_page * bpage)1457 static int rb_check_bpage(struct ring_buffer_per_cpu *cpu_buffer,
1458 			  struct buffer_page *bpage)
1459 {
1460 	unsigned long val = (unsigned long)bpage;
1461 
1462 	if (RB_WARN_ON(cpu_buffer, val & RB_FLAG_MASK))
1463 		return 1;
1464 
1465 	return 0;
1466 }
1467 
1468 /**
1469  * rb_check_pages - integrity check of buffer pages
1470  * @cpu_buffer: CPU buffer with pages to test
1471  *
1472  * As a safety measure we check to make sure the data pages have not
1473  * been corrupted.
1474  *
1475  * Callers of this function need to guarantee that the list of pages doesn't get
1476  * modified during the check. In particular, if it's possible that the function
1477  * is invoked with concurrent readers which can swap in a new reader page then
1478  * the caller should take cpu_buffer->reader_lock.
1479  */
rb_check_pages(struct ring_buffer_per_cpu * cpu_buffer)1480 static int rb_check_pages(struct ring_buffer_per_cpu *cpu_buffer)
1481 {
1482 	struct list_head *head = rb_list_head(cpu_buffer->pages);
1483 	struct list_head *tmp;
1484 
1485 	if (RB_WARN_ON(cpu_buffer,
1486 			rb_list_head(rb_list_head(head->next)->prev) != head))
1487 		return -1;
1488 
1489 	if (RB_WARN_ON(cpu_buffer,
1490 			rb_list_head(rb_list_head(head->prev)->next) != head))
1491 		return -1;
1492 
1493 	for (tmp = rb_list_head(head->next); tmp != head; tmp = rb_list_head(tmp->next)) {
1494 		if (RB_WARN_ON(cpu_buffer,
1495 				rb_list_head(rb_list_head(tmp->next)->prev) != tmp))
1496 			return -1;
1497 
1498 		if (RB_WARN_ON(cpu_buffer,
1499 				rb_list_head(rb_list_head(tmp->prev)->next) != tmp))
1500 			return -1;
1501 	}
1502 
1503 	return 0;
1504 }
1505 
__rb_allocate_pages(long nr_pages,struct list_head * pages,int cpu)1506 static int __rb_allocate_pages(long nr_pages, struct list_head *pages, int cpu)
1507 {
1508 	struct buffer_page *bpage, *tmp;
1509 	bool user_thread = current->mm != NULL;
1510 	gfp_t mflags;
1511 	long i;
1512 
1513 	/*
1514 	 * Check if the available memory is there first.
1515 	 * Note, si_mem_available() only gives us a rough estimate of available
1516 	 * memory. It may not be accurate. But we don't care, we just want
1517 	 * to prevent doing any allocation when it is obvious that it is
1518 	 * not going to succeed.
1519 	 */
1520 	i = si_mem_available();
1521 	if (i < nr_pages)
1522 		return -ENOMEM;
1523 
1524 	/*
1525 	 * __GFP_RETRY_MAYFAIL flag makes sure that the allocation fails
1526 	 * gracefully without invoking oom-killer and the system is not
1527 	 * destabilized.
1528 	 */
1529 	mflags = GFP_KERNEL | __GFP_RETRY_MAYFAIL;
1530 
1531 	/*
1532 	 * If a user thread allocates too much, and si_mem_available()
1533 	 * reports there's enough memory, even though there is not.
1534 	 * Make sure the OOM killer kills this thread. This can happen
1535 	 * even with RETRY_MAYFAIL because another task may be doing
1536 	 * an allocation after this task has taken all memory.
1537 	 * This is the task the OOM killer needs to take out during this
1538 	 * loop, even if it was triggered by an allocation somewhere else.
1539 	 */
1540 	if (user_thread)
1541 		set_current_oom_origin();
1542 	for (i = 0; i < nr_pages; i++) {
1543 		struct page *page;
1544 
1545 		bpage = kzalloc_node(ALIGN(sizeof(*bpage), cache_line_size()),
1546 				    mflags, cpu_to_node(cpu));
1547 		if (!bpage)
1548 			goto free_pages;
1549 
1550 		list_add(&bpage->list, pages);
1551 
1552 		page = alloc_pages_node(cpu_to_node(cpu), mflags, 0);
1553 		if (!page)
1554 			goto free_pages;
1555 		bpage->page = page_address(page);
1556 		rb_init_page(bpage->page);
1557 
1558 		if (user_thread && fatal_signal_pending(current))
1559 			goto free_pages;
1560 	}
1561 	if (user_thread)
1562 		clear_current_oom_origin();
1563 
1564 	return 0;
1565 
1566 free_pages:
1567 	list_for_each_entry_safe(bpage, tmp, pages, list) {
1568 		list_del_init(&bpage->list);
1569 		free_buffer_page(bpage);
1570 	}
1571 	if (user_thread)
1572 		clear_current_oom_origin();
1573 
1574 	return -ENOMEM;
1575 }
1576 
rb_allocate_pages(struct ring_buffer_per_cpu * cpu_buffer,unsigned long nr_pages)1577 static int rb_allocate_pages(struct ring_buffer_per_cpu *cpu_buffer,
1578 			     unsigned long nr_pages)
1579 {
1580 	LIST_HEAD(pages);
1581 
1582 	WARN_ON(!nr_pages);
1583 
1584 	if (__rb_allocate_pages(nr_pages, &pages, cpu_buffer->cpu))
1585 		return -ENOMEM;
1586 
1587 	/*
1588 	 * The ring buffer page list is a circular list that does not
1589 	 * start and end with a list head. All page list items point to
1590 	 * other pages.
1591 	 */
1592 	cpu_buffer->pages = pages.next;
1593 	list_del(&pages);
1594 
1595 	cpu_buffer->nr_pages = nr_pages;
1596 
1597 	rb_check_pages(cpu_buffer);
1598 
1599 	return 0;
1600 }
1601 
1602 static struct ring_buffer_per_cpu *
rb_allocate_cpu_buffer(struct trace_buffer * buffer,long nr_pages,int cpu)1603 rb_allocate_cpu_buffer(struct trace_buffer *buffer, long nr_pages, int cpu)
1604 {
1605 	struct ring_buffer_per_cpu *cpu_buffer;
1606 	struct buffer_page *bpage;
1607 	struct page *page;
1608 	int ret;
1609 
1610 	cpu_buffer = kzalloc_node(ALIGN(sizeof(*cpu_buffer), cache_line_size()),
1611 				  GFP_KERNEL, cpu_to_node(cpu));
1612 	if (!cpu_buffer)
1613 		return NULL;
1614 
1615 	cpu_buffer->cpu = cpu;
1616 	cpu_buffer->buffer = buffer;
1617 	raw_spin_lock_init(&cpu_buffer->reader_lock);
1618 	lockdep_set_class(&cpu_buffer->reader_lock, buffer->reader_lock_key);
1619 	cpu_buffer->lock = (arch_spinlock_t)__ARCH_SPIN_LOCK_UNLOCKED;
1620 	INIT_WORK(&cpu_buffer->update_pages_work, update_pages_handler);
1621 	init_completion(&cpu_buffer->update_done);
1622 	init_irq_work(&cpu_buffer->irq_work.work, rb_wake_up_waiters);
1623 	init_waitqueue_head(&cpu_buffer->irq_work.waiters);
1624 	init_waitqueue_head(&cpu_buffer->irq_work.full_waiters);
1625 
1626 	bpage = kzalloc_node(ALIGN(sizeof(*bpage), cache_line_size()),
1627 			    GFP_KERNEL, cpu_to_node(cpu));
1628 	if (!bpage)
1629 		goto fail_free_buffer;
1630 
1631 	rb_check_bpage(cpu_buffer, bpage);
1632 
1633 	cpu_buffer->reader_page = bpage;
1634 	page = alloc_pages_node(cpu_to_node(cpu), GFP_KERNEL, 0);
1635 	if (!page)
1636 		goto fail_free_reader;
1637 	bpage->page = page_address(page);
1638 	rb_init_page(bpage->page);
1639 
1640 	INIT_LIST_HEAD(&cpu_buffer->reader_page->list);
1641 	INIT_LIST_HEAD(&cpu_buffer->new_pages);
1642 
1643 	ret = rb_allocate_pages(cpu_buffer, nr_pages);
1644 	if (ret < 0)
1645 		goto fail_free_reader;
1646 
1647 	cpu_buffer->head_page
1648 		= list_entry(cpu_buffer->pages, struct buffer_page, list);
1649 	cpu_buffer->tail_page = cpu_buffer->commit_page = cpu_buffer->head_page;
1650 
1651 	rb_head_page_activate(cpu_buffer);
1652 
1653 	return cpu_buffer;
1654 
1655  fail_free_reader:
1656 	free_buffer_page(cpu_buffer->reader_page);
1657 
1658  fail_free_buffer:
1659 	kfree(cpu_buffer);
1660 	return NULL;
1661 }
1662 
rb_free_cpu_buffer(struct ring_buffer_per_cpu * cpu_buffer)1663 static void rb_free_cpu_buffer(struct ring_buffer_per_cpu *cpu_buffer)
1664 {
1665 	struct list_head *head = cpu_buffer->pages;
1666 	struct buffer_page *bpage, *tmp;
1667 
1668 	irq_work_sync(&cpu_buffer->irq_work.work);
1669 
1670 	free_buffer_page(cpu_buffer->reader_page);
1671 
1672 	if (head) {
1673 		rb_head_page_deactivate(cpu_buffer);
1674 
1675 		list_for_each_entry_safe(bpage, tmp, head, list) {
1676 			list_del_init(&bpage->list);
1677 			free_buffer_page(bpage);
1678 		}
1679 		bpage = list_entry(head, struct buffer_page, list);
1680 		free_buffer_page(bpage);
1681 	}
1682 
1683 	free_page((unsigned long)cpu_buffer->free_page);
1684 
1685 	kfree(cpu_buffer);
1686 }
1687 
1688 /**
1689  * __ring_buffer_alloc - allocate a new ring_buffer
1690  * @size: the size in bytes per cpu that is needed.
1691  * @flags: attributes to set for the ring buffer.
1692  * @key: ring buffer reader_lock_key.
1693  *
1694  * Currently the only flag that is available is the RB_FL_OVERWRITE
1695  * flag. This flag means that the buffer will overwrite old data
1696  * when the buffer wraps. If this flag is not set, the buffer will
1697  * drop data when the tail hits the head.
1698  */
__ring_buffer_alloc(unsigned long size,unsigned flags,struct lock_class_key * key)1699 struct trace_buffer *__ring_buffer_alloc(unsigned long size, unsigned flags,
1700 					struct lock_class_key *key)
1701 {
1702 	struct trace_buffer *buffer;
1703 	long nr_pages;
1704 	int bsize;
1705 	int cpu;
1706 	int ret;
1707 
1708 	/* keep it in its own cache line */
1709 	buffer = kzalloc(ALIGN(sizeof(*buffer), cache_line_size()),
1710 			 GFP_KERNEL);
1711 	if (!buffer)
1712 		return NULL;
1713 
1714 	if (!zalloc_cpumask_var(&buffer->cpumask, GFP_KERNEL))
1715 		goto fail_free_buffer;
1716 
1717 	nr_pages = DIV_ROUND_UP(size, BUF_PAGE_SIZE);
1718 	buffer->flags = flags;
1719 	buffer->clock = trace_clock_local;
1720 	buffer->reader_lock_key = key;
1721 
1722 	init_irq_work(&buffer->irq_work.work, rb_wake_up_waiters);
1723 	init_waitqueue_head(&buffer->irq_work.waiters);
1724 
1725 	/* need at least two pages */
1726 	if (nr_pages < 2)
1727 		nr_pages = 2;
1728 
1729 	buffer->cpus = nr_cpu_ids;
1730 
1731 	bsize = sizeof(void *) * nr_cpu_ids;
1732 	buffer->buffers = kzalloc(ALIGN(bsize, cache_line_size()),
1733 				  GFP_KERNEL);
1734 	if (!buffer->buffers)
1735 		goto fail_free_cpumask;
1736 
1737 	cpu = raw_smp_processor_id();
1738 	cpumask_set_cpu(cpu, buffer->cpumask);
1739 	buffer->buffers[cpu] = rb_allocate_cpu_buffer(buffer, nr_pages, cpu);
1740 	if (!buffer->buffers[cpu])
1741 		goto fail_free_buffers;
1742 
1743 	ret = cpuhp_state_add_instance(CPUHP_TRACE_RB_PREPARE, &buffer->node);
1744 	if (ret < 0)
1745 		goto fail_free_buffers;
1746 
1747 	mutex_init(&buffer->mutex);
1748 
1749 	return buffer;
1750 
1751  fail_free_buffers:
1752 	for_each_buffer_cpu(buffer, cpu) {
1753 		if (buffer->buffers[cpu])
1754 			rb_free_cpu_buffer(buffer->buffers[cpu]);
1755 	}
1756 	kfree(buffer->buffers);
1757 
1758  fail_free_cpumask:
1759 	free_cpumask_var(buffer->cpumask);
1760 
1761  fail_free_buffer:
1762 	kfree(buffer);
1763 	return NULL;
1764 }
1765 EXPORT_SYMBOL_GPL(__ring_buffer_alloc);
1766 
1767 /**
1768  * ring_buffer_free - free a ring buffer.
1769  * @buffer: the buffer to free.
1770  */
1771 void
ring_buffer_free(struct trace_buffer * buffer)1772 ring_buffer_free(struct trace_buffer *buffer)
1773 {
1774 	int cpu;
1775 
1776 	cpuhp_state_remove_instance(CPUHP_TRACE_RB_PREPARE, &buffer->node);
1777 
1778 	irq_work_sync(&buffer->irq_work.work);
1779 
1780 	for_each_buffer_cpu(buffer, cpu)
1781 		rb_free_cpu_buffer(buffer->buffers[cpu]);
1782 
1783 	kfree(buffer->buffers);
1784 	free_cpumask_var(buffer->cpumask);
1785 
1786 	kfree(buffer);
1787 }
1788 EXPORT_SYMBOL_GPL(ring_buffer_free);
1789 
ring_buffer_set_clock(struct trace_buffer * buffer,u64 (* clock)(void))1790 void ring_buffer_set_clock(struct trace_buffer *buffer,
1791 			   u64 (*clock)(void))
1792 {
1793 	buffer->clock = clock;
1794 }
1795 
ring_buffer_set_time_stamp_abs(struct trace_buffer * buffer,bool abs)1796 void ring_buffer_set_time_stamp_abs(struct trace_buffer *buffer, bool abs)
1797 {
1798 	buffer->time_stamp_abs = abs;
1799 }
1800 
ring_buffer_time_stamp_abs(struct trace_buffer * buffer)1801 bool ring_buffer_time_stamp_abs(struct trace_buffer *buffer)
1802 {
1803 	return buffer->time_stamp_abs;
1804 }
1805 
1806 static void rb_reset_cpu(struct ring_buffer_per_cpu *cpu_buffer);
1807 
rb_page_entries(struct buffer_page * bpage)1808 static inline unsigned long rb_page_entries(struct buffer_page *bpage)
1809 {
1810 	return local_read(&bpage->entries) & RB_WRITE_MASK;
1811 }
1812 
rb_page_write(struct buffer_page * bpage)1813 static inline unsigned long rb_page_write(struct buffer_page *bpage)
1814 {
1815 	return local_read(&bpage->write) & RB_WRITE_MASK;
1816 }
1817 
1818 static int
rb_remove_pages(struct ring_buffer_per_cpu * cpu_buffer,unsigned long nr_pages)1819 rb_remove_pages(struct ring_buffer_per_cpu *cpu_buffer, unsigned long nr_pages)
1820 {
1821 	struct list_head *tail_page, *to_remove, *next_page;
1822 	struct buffer_page *to_remove_page, *tmp_iter_page;
1823 	struct buffer_page *last_page, *first_page;
1824 	unsigned long nr_removed;
1825 	unsigned long head_bit;
1826 	int page_entries;
1827 
1828 	head_bit = 0;
1829 
1830 	raw_spin_lock_irq(&cpu_buffer->reader_lock);
1831 	atomic_inc(&cpu_buffer->record_disabled);
1832 	/*
1833 	 * We don't race with the readers since we have acquired the reader
1834 	 * lock. We also don't race with writers after disabling recording.
1835 	 * This makes it easy to figure out the first and the last page to be
1836 	 * removed from the list. We unlink all the pages in between including
1837 	 * the first and last pages. This is done in a busy loop so that we
1838 	 * lose the least number of traces.
1839 	 * The pages are freed after we restart recording and unlock readers.
1840 	 */
1841 	tail_page = &cpu_buffer->tail_page->list;
1842 
1843 	/*
1844 	 * tail page might be on reader page, we remove the next page
1845 	 * from the ring buffer
1846 	 */
1847 	if (cpu_buffer->tail_page == cpu_buffer->reader_page)
1848 		tail_page = rb_list_head(tail_page->next);
1849 	to_remove = tail_page;
1850 
1851 	/* start of pages to remove */
1852 	first_page = list_entry(rb_list_head(to_remove->next),
1853 				struct buffer_page, list);
1854 
1855 	for (nr_removed = 0; nr_removed < nr_pages; nr_removed++) {
1856 		to_remove = rb_list_head(to_remove)->next;
1857 		head_bit |= (unsigned long)to_remove & RB_PAGE_HEAD;
1858 	}
1859 	/* Read iterators need to reset themselves when some pages removed */
1860 	cpu_buffer->pages_removed += nr_removed;
1861 
1862 	next_page = rb_list_head(to_remove)->next;
1863 
1864 	/*
1865 	 * Now we remove all pages between tail_page and next_page.
1866 	 * Make sure that we have head_bit value preserved for the
1867 	 * next page
1868 	 */
1869 	tail_page->next = (struct list_head *)((unsigned long)next_page |
1870 						head_bit);
1871 	next_page = rb_list_head(next_page);
1872 	next_page->prev = tail_page;
1873 
1874 	/* make sure pages points to a valid page in the ring buffer */
1875 	cpu_buffer->pages = next_page;
1876 
1877 	/* update head page */
1878 	if (head_bit)
1879 		cpu_buffer->head_page = list_entry(next_page,
1880 						struct buffer_page, list);
1881 
1882 	/* pages are removed, resume tracing and then free the pages */
1883 	atomic_dec(&cpu_buffer->record_disabled);
1884 	raw_spin_unlock_irq(&cpu_buffer->reader_lock);
1885 
1886 	RB_WARN_ON(cpu_buffer, list_empty(cpu_buffer->pages));
1887 
1888 	/* last buffer page to remove */
1889 	last_page = list_entry(rb_list_head(to_remove), struct buffer_page,
1890 				list);
1891 	tmp_iter_page = first_page;
1892 
1893 	do {
1894 		cond_resched();
1895 
1896 		to_remove_page = tmp_iter_page;
1897 		rb_inc_page(cpu_buffer, &tmp_iter_page);
1898 
1899 		/* update the counters */
1900 		page_entries = rb_page_entries(to_remove_page);
1901 		if (page_entries) {
1902 			/*
1903 			 * If something was added to this page, it was full
1904 			 * since it is not the tail page. So we deduct the
1905 			 * bytes consumed in ring buffer from here.
1906 			 * Increment overrun to account for the lost events.
1907 			 */
1908 			local_add(page_entries, &cpu_buffer->overrun);
1909 			local_sub(rb_page_commit(to_remove_page), &cpu_buffer->entries_bytes);
1910 			local_inc(&cpu_buffer->pages_lost);
1911 		}
1912 
1913 		/*
1914 		 * We have already removed references to this list item, just
1915 		 * free up the buffer_page and its page
1916 		 */
1917 		free_buffer_page(to_remove_page);
1918 		nr_removed--;
1919 
1920 	} while (to_remove_page != last_page);
1921 
1922 	RB_WARN_ON(cpu_buffer, nr_removed);
1923 
1924 	return nr_removed == 0;
1925 }
1926 
1927 static int
rb_insert_pages(struct ring_buffer_per_cpu * cpu_buffer)1928 rb_insert_pages(struct ring_buffer_per_cpu *cpu_buffer)
1929 {
1930 	struct list_head *pages = &cpu_buffer->new_pages;
1931 	int retries, success;
1932 
1933 	raw_spin_lock_irq(&cpu_buffer->reader_lock);
1934 	/*
1935 	 * We are holding the reader lock, so the reader page won't be swapped
1936 	 * in the ring buffer. Now we are racing with the writer trying to
1937 	 * move head page and the tail page.
1938 	 * We are going to adapt the reader page update process where:
1939 	 * 1. We first splice the start and end of list of new pages between
1940 	 *    the head page and its previous page.
1941 	 * 2. We cmpxchg the prev_page->next to point from head page to the
1942 	 *    start of new pages list.
1943 	 * 3. Finally, we update the head->prev to the end of new list.
1944 	 *
1945 	 * We will try this process 10 times, to make sure that we don't keep
1946 	 * spinning.
1947 	 */
1948 	retries = 10;
1949 	success = 0;
1950 	while (retries--) {
1951 		struct list_head *head_page, *prev_page, *r;
1952 		struct list_head *last_page, *first_page;
1953 		struct list_head *head_page_with_bit;
1954 
1955 		head_page = &rb_set_head_page(cpu_buffer)->list;
1956 		if (!head_page)
1957 			break;
1958 		prev_page = head_page->prev;
1959 
1960 		first_page = pages->next;
1961 		last_page  = pages->prev;
1962 
1963 		head_page_with_bit = (struct list_head *)
1964 				     ((unsigned long)head_page | RB_PAGE_HEAD);
1965 
1966 		last_page->next = head_page_with_bit;
1967 		first_page->prev = prev_page;
1968 
1969 		r = cmpxchg(&prev_page->next, head_page_with_bit, first_page);
1970 
1971 		if (r == head_page_with_bit) {
1972 			/*
1973 			 * yay, we replaced the page pointer to our new list,
1974 			 * now, we just have to update to head page's prev
1975 			 * pointer to point to end of list
1976 			 */
1977 			head_page->prev = last_page;
1978 			success = 1;
1979 			break;
1980 		}
1981 	}
1982 
1983 	if (success)
1984 		INIT_LIST_HEAD(pages);
1985 	/*
1986 	 * If we weren't successful in adding in new pages, warn and stop
1987 	 * tracing
1988 	 */
1989 	RB_WARN_ON(cpu_buffer, !success);
1990 	raw_spin_unlock_irq(&cpu_buffer->reader_lock);
1991 
1992 	/* free pages if they weren't inserted */
1993 	if (!success) {
1994 		struct buffer_page *bpage, *tmp;
1995 		list_for_each_entry_safe(bpage, tmp, &cpu_buffer->new_pages,
1996 					 list) {
1997 			list_del_init(&bpage->list);
1998 			free_buffer_page(bpage);
1999 		}
2000 	}
2001 	return success;
2002 }
2003 
rb_update_pages(struct ring_buffer_per_cpu * cpu_buffer)2004 static void rb_update_pages(struct ring_buffer_per_cpu *cpu_buffer)
2005 {
2006 	int success;
2007 
2008 	if (cpu_buffer->nr_pages_to_update > 0)
2009 		success = rb_insert_pages(cpu_buffer);
2010 	else
2011 		success = rb_remove_pages(cpu_buffer,
2012 					-cpu_buffer->nr_pages_to_update);
2013 
2014 	if (success)
2015 		cpu_buffer->nr_pages += cpu_buffer->nr_pages_to_update;
2016 }
2017 
update_pages_handler(struct work_struct * work)2018 static void update_pages_handler(struct work_struct *work)
2019 {
2020 	struct ring_buffer_per_cpu *cpu_buffer = container_of(work,
2021 			struct ring_buffer_per_cpu, update_pages_work);
2022 	rb_update_pages(cpu_buffer);
2023 	complete(&cpu_buffer->update_done);
2024 }
2025 
2026 /**
2027  * ring_buffer_resize - resize the ring buffer
2028  * @buffer: the buffer to resize.
2029  * @size: the new size.
2030  * @cpu_id: the cpu buffer to resize
2031  *
2032  * Minimum size is 2 * BUF_PAGE_SIZE.
2033  *
2034  * Returns 0 on success and < 0 on failure.
2035  */
ring_buffer_resize(struct trace_buffer * buffer,unsigned long size,int cpu_id)2036 int ring_buffer_resize(struct trace_buffer *buffer, unsigned long size,
2037 			int cpu_id)
2038 {
2039 	struct ring_buffer_per_cpu *cpu_buffer;
2040 	unsigned long nr_pages;
2041 	int cpu, err;
2042 
2043 	/*
2044 	 * Always succeed at resizing a non-existent buffer:
2045 	 */
2046 	if (!buffer)
2047 		return 0;
2048 
2049 	/* Make sure the requested buffer exists */
2050 	if (cpu_id != RING_BUFFER_ALL_CPUS &&
2051 	    !cpumask_test_cpu(cpu_id, buffer->cpumask))
2052 		return 0;
2053 
2054 	nr_pages = DIV_ROUND_UP(size, BUF_PAGE_SIZE);
2055 
2056 	/* we need a minimum of two pages */
2057 	if (nr_pages < 2)
2058 		nr_pages = 2;
2059 
2060 	size = nr_pages * BUF_PAGE_SIZE;
2061 
2062 	/* prevent another thread from changing buffer sizes */
2063 	mutex_lock(&buffer->mutex);
2064 	atomic_inc(&buffer->resizing);
2065 
2066 	if (cpu_id == RING_BUFFER_ALL_CPUS) {
2067 		/*
2068 		 * Don't succeed if resizing is disabled, as a reader might be
2069 		 * manipulating the ring buffer and is expecting a sane state while
2070 		 * this is true.
2071 		 */
2072 		for_each_buffer_cpu(buffer, cpu) {
2073 			cpu_buffer = buffer->buffers[cpu];
2074 			if (atomic_read(&cpu_buffer->resize_disabled)) {
2075 				err = -EBUSY;
2076 				goto out_err_unlock;
2077 			}
2078 		}
2079 
2080 		/* calculate the pages to update */
2081 		for_each_buffer_cpu(buffer, cpu) {
2082 			cpu_buffer = buffer->buffers[cpu];
2083 
2084 			cpu_buffer->nr_pages_to_update = nr_pages -
2085 							cpu_buffer->nr_pages;
2086 			/*
2087 			 * nothing more to do for removing pages or no update
2088 			 */
2089 			if (cpu_buffer->nr_pages_to_update <= 0)
2090 				continue;
2091 			/*
2092 			 * to add pages, make sure all new pages can be
2093 			 * allocated without receiving ENOMEM
2094 			 */
2095 			INIT_LIST_HEAD(&cpu_buffer->new_pages);
2096 			if (__rb_allocate_pages(cpu_buffer->nr_pages_to_update,
2097 						&cpu_buffer->new_pages, cpu)) {
2098 				/* not enough memory for new pages */
2099 				err = -ENOMEM;
2100 				goto out_err;
2101 			}
2102 
2103 			cond_resched();
2104 		}
2105 
2106 		get_online_cpus();
2107 		/*
2108 		 * Fire off all the required work handlers
2109 		 * We can't schedule on offline CPUs, but it's not necessary
2110 		 * since we can change their buffer sizes without any race.
2111 		 */
2112 		for_each_buffer_cpu(buffer, cpu) {
2113 			cpu_buffer = buffer->buffers[cpu];
2114 			if (!cpu_buffer->nr_pages_to_update)
2115 				continue;
2116 
2117 			/* Can't run something on an offline CPU. */
2118 			if (!cpu_online(cpu)) {
2119 				rb_update_pages(cpu_buffer);
2120 				cpu_buffer->nr_pages_to_update = 0;
2121 			} else {
2122 				schedule_work_on(cpu,
2123 						&cpu_buffer->update_pages_work);
2124 			}
2125 		}
2126 
2127 		/* wait for all the updates to complete */
2128 		for_each_buffer_cpu(buffer, cpu) {
2129 			cpu_buffer = buffer->buffers[cpu];
2130 			if (!cpu_buffer->nr_pages_to_update)
2131 				continue;
2132 
2133 			if (cpu_online(cpu))
2134 				wait_for_completion(&cpu_buffer->update_done);
2135 			cpu_buffer->nr_pages_to_update = 0;
2136 		}
2137 
2138 		put_online_cpus();
2139 	} else {
2140 		/* Make sure this CPU has been initialized */
2141 		if (!cpumask_test_cpu(cpu_id, buffer->cpumask))
2142 			goto out;
2143 
2144 		cpu_buffer = buffer->buffers[cpu_id];
2145 
2146 		if (nr_pages == cpu_buffer->nr_pages)
2147 			goto out;
2148 
2149 		/*
2150 		 * Don't succeed if resizing is disabled, as a reader might be
2151 		 * manipulating the ring buffer and is expecting a sane state while
2152 		 * this is true.
2153 		 */
2154 		if (atomic_read(&cpu_buffer->resize_disabled)) {
2155 			err = -EBUSY;
2156 			goto out_err_unlock;
2157 		}
2158 
2159 		cpu_buffer->nr_pages_to_update = nr_pages -
2160 						cpu_buffer->nr_pages;
2161 
2162 		INIT_LIST_HEAD(&cpu_buffer->new_pages);
2163 		if (cpu_buffer->nr_pages_to_update > 0 &&
2164 			__rb_allocate_pages(cpu_buffer->nr_pages_to_update,
2165 					    &cpu_buffer->new_pages, cpu_id)) {
2166 			err = -ENOMEM;
2167 			goto out_err;
2168 		}
2169 
2170 		get_online_cpus();
2171 
2172 		/* Can't run something on an offline CPU. */
2173 		if (!cpu_online(cpu_id))
2174 			rb_update_pages(cpu_buffer);
2175 		else {
2176 			schedule_work_on(cpu_id,
2177 					 &cpu_buffer->update_pages_work);
2178 			wait_for_completion(&cpu_buffer->update_done);
2179 		}
2180 
2181 		cpu_buffer->nr_pages_to_update = 0;
2182 		put_online_cpus();
2183 	}
2184 
2185  out:
2186 	/*
2187 	 * The ring buffer resize can happen with the ring buffer
2188 	 * enabled, so that the update disturbs the tracing as little
2189 	 * as possible. But if the buffer is disabled, we do not need
2190 	 * to worry about that, and we can take the time to verify
2191 	 * that the buffer is not corrupt.
2192 	 */
2193 	if (atomic_read(&buffer->record_disabled)) {
2194 		atomic_inc(&buffer->record_disabled);
2195 		/*
2196 		 * Even though the buffer was disabled, we must make sure
2197 		 * that it is truly disabled before calling rb_check_pages.
2198 		 * There could have been a race between checking
2199 		 * record_disable and incrementing it.
2200 		 */
2201 		synchronize_rcu();
2202 		for_each_buffer_cpu(buffer, cpu) {
2203 			unsigned long flags;
2204 
2205 			cpu_buffer = buffer->buffers[cpu];
2206 			raw_spin_lock_irqsave(&cpu_buffer->reader_lock, flags);
2207 			rb_check_pages(cpu_buffer);
2208 			raw_spin_unlock_irqrestore(&cpu_buffer->reader_lock, flags);
2209 		}
2210 		atomic_dec(&buffer->record_disabled);
2211 	}
2212 
2213 	atomic_dec(&buffer->resizing);
2214 	mutex_unlock(&buffer->mutex);
2215 	return 0;
2216 
2217  out_err:
2218 	for_each_buffer_cpu(buffer, cpu) {
2219 		struct buffer_page *bpage, *tmp;
2220 
2221 		cpu_buffer = buffer->buffers[cpu];
2222 		cpu_buffer->nr_pages_to_update = 0;
2223 
2224 		if (list_empty(&cpu_buffer->new_pages))
2225 			continue;
2226 
2227 		list_for_each_entry_safe(bpage, tmp, &cpu_buffer->new_pages,
2228 					list) {
2229 			list_del_init(&bpage->list);
2230 			free_buffer_page(bpage);
2231 		}
2232 	}
2233  out_err_unlock:
2234 	atomic_dec(&buffer->resizing);
2235 	mutex_unlock(&buffer->mutex);
2236 	return err;
2237 }
2238 EXPORT_SYMBOL_GPL(ring_buffer_resize);
2239 
ring_buffer_change_overwrite(struct trace_buffer * buffer,int val)2240 void ring_buffer_change_overwrite(struct trace_buffer *buffer, int val)
2241 {
2242 	mutex_lock(&buffer->mutex);
2243 	if (val)
2244 		buffer->flags |= RB_FL_OVERWRITE;
2245 	else
2246 		buffer->flags &= ~RB_FL_OVERWRITE;
2247 	mutex_unlock(&buffer->mutex);
2248 }
2249 EXPORT_SYMBOL_GPL(ring_buffer_change_overwrite);
2250 
__rb_page_index(struct buffer_page * bpage,unsigned index)2251 static __always_inline void *__rb_page_index(struct buffer_page *bpage, unsigned index)
2252 {
2253 	return bpage->page->data + index;
2254 }
2255 
2256 static __always_inline struct ring_buffer_event *
rb_reader_event(struct ring_buffer_per_cpu * cpu_buffer)2257 rb_reader_event(struct ring_buffer_per_cpu *cpu_buffer)
2258 {
2259 	return __rb_page_index(cpu_buffer->reader_page,
2260 			       cpu_buffer->reader_page->read);
2261 }
2262 
2263 static struct ring_buffer_event *
rb_iter_head_event(struct ring_buffer_iter * iter)2264 rb_iter_head_event(struct ring_buffer_iter *iter)
2265 {
2266 	struct ring_buffer_event *event;
2267 	struct buffer_page *iter_head_page = iter->head_page;
2268 	unsigned long commit;
2269 	unsigned length;
2270 
2271 	if (iter->head != iter->next_event)
2272 		return iter->event;
2273 
2274 	/*
2275 	 * When the writer goes across pages, it issues a cmpxchg which
2276 	 * is a mb(), which will synchronize with the rmb here.
2277 	 * (see rb_tail_page_update() and __rb_reserve_next())
2278 	 */
2279 	commit = rb_page_commit(iter_head_page);
2280 	smp_rmb();
2281 
2282 	/* An event needs to be at least 8 bytes in size */
2283 	if (iter->head > commit - 8)
2284 		goto reset;
2285 
2286 	event = __rb_page_index(iter_head_page, iter->head);
2287 	length = rb_event_length(event);
2288 
2289 	/*
2290 	 * READ_ONCE() doesn't work on functions and we don't want the
2291 	 * compiler doing any crazy optimizations with length.
2292 	 */
2293 	barrier();
2294 
2295 	if ((iter->head + length) > commit || length > BUF_PAGE_SIZE)
2296 		/* Writer corrupted the read? */
2297 		goto reset;
2298 
2299 	memcpy(iter->event, event, length);
2300 	/*
2301 	 * If the page stamp is still the same after this rmb() then the
2302 	 * event was safely copied without the writer entering the page.
2303 	 */
2304 	smp_rmb();
2305 
2306 	/* Make sure the page didn't change since we read this */
2307 	if (iter->page_stamp != iter_head_page->page->time_stamp ||
2308 	    commit > rb_page_commit(iter_head_page))
2309 		goto reset;
2310 
2311 	iter->next_event = iter->head + length;
2312 	return iter->event;
2313  reset:
2314 	/* Reset to the beginning */
2315 	iter->page_stamp = iter->read_stamp = iter->head_page->page->time_stamp;
2316 	iter->head = 0;
2317 	iter->next_event = 0;
2318 	iter->missed_events = 1;
2319 	return NULL;
2320 }
2321 
2322 /* Size is determined by what has been committed */
rb_page_size(struct buffer_page * bpage)2323 static __always_inline unsigned rb_page_size(struct buffer_page *bpage)
2324 {
2325 	return rb_page_commit(bpage);
2326 }
2327 
2328 static __always_inline unsigned
rb_commit_index(struct ring_buffer_per_cpu * cpu_buffer)2329 rb_commit_index(struct ring_buffer_per_cpu *cpu_buffer)
2330 {
2331 	return rb_page_commit(cpu_buffer->commit_page);
2332 }
2333 
2334 static __always_inline unsigned
rb_event_index(struct ring_buffer_event * event)2335 rb_event_index(struct ring_buffer_event *event)
2336 {
2337 	unsigned long addr = (unsigned long)event;
2338 
2339 	return (addr & ~PAGE_MASK) - BUF_PAGE_HDR_SIZE;
2340 }
2341 
rb_inc_iter(struct ring_buffer_iter * iter)2342 static void rb_inc_iter(struct ring_buffer_iter *iter)
2343 {
2344 	struct ring_buffer_per_cpu *cpu_buffer = iter->cpu_buffer;
2345 
2346 	/*
2347 	 * The iterator could be on the reader page (it starts there).
2348 	 * But the head could have moved, since the reader was
2349 	 * found. Check for this case and assign the iterator
2350 	 * to the head page instead of next.
2351 	 */
2352 	if (iter->head_page == cpu_buffer->reader_page)
2353 		iter->head_page = rb_set_head_page(cpu_buffer);
2354 	else
2355 		rb_inc_page(cpu_buffer, &iter->head_page);
2356 
2357 	iter->page_stamp = iter->read_stamp = iter->head_page->page->time_stamp;
2358 	iter->head = 0;
2359 	iter->next_event = 0;
2360 }
2361 
2362 /*
2363  * rb_handle_head_page - writer hit the head page
2364  *
2365  * Returns: +1 to retry page
2366  *           0 to continue
2367  *          -1 on error
2368  */
2369 static int
rb_handle_head_page(struct ring_buffer_per_cpu * cpu_buffer,struct buffer_page * tail_page,struct buffer_page * next_page)2370 rb_handle_head_page(struct ring_buffer_per_cpu *cpu_buffer,
2371 		    struct buffer_page *tail_page,
2372 		    struct buffer_page *next_page)
2373 {
2374 	struct buffer_page *new_head;
2375 	int entries;
2376 	int type;
2377 	int ret;
2378 
2379 	entries = rb_page_entries(next_page);
2380 
2381 	/*
2382 	 * The hard part is here. We need to move the head
2383 	 * forward, and protect against both readers on
2384 	 * other CPUs and writers coming in via interrupts.
2385 	 */
2386 	type = rb_head_page_set_update(cpu_buffer, next_page, tail_page,
2387 				       RB_PAGE_HEAD);
2388 
2389 	/*
2390 	 * type can be one of four:
2391 	 *  NORMAL - an interrupt already moved it for us
2392 	 *  HEAD   - we are the first to get here.
2393 	 *  UPDATE - we are the interrupt interrupting
2394 	 *           a current move.
2395 	 *  MOVED  - a reader on another CPU moved the next
2396 	 *           pointer to its reader page. Give up
2397 	 *           and try again.
2398 	 */
2399 
2400 	switch (type) {
2401 	case RB_PAGE_HEAD:
2402 		/*
2403 		 * We changed the head to UPDATE, thus
2404 		 * it is our responsibility to update
2405 		 * the counters.
2406 		 */
2407 		local_add(entries, &cpu_buffer->overrun);
2408 		local_sub(rb_page_commit(next_page), &cpu_buffer->entries_bytes);
2409 		local_inc(&cpu_buffer->pages_lost);
2410 
2411 		/*
2412 		 * The entries will be zeroed out when we move the
2413 		 * tail page.
2414 		 */
2415 
2416 		/* still more to do */
2417 		break;
2418 
2419 	case RB_PAGE_UPDATE:
2420 		/*
2421 		 * This is an interrupt that interrupt the
2422 		 * previous update. Still more to do.
2423 		 */
2424 		break;
2425 	case RB_PAGE_NORMAL:
2426 		/*
2427 		 * An interrupt came in before the update
2428 		 * and processed this for us.
2429 		 * Nothing left to do.
2430 		 */
2431 		return 1;
2432 	case RB_PAGE_MOVED:
2433 		/*
2434 		 * The reader is on another CPU and just did
2435 		 * a swap with our next_page.
2436 		 * Try again.
2437 		 */
2438 		return 1;
2439 	default:
2440 		RB_WARN_ON(cpu_buffer, 1); /* WTF??? */
2441 		return -1;
2442 	}
2443 
2444 	/*
2445 	 * Now that we are here, the old head pointer is
2446 	 * set to UPDATE. This will keep the reader from
2447 	 * swapping the head page with the reader page.
2448 	 * The reader (on another CPU) will spin till
2449 	 * we are finished.
2450 	 *
2451 	 * We just need to protect against interrupts
2452 	 * doing the job. We will set the next pointer
2453 	 * to HEAD. After that, we set the old pointer
2454 	 * to NORMAL, but only if it was HEAD before.
2455 	 * otherwise we are an interrupt, and only
2456 	 * want the outer most commit to reset it.
2457 	 */
2458 	new_head = next_page;
2459 	rb_inc_page(cpu_buffer, &new_head);
2460 
2461 	ret = rb_head_page_set_head(cpu_buffer, new_head, next_page,
2462 				    RB_PAGE_NORMAL);
2463 
2464 	/*
2465 	 * Valid returns are:
2466 	 *  HEAD   - an interrupt came in and already set it.
2467 	 *  NORMAL - One of two things:
2468 	 *            1) We really set it.
2469 	 *            2) A bunch of interrupts came in and moved
2470 	 *               the page forward again.
2471 	 */
2472 	switch (ret) {
2473 	case RB_PAGE_HEAD:
2474 	case RB_PAGE_NORMAL:
2475 		/* OK */
2476 		break;
2477 	default:
2478 		RB_WARN_ON(cpu_buffer, 1);
2479 		return -1;
2480 	}
2481 
2482 	/*
2483 	 * It is possible that an interrupt came in,
2484 	 * set the head up, then more interrupts came in
2485 	 * and moved it again. When we get back here,
2486 	 * the page would have been set to NORMAL but we
2487 	 * just set it back to HEAD.
2488 	 *
2489 	 * How do you detect this? Well, if that happened
2490 	 * the tail page would have moved.
2491 	 */
2492 	if (ret == RB_PAGE_NORMAL) {
2493 		struct buffer_page *buffer_tail_page;
2494 
2495 		buffer_tail_page = READ_ONCE(cpu_buffer->tail_page);
2496 		/*
2497 		 * If the tail had moved passed next, then we need
2498 		 * to reset the pointer.
2499 		 */
2500 		if (buffer_tail_page != tail_page &&
2501 		    buffer_tail_page != next_page)
2502 			rb_head_page_set_normal(cpu_buffer, new_head,
2503 						next_page,
2504 						RB_PAGE_HEAD);
2505 	}
2506 
2507 	/*
2508 	 * If this was the outer most commit (the one that
2509 	 * changed the original pointer from HEAD to UPDATE),
2510 	 * then it is up to us to reset it to NORMAL.
2511 	 */
2512 	if (type == RB_PAGE_HEAD) {
2513 		ret = rb_head_page_set_normal(cpu_buffer, next_page,
2514 					      tail_page,
2515 					      RB_PAGE_UPDATE);
2516 		if (RB_WARN_ON(cpu_buffer,
2517 			       ret != RB_PAGE_UPDATE))
2518 			return -1;
2519 	}
2520 
2521 	return 0;
2522 }
2523 
2524 static inline void
rb_reset_tail(struct ring_buffer_per_cpu * cpu_buffer,unsigned long tail,struct rb_event_info * info)2525 rb_reset_tail(struct ring_buffer_per_cpu *cpu_buffer,
2526 	      unsigned long tail, struct rb_event_info *info)
2527 {
2528 	struct buffer_page *tail_page = info->tail_page;
2529 	struct ring_buffer_event *event;
2530 	unsigned long length = info->length;
2531 
2532 	/*
2533 	 * Only the event that crossed the page boundary
2534 	 * must fill the old tail_page with padding.
2535 	 */
2536 	if (tail >= BUF_PAGE_SIZE) {
2537 		/*
2538 		 * If the page was filled, then we still need
2539 		 * to update the real_end. Reset it to zero
2540 		 * and the reader will ignore it.
2541 		 */
2542 		if (tail == BUF_PAGE_SIZE)
2543 			tail_page->real_end = 0;
2544 
2545 		local_sub(length, &tail_page->write);
2546 		return;
2547 	}
2548 
2549 	event = __rb_page_index(tail_page, tail);
2550 
2551 	/*
2552 	 * Save the original length to the meta data.
2553 	 * This will be used by the reader to add lost event
2554 	 * counter.
2555 	 */
2556 	tail_page->real_end = tail;
2557 
2558 	/*
2559 	 * If this event is bigger than the minimum size, then
2560 	 * we need to be careful that we don't subtract the
2561 	 * write counter enough to allow another writer to slip
2562 	 * in on this page.
2563 	 * We put in a discarded commit instead, to make sure
2564 	 * that this space is not used again, and this space will
2565 	 * not be accounted into 'entries_bytes'.
2566 	 *
2567 	 * If we are less than the minimum size, we don't need to
2568 	 * worry about it.
2569 	 */
2570 	if (tail > (BUF_PAGE_SIZE - RB_EVNT_MIN_SIZE)) {
2571 		/* No room for any events */
2572 
2573 		/* Mark the rest of the page with padding */
2574 		rb_event_set_padding(event);
2575 
2576 		/* Make sure the padding is visible before the write update */
2577 		smp_wmb();
2578 
2579 		/* Set the write back to the previous setting */
2580 		local_sub(length, &tail_page->write);
2581 		return;
2582 	}
2583 
2584 	/* Put in a discarded event */
2585 	event->array[0] = (BUF_PAGE_SIZE - tail) - RB_EVNT_HDR_SIZE;
2586 	event->type_len = RINGBUF_TYPE_PADDING;
2587 	/* time delta must be non zero */
2588 	event->time_delta = 1;
2589 
2590 	/* account for padding bytes */
2591 	local_add(BUF_PAGE_SIZE - tail, &cpu_buffer->entries_bytes);
2592 
2593 	/* Make sure the padding is visible before the tail_page->write update */
2594 	smp_wmb();
2595 
2596 	/* Set write to end of buffer */
2597 	length = (tail + length) - BUF_PAGE_SIZE;
2598 	local_sub(length, &tail_page->write);
2599 }
2600 
2601 static inline void rb_end_commit(struct ring_buffer_per_cpu *cpu_buffer);
2602 
2603 /*
2604  * This is the slow path, force gcc not to inline it.
2605  */
2606 static noinline struct ring_buffer_event *
rb_move_tail(struct ring_buffer_per_cpu * cpu_buffer,unsigned long tail,struct rb_event_info * info)2607 rb_move_tail(struct ring_buffer_per_cpu *cpu_buffer,
2608 	     unsigned long tail, struct rb_event_info *info)
2609 {
2610 	struct buffer_page *tail_page = info->tail_page;
2611 	struct buffer_page *commit_page = cpu_buffer->commit_page;
2612 	struct trace_buffer *buffer = cpu_buffer->buffer;
2613 	struct buffer_page *next_page;
2614 	int ret;
2615 
2616 	next_page = tail_page;
2617 
2618 	rb_inc_page(cpu_buffer, &next_page);
2619 
2620 	/*
2621 	 * If for some reason, we had an interrupt storm that made
2622 	 * it all the way around the buffer, bail, and warn
2623 	 * about it.
2624 	 */
2625 	if (unlikely(next_page == commit_page)) {
2626 		local_inc(&cpu_buffer->commit_overrun);
2627 		goto out_reset;
2628 	}
2629 
2630 	/*
2631 	 * This is where the fun begins!
2632 	 *
2633 	 * We are fighting against races between a reader that
2634 	 * could be on another CPU trying to swap its reader
2635 	 * page with the buffer head.
2636 	 *
2637 	 * We are also fighting against interrupts coming in and
2638 	 * moving the head or tail on us as well.
2639 	 *
2640 	 * If the next page is the head page then we have filled
2641 	 * the buffer, unless the commit page is still on the
2642 	 * reader page.
2643 	 */
2644 	if (rb_is_head_page(cpu_buffer, next_page, &tail_page->list)) {
2645 
2646 		/*
2647 		 * If the commit is not on the reader page, then
2648 		 * move the header page.
2649 		 */
2650 		if (!rb_is_reader_page(cpu_buffer->commit_page)) {
2651 			/*
2652 			 * If we are not in overwrite mode,
2653 			 * this is easy, just stop here.
2654 			 */
2655 			if (!(buffer->flags & RB_FL_OVERWRITE)) {
2656 				local_inc(&cpu_buffer->dropped_events);
2657 				goto out_reset;
2658 			}
2659 
2660 			ret = rb_handle_head_page(cpu_buffer,
2661 						  tail_page,
2662 						  next_page);
2663 			if (ret < 0)
2664 				goto out_reset;
2665 			if (ret)
2666 				goto out_again;
2667 		} else {
2668 			/*
2669 			 * We need to be careful here too. The
2670 			 * commit page could still be on the reader
2671 			 * page. We could have a small buffer, and
2672 			 * have filled up the buffer with events
2673 			 * from interrupts and such, and wrapped.
2674 			 *
2675 			 * Note, if the tail page is also the on the
2676 			 * reader_page, we let it move out.
2677 			 */
2678 			if (unlikely((cpu_buffer->commit_page !=
2679 				      cpu_buffer->tail_page) &&
2680 				     (cpu_buffer->commit_page ==
2681 				      cpu_buffer->reader_page))) {
2682 				local_inc(&cpu_buffer->commit_overrun);
2683 				goto out_reset;
2684 			}
2685 		}
2686 	}
2687 
2688 	rb_tail_page_update(cpu_buffer, tail_page, next_page);
2689 
2690  out_again:
2691 
2692 	rb_reset_tail(cpu_buffer, tail, info);
2693 
2694 	/* Commit what we have for now. */
2695 	rb_end_commit(cpu_buffer);
2696 	/* rb_end_commit() decs committing */
2697 	local_inc(&cpu_buffer->committing);
2698 
2699 	/* fail and let the caller try again */
2700 	return ERR_PTR(-EAGAIN);
2701 
2702  out_reset:
2703 	/* reset write */
2704 	rb_reset_tail(cpu_buffer, tail, info);
2705 
2706 	return NULL;
2707 }
2708 
2709 /* Slow path */
2710 static struct ring_buffer_event *
rb_add_time_stamp(struct ring_buffer_event * event,u64 delta,bool abs)2711 rb_add_time_stamp(struct ring_buffer_event *event, u64 delta, bool abs)
2712 {
2713 	if (abs)
2714 		event->type_len = RINGBUF_TYPE_TIME_STAMP;
2715 	else
2716 		event->type_len = RINGBUF_TYPE_TIME_EXTEND;
2717 
2718 	/* Not the first event on the page, or not delta? */
2719 	if (abs || rb_event_index(event)) {
2720 		event->time_delta = delta & TS_MASK;
2721 		event->array[0] = delta >> TS_SHIFT;
2722 	} else {
2723 		/* nope, just zero it */
2724 		event->time_delta = 0;
2725 		event->array[0] = 0;
2726 	}
2727 
2728 	return skip_time_extend(event);
2729 }
2730 
2731 static inline bool rb_event_is_commit(struct ring_buffer_per_cpu *cpu_buffer,
2732 				     struct ring_buffer_event *event);
2733 
2734 #ifndef CONFIG_HAVE_UNSTABLE_SCHED_CLOCK
sched_clock_stable(void)2735 static inline bool sched_clock_stable(void)
2736 {
2737 	return true;
2738 }
2739 #endif
2740 
2741 static void
rb_check_timestamp(struct ring_buffer_per_cpu * cpu_buffer,struct rb_event_info * info)2742 rb_check_timestamp(struct ring_buffer_per_cpu *cpu_buffer,
2743 		   struct rb_event_info *info)
2744 {
2745 	u64 write_stamp;
2746 
2747 	WARN_ONCE(1, "Delta way too big! %llu ts=%llu before=%llu after=%llu write stamp=%llu\n%s",
2748 		  (unsigned long long)info->delta,
2749 		  (unsigned long long)info->ts,
2750 		  (unsigned long long)info->before,
2751 		  (unsigned long long)info->after,
2752 		  (unsigned long long)(rb_time_read(&cpu_buffer->write_stamp, &write_stamp) ? write_stamp : 0),
2753 		  sched_clock_stable() ? "" :
2754 		  "If you just came from a suspend/resume,\n"
2755 		  "please switch to the trace global clock:\n"
2756 		  "  echo global > /sys/kernel/debug/tracing/trace_clock\n"
2757 		  "or add trace_clock=global to the kernel command line\n");
2758 }
2759 
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)2760 static void rb_add_timestamp(struct ring_buffer_per_cpu *cpu_buffer,
2761 				      struct ring_buffer_event **event,
2762 				      struct rb_event_info *info,
2763 				      u64 *delta,
2764 				      unsigned int *length)
2765 {
2766 	bool abs = info->add_timestamp &
2767 		(RB_ADD_STAMP_FORCE | RB_ADD_STAMP_ABSOLUTE);
2768 
2769 	if (unlikely(info->delta > (1ULL << 59))) {
2770 		/* did the clock go backwards */
2771 		if (info->before == info->after && info->before > info->ts) {
2772 			/* not interrupted */
2773 			static int once;
2774 
2775 			/*
2776 			 * This is possible with a recalibrating of the TSC.
2777 			 * Do not produce a call stack, but just report it.
2778 			 */
2779 			if (!once) {
2780 				once++;
2781 				pr_warn("Ring buffer clock went backwards: %llu -> %llu\n",
2782 					info->before, info->ts);
2783 			}
2784 		} else
2785 			rb_check_timestamp(cpu_buffer, info);
2786 		if (!abs)
2787 			info->delta = 0;
2788 	}
2789 	*event = rb_add_time_stamp(*event, info->delta, abs);
2790 	*length -= RB_LEN_TIME_EXTEND;
2791 	*delta = 0;
2792 }
2793 
2794 /**
2795  * rb_update_event - update event type and data
2796  * @cpu_buffer: The per cpu buffer of the @event
2797  * @event: the event to update
2798  * @info: The info to update the @event with (contains length and delta)
2799  *
2800  * Update the type and data fields of the @event. The length
2801  * is the actual size that is written to the ring buffer,
2802  * and with this, we can determine what to place into the
2803  * data field.
2804  */
2805 static void
rb_update_event(struct ring_buffer_per_cpu * cpu_buffer,struct ring_buffer_event * event,struct rb_event_info * info)2806 rb_update_event(struct ring_buffer_per_cpu *cpu_buffer,
2807 		struct ring_buffer_event *event,
2808 		struct rb_event_info *info)
2809 {
2810 	unsigned length = info->length;
2811 	u64 delta = info->delta;
2812 
2813 	/*
2814 	 * If we need to add a timestamp, then we
2815 	 * add it to the start of the reserved space.
2816 	 */
2817 	if (unlikely(info->add_timestamp))
2818 		rb_add_timestamp(cpu_buffer, &event, info, &delta, &length);
2819 
2820 	event->time_delta = delta;
2821 	length -= RB_EVNT_HDR_SIZE;
2822 	if (length > RB_MAX_SMALL_DATA || RB_FORCE_8BYTE_ALIGNMENT) {
2823 		event->type_len = 0;
2824 		event->array[0] = length;
2825 	} else
2826 		event->type_len = DIV_ROUND_UP(length, RB_ALIGNMENT);
2827 }
2828 
rb_calculate_event_length(unsigned length)2829 static unsigned rb_calculate_event_length(unsigned length)
2830 {
2831 	struct ring_buffer_event event; /* Used only for sizeof array */
2832 
2833 	/* zero length can cause confusions */
2834 	if (!length)
2835 		length++;
2836 
2837 	if (length > RB_MAX_SMALL_DATA || RB_FORCE_8BYTE_ALIGNMENT)
2838 		length += sizeof(event.array[0]);
2839 
2840 	length += RB_EVNT_HDR_SIZE;
2841 	length = ALIGN(length, RB_ARCH_ALIGNMENT);
2842 
2843 	/*
2844 	 * In case the time delta is larger than the 27 bits for it
2845 	 * in the header, we need to add a timestamp. If another
2846 	 * event comes in when trying to discard this one to increase
2847 	 * the length, then the timestamp will be added in the allocated
2848 	 * space of this event. If length is bigger than the size needed
2849 	 * for the TIME_EXTEND, then padding has to be used. The events
2850 	 * length must be either RB_LEN_TIME_EXTEND, or greater than or equal
2851 	 * to RB_LEN_TIME_EXTEND + 8, as 8 is the minimum size for padding.
2852 	 * As length is a multiple of 4, we only need to worry if it
2853 	 * is 12 (RB_LEN_TIME_EXTEND + 4).
2854 	 */
2855 	if (length == RB_LEN_TIME_EXTEND + RB_ALIGNMENT)
2856 		length += RB_ALIGNMENT;
2857 
2858 	return length;
2859 }
2860 
2861 static __always_inline bool
rb_event_is_commit(struct ring_buffer_per_cpu * cpu_buffer,struct ring_buffer_event * event)2862 rb_event_is_commit(struct ring_buffer_per_cpu *cpu_buffer,
2863 		   struct ring_buffer_event *event)
2864 {
2865 	unsigned long addr = (unsigned long)event;
2866 	unsigned long index;
2867 
2868 	index = rb_event_index(event);
2869 	addr &= PAGE_MASK;
2870 
2871 	return cpu_buffer->commit_page->page == (void *)addr &&
2872 		rb_commit_index(cpu_buffer) == index;
2873 }
2874 
rb_time_delta(struct ring_buffer_event * event)2875 static u64 rb_time_delta(struct ring_buffer_event *event)
2876 {
2877 	switch (event->type_len) {
2878 	case RINGBUF_TYPE_PADDING:
2879 		return 0;
2880 
2881 	case RINGBUF_TYPE_TIME_EXTEND:
2882 		return ring_buffer_event_time_stamp(event);
2883 
2884 	case RINGBUF_TYPE_TIME_STAMP:
2885 		return 0;
2886 
2887 	case RINGBUF_TYPE_DATA:
2888 		return event->time_delta;
2889 	default:
2890 		return 0;
2891 	}
2892 }
2893 
2894 static inline int
rb_try_to_discard(struct ring_buffer_per_cpu * cpu_buffer,struct ring_buffer_event * event)2895 rb_try_to_discard(struct ring_buffer_per_cpu *cpu_buffer,
2896 		  struct ring_buffer_event *event)
2897 {
2898 	unsigned long new_index, old_index;
2899 	struct buffer_page *bpage;
2900 	unsigned long index;
2901 	unsigned long addr;
2902 	u64 write_stamp;
2903 	u64 delta;
2904 
2905 	new_index = rb_event_index(event);
2906 	old_index = new_index + rb_event_ts_length(event);
2907 	addr = (unsigned long)event;
2908 	addr &= PAGE_MASK;
2909 
2910 	bpage = READ_ONCE(cpu_buffer->tail_page);
2911 
2912 	delta = rb_time_delta(event);
2913 
2914 	if (!rb_time_read(&cpu_buffer->write_stamp, &write_stamp))
2915 		return 0;
2916 
2917 	/* Make sure the write stamp is read before testing the location */
2918 	barrier();
2919 
2920 	if (bpage->page == (void *)addr && rb_page_write(bpage) == old_index) {
2921 		unsigned long write_mask =
2922 			local_read(&bpage->write) & ~RB_WRITE_MASK;
2923 		unsigned long event_length = rb_event_length(event);
2924 
2925 		/*
2926 		 * For the before_stamp to be different than the write_stamp
2927 		 * to make sure that the next event adds an absolute
2928 		 * value and does not rely on the saved write stamp, which
2929 		 * is now going to be bogus.
2930 		 */
2931 		rb_time_set(&cpu_buffer->before_stamp, 0);
2932 
2933 		/* Something came in, can't discard */
2934 		if (!rb_time_cmpxchg(&cpu_buffer->write_stamp,
2935 				       write_stamp, write_stamp - delta))
2936 			return 0;
2937 
2938 		/*
2939 		 * If an event were to come in now, it would see that the
2940 		 * write_stamp and the before_stamp are different, and assume
2941 		 * that this event just added itself before updating
2942 		 * the write stamp. The interrupting event will fix the
2943 		 * write stamp for us, and use the before stamp as its delta.
2944 		 */
2945 
2946 		/*
2947 		 * This is on the tail page. It is possible that
2948 		 * a write could come in and move the tail page
2949 		 * and write to the next page. That is fine
2950 		 * because we just shorten what is on this page.
2951 		 */
2952 		old_index += write_mask;
2953 		new_index += write_mask;
2954 		index = local_cmpxchg(&bpage->write, old_index, new_index);
2955 		if (index == old_index) {
2956 			/* update counters */
2957 			local_sub(event_length, &cpu_buffer->entries_bytes);
2958 			return 1;
2959 		}
2960 	}
2961 
2962 	/* could not discard */
2963 	return 0;
2964 }
2965 
rb_start_commit(struct ring_buffer_per_cpu * cpu_buffer)2966 static void rb_start_commit(struct ring_buffer_per_cpu *cpu_buffer)
2967 {
2968 	local_inc(&cpu_buffer->committing);
2969 	local_inc(&cpu_buffer->commits);
2970 }
2971 
2972 static __always_inline void
rb_set_commit_to_write(struct ring_buffer_per_cpu * cpu_buffer)2973 rb_set_commit_to_write(struct ring_buffer_per_cpu *cpu_buffer)
2974 {
2975 	unsigned long max_count;
2976 
2977 	/*
2978 	 * We only race with interrupts and NMIs on this CPU.
2979 	 * If we own the commit event, then we can commit
2980 	 * all others that interrupted us, since the interruptions
2981 	 * are in stack format (they finish before they come
2982 	 * back to us). This allows us to do a simple loop to
2983 	 * assign the commit to the tail.
2984 	 */
2985  again:
2986 	max_count = cpu_buffer->nr_pages * 100;
2987 
2988 	while (cpu_buffer->commit_page != READ_ONCE(cpu_buffer->tail_page)) {
2989 		if (RB_WARN_ON(cpu_buffer, !(--max_count)))
2990 			return;
2991 		if (RB_WARN_ON(cpu_buffer,
2992 			       rb_is_reader_page(cpu_buffer->tail_page)))
2993 			return;
2994 		/*
2995 		 * No need for a memory barrier here, as the update
2996 		 * of the tail_page did it for this page.
2997 		 */
2998 		local_set(&cpu_buffer->commit_page->page->commit,
2999 			  rb_page_write(cpu_buffer->commit_page));
3000 		rb_inc_page(cpu_buffer, &cpu_buffer->commit_page);
3001 		/* add barrier to keep gcc from optimizing too much */
3002 		barrier();
3003 	}
3004 	while (rb_commit_index(cpu_buffer) !=
3005 	       rb_page_write(cpu_buffer->commit_page)) {
3006 
3007 		/* Make sure the readers see the content of what is committed. */
3008 		smp_wmb();
3009 		local_set(&cpu_buffer->commit_page->page->commit,
3010 			  rb_page_write(cpu_buffer->commit_page));
3011 		RB_WARN_ON(cpu_buffer,
3012 			   local_read(&cpu_buffer->commit_page->page->commit) &
3013 			   ~RB_WRITE_MASK);
3014 		barrier();
3015 	}
3016 
3017 	/* again, keep gcc from optimizing */
3018 	barrier();
3019 
3020 	/*
3021 	 * If an interrupt came in just after the first while loop
3022 	 * and pushed the tail page forward, we will be left with
3023 	 * a dangling commit that will never go forward.
3024 	 */
3025 	if (unlikely(cpu_buffer->commit_page != READ_ONCE(cpu_buffer->tail_page)))
3026 		goto again;
3027 }
3028 
rb_end_commit(struct ring_buffer_per_cpu * cpu_buffer)3029 static __always_inline void rb_end_commit(struct ring_buffer_per_cpu *cpu_buffer)
3030 {
3031 	unsigned long commits;
3032 
3033 	if (RB_WARN_ON(cpu_buffer,
3034 		       !local_read(&cpu_buffer->committing)))
3035 		return;
3036 
3037  again:
3038 	commits = local_read(&cpu_buffer->commits);
3039 	/* synchronize with interrupts */
3040 	barrier();
3041 	if (local_read(&cpu_buffer->committing) == 1)
3042 		rb_set_commit_to_write(cpu_buffer);
3043 
3044 	local_dec(&cpu_buffer->committing);
3045 
3046 	/* synchronize with interrupts */
3047 	barrier();
3048 
3049 	/*
3050 	 * Need to account for interrupts coming in between the
3051 	 * updating of the commit page and the clearing of the
3052 	 * committing counter.
3053 	 */
3054 	if (unlikely(local_read(&cpu_buffer->commits) != commits) &&
3055 	    !local_read(&cpu_buffer->committing)) {
3056 		local_inc(&cpu_buffer->committing);
3057 		goto again;
3058 	}
3059 }
3060 
rb_event_discard(struct ring_buffer_event * event)3061 static inline void rb_event_discard(struct ring_buffer_event *event)
3062 {
3063 	if (extended_time(event))
3064 		event = skip_time_extend(event);
3065 
3066 	/* array[0] holds the actual length for the discarded event */
3067 	event->array[0] = rb_event_data_length(event) - RB_EVNT_HDR_SIZE;
3068 	event->type_len = RINGBUF_TYPE_PADDING;
3069 	/* time delta must be non zero */
3070 	if (!event->time_delta)
3071 		event->time_delta = 1;
3072 }
3073 
rb_commit(struct ring_buffer_per_cpu * cpu_buffer,struct ring_buffer_event * event)3074 static void rb_commit(struct ring_buffer_per_cpu *cpu_buffer,
3075 		      struct ring_buffer_event *event)
3076 {
3077 	local_inc(&cpu_buffer->entries);
3078 	rb_end_commit(cpu_buffer);
3079 }
3080 
3081 static __always_inline void
rb_wakeups(struct trace_buffer * buffer,struct ring_buffer_per_cpu * cpu_buffer)3082 rb_wakeups(struct trace_buffer *buffer, struct ring_buffer_per_cpu *cpu_buffer)
3083 {
3084 	if (buffer->irq_work.waiters_pending) {
3085 		buffer->irq_work.waiters_pending = false;
3086 		/* irq_work_queue() supplies it's own memory barriers */
3087 		irq_work_queue(&buffer->irq_work.work);
3088 	}
3089 
3090 	if (cpu_buffer->irq_work.waiters_pending) {
3091 		cpu_buffer->irq_work.waiters_pending = false;
3092 		/* irq_work_queue() supplies it's own memory barriers */
3093 		irq_work_queue(&cpu_buffer->irq_work.work);
3094 	}
3095 
3096 	if (cpu_buffer->last_pages_touch == local_read(&cpu_buffer->pages_touched))
3097 		return;
3098 
3099 	if (cpu_buffer->reader_page == cpu_buffer->commit_page)
3100 		return;
3101 
3102 	if (!cpu_buffer->irq_work.full_waiters_pending)
3103 		return;
3104 
3105 	cpu_buffer->last_pages_touch = local_read(&cpu_buffer->pages_touched);
3106 
3107 	if (!full_hit(buffer, cpu_buffer->cpu, cpu_buffer->shortest_full))
3108 		return;
3109 
3110 	cpu_buffer->irq_work.wakeup_full = true;
3111 	cpu_buffer->irq_work.full_waiters_pending = false;
3112 	/* irq_work_queue() supplies it's own memory barriers */
3113 	irq_work_queue(&cpu_buffer->irq_work.work);
3114 }
3115 
3116 /*
3117  * The lock and unlock are done within a preempt disable section.
3118  * The current_context per_cpu variable can only be modified
3119  * by the current task between lock and unlock. But it can
3120  * be modified more than once via an interrupt. To pass this
3121  * information from the lock to the unlock without having to
3122  * access the 'in_interrupt()' functions again (which do show
3123  * a bit of overhead in something as critical as function tracing,
3124  * we use a bitmask trick.
3125  *
3126  *  bit 1 =  NMI context
3127  *  bit 2 =  IRQ context
3128  *  bit 3 =  SoftIRQ context
3129  *  bit 4 =  normal context.
3130  *
3131  * This works because this is the order of contexts that can
3132  * preempt other contexts. A SoftIRQ never preempts an IRQ
3133  * context.
3134  *
3135  * When the context is determined, the corresponding bit is
3136  * checked and set (if it was set, then a recursion of that context
3137  * happened).
3138  *
3139  * On unlock, we need to clear this bit. To do so, just subtract
3140  * 1 from the current_context and AND it to itself.
3141  *
3142  * (binary)
3143  *  101 - 1 = 100
3144  *  101 & 100 = 100 (clearing bit zero)
3145  *
3146  *  1010 - 1 = 1001
3147  *  1010 & 1001 = 1000 (clearing bit 1)
3148  *
3149  * The least significant bit can be cleared this way, and it
3150  * just so happens that it is the same bit corresponding to
3151  * the current context.
3152  *
3153  * Now the TRANSITION bit breaks the above slightly. The TRANSITION bit
3154  * is set when a recursion is detected at the current context, and if
3155  * the TRANSITION bit is already set, it will fail the recursion.
3156  * This is needed because there's a lag between the changing of
3157  * interrupt context and updating the preempt count. In this case,
3158  * a false positive will be found. To handle this, one extra recursion
3159  * is allowed, and this is done by the TRANSITION bit. If the TRANSITION
3160  * bit is already set, then it is considered a recursion and the function
3161  * ends. Otherwise, the TRANSITION bit is set, and that bit is returned.
3162  *
3163  * On the trace_recursive_unlock(), the TRANSITION bit will be the first
3164  * to be cleared. Even if it wasn't the context that set it. That is,
3165  * if an interrupt comes in while NORMAL bit is set and the ring buffer
3166  * is called before preempt_count() is updated, since the check will
3167  * be on the NORMAL bit, the TRANSITION bit will then be set. If an
3168  * NMI then comes in, it will set the NMI bit, but when the NMI code
3169  * does the trace_recursive_unlock() it will clear the TRANSTION bit
3170  * and leave the NMI bit set. But this is fine, because the interrupt
3171  * code that set the TRANSITION bit will then clear the NMI bit when it
3172  * calls trace_recursive_unlock(). If another NMI comes in, it will
3173  * set the TRANSITION bit and continue.
3174  *
3175  * Note: The TRANSITION bit only handles a single transition between context.
3176  */
3177 
3178 static __always_inline int
trace_recursive_lock(struct ring_buffer_per_cpu * cpu_buffer)3179 trace_recursive_lock(struct ring_buffer_per_cpu *cpu_buffer)
3180 {
3181 	unsigned int val = cpu_buffer->current_context;
3182 	unsigned long pc = preempt_count();
3183 	int bit;
3184 
3185 	if (!(pc & (NMI_MASK | HARDIRQ_MASK | SOFTIRQ_OFFSET)))
3186 		bit = RB_CTX_NORMAL;
3187 	else
3188 		bit = pc & NMI_MASK ? RB_CTX_NMI :
3189 			pc & HARDIRQ_MASK ? RB_CTX_IRQ : RB_CTX_SOFTIRQ;
3190 
3191 	if (unlikely(val & (1 << (bit + cpu_buffer->nest)))) {
3192 		/*
3193 		 * It is possible that this was called by transitioning
3194 		 * between interrupt context, and preempt_count() has not
3195 		 * been updated yet. In this case, use the TRANSITION bit.
3196 		 */
3197 		bit = RB_CTX_TRANSITION;
3198 		if (val & (1 << (bit + cpu_buffer->nest)))
3199 			return 1;
3200 	}
3201 
3202 	val |= (1 << (bit + cpu_buffer->nest));
3203 	cpu_buffer->current_context = val;
3204 
3205 	return 0;
3206 }
3207 
3208 static __always_inline void
trace_recursive_unlock(struct ring_buffer_per_cpu * cpu_buffer)3209 trace_recursive_unlock(struct ring_buffer_per_cpu *cpu_buffer)
3210 {
3211 	cpu_buffer->current_context &=
3212 		cpu_buffer->current_context - (1 << cpu_buffer->nest);
3213 }
3214 
3215 /* The recursive locking above uses 5 bits */
3216 #define NESTED_BITS 5
3217 
3218 /**
3219  * ring_buffer_nest_start - Allow to trace while nested
3220  * @buffer: The ring buffer to modify
3221  *
3222  * The ring buffer has a safety mechanism to prevent recursion.
3223  * But there may be a case where a trace needs to be done while
3224  * tracing something else. In this case, calling this function
3225  * will allow this function to nest within a currently active
3226  * ring_buffer_lock_reserve().
3227  *
3228  * Call this function before calling another ring_buffer_lock_reserve() and
3229  * call ring_buffer_nest_end() after the nested ring_buffer_unlock_commit().
3230  */
ring_buffer_nest_start(struct trace_buffer * buffer)3231 void ring_buffer_nest_start(struct trace_buffer *buffer)
3232 {
3233 	struct ring_buffer_per_cpu *cpu_buffer;
3234 	int cpu;
3235 
3236 	/* Enabled by ring_buffer_nest_end() */
3237 	preempt_disable_notrace();
3238 	cpu = raw_smp_processor_id();
3239 	cpu_buffer = buffer->buffers[cpu];
3240 	/* This is the shift value for the above recursive locking */
3241 	cpu_buffer->nest += NESTED_BITS;
3242 }
3243 
3244 /**
3245  * ring_buffer_nest_end - Allow to trace while nested
3246  * @buffer: The ring buffer to modify
3247  *
3248  * Must be called after ring_buffer_nest_start() and after the
3249  * ring_buffer_unlock_commit().
3250  */
ring_buffer_nest_end(struct trace_buffer * buffer)3251 void ring_buffer_nest_end(struct trace_buffer *buffer)
3252 {
3253 	struct ring_buffer_per_cpu *cpu_buffer;
3254 	int cpu;
3255 
3256 	/* disabled by ring_buffer_nest_start() */
3257 	cpu = raw_smp_processor_id();
3258 	cpu_buffer = buffer->buffers[cpu];
3259 	/* This is the shift value for the above recursive locking */
3260 	cpu_buffer->nest -= NESTED_BITS;
3261 	preempt_enable_notrace();
3262 }
3263 
3264 /**
3265  * ring_buffer_unlock_commit - commit a reserved
3266  * @buffer: The buffer to commit to
3267  * @event: The event pointer to commit.
3268  *
3269  * This commits the data to the ring buffer, and releases any locks held.
3270  *
3271  * Must be paired with ring_buffer_lock_reserve.
3272  */
ring_buffer_unlock_commit(struct trace_buffer * buffer,struct ring_buffer_event * event)3273 int ring_buffer_unlock_commit(struct trace_buffer *buffer,
3274 			      struct ring_buffer_event *event)
3275 {
3276 	struct ring_buffer_per_cpu *cpu_buffer;
3277 	int cpu = raw_smp_processor_id();
3278 
3279 	cpu_buffer = buffer->buffers[cpu];
3280 
3281 	rb_commit(cpu_buffer, event);
3282 
3283 	rb_wakeups(buffer, cpu_buffer);
3284 
3285 	trace_recursive_unlock(cpu_buffer);
3286 
3287 	preempt_enable_notrace();
3288 
3289 	return 0;
3290 }
3291 EXPORT_SYMBOL_GPL(ring_buffer_unlock_commit);
3292 
3293 static struct ring_buffer_event *
__rb_reserve_next(struct ring_buffer_per_cpu * cpu_buffer,struct rb_event_info * info)3294 __rb_reserve_next(struct ring_buffer_per_cpu *cpu_buffer,
3295 		  struct rb_event_info *info)
3296 {
3297 	struct ring_buffer_event *event;
3298 	struct buffer_page *tail_page;
3299 	unsigned long tail, write, w;
3300 	bool a_ok;
3301 	bool b_ok;
3302 
3303 	/* Don't let the compiler play games with cpu_buffer->tail_page */
3304 	tail_page = info->tail_page = READ_ONCE(cpu_buffer->tail_page);
3305 
3306  /*A*/	w = local_read(&tail_page->write) & RB_WRITE_MASK;
3307 	barrier();
3308 	b_ok = rb_time_read(&cpu_buffer->before_stamp, &info->before);
3309 	a_ok = rb_time_read(&cpu_buffer->write_stamp, &info->after);
3310 	barrier();
3311 	info->ts = rb_time_stamp(cpu_buffer->buffer);
3312 
3313 	if ((info->add_timestamp & RB_ADD_STAMP_ABSOLUTE)) {
3314 		info->delta = info->ts;
3315 	} else {
3316 		/*
3317 		 * If interrupting an event time update, we may need an
3318 		 * absolute timestamp.
3319 		 * Don't bother if this is the start of a new page (w == 0).
3320 		 */
3321 		if (!w) {
3322 			/* Use the sub-buffer timestamp */
3323 			info->delta = 0;
3324 		} else if (unlikely(!a_ok || !b_ok || info->before != info->after)) {
3325 			info->add_timestamp |= RB_ADD_STAMP_FORCE | RB_ADD_STAMP_EXTEND;
3326 			info->length += RB_LEN_TIME_EXTEND;
3327 		} else {
3328 			info->delta = info->ts - info->after;
3329 			if (unlikely(test_time_stamp(info->delta))) {
3330 				info->add_timestamp |= RB_ADD_STAMP_EXTEND;
3331 				info->length += RB_LEN_TIME_EXTEND;
3332 			}
3333 		}
3334 	}
3335 
3336  /*B*/	rb_time_set(&cpu_buffer->before_stamp, info->ts);
3337 
3338  /*C*/	write = local_add_return(info->length, &tail_page->write);
3339 
3340 	/* set write to only the index of the write */
3341 	write &= RB_WRITE_MASK;
3342 
3343 	tail = write - info->length;
3344 
3345 	/* See if we shot pass the end of this buffer page */
3346 	if (unlikely(write > BUF_PAGE_SIZE)) {
3347 		/* before and after may now different, fix it up*/
3348 		b_ok = rb_time_read(&cpu_buffer->before_stamp, &info->before);
3349 		a_ok = rb_time_read(&cpu_buffer->write_stamp, &info->after);
3350 		if (a_ok && b_ok && info->before != info->after)
3351 			(void)rb_time_cmpxchg(&cpu_buffer->before_stamp,
3352 					      info->before, info->after);
3353 		return rb_move_tail(cpu_buffer, tail, info);
3354 	}
3355 
3356 	if (likely(tail == w)) {
3357 		u64 save_before;
3358 		bool s_ok;
3359 
3360 		/* Nothing interrupted us between A and C */
3361  /*D*/		rb_time_set(&cpu_buffer->write_stamp, info->ts);
3362 		barrier();
3363  /*E*/		s_ok = rb_time_read(&cpu_buffer->before_stamp, &save_before);
3364 		RB_WARN_ON(cpu_buffer, !s_ok);
3365 		if (likely(!(info->add_timestamp &
3366 			     (RB_ADD_STAMP_FORCE | RB_ADD_STAMP_ABSOLUTE))))
3367 			/* This did not interrupt any time update */
3368 			info->delta = info->ts - info->after;
3369 		else
3370 			/* Just use full timestamp for inerrupting event */
3371 			info->delta = info->ts;
3372 		barrier();
3373 		if (unlikely(info->ts != save_before)) {
3374 			/* SLOW PATH - Interrupted between C and E */
3375 
3376 			a_ok = rb_time_read(&cpu_buffer->write_stamp, &info->after);
3377 			RB_WARN_ON(cpu_buffer, !a_ok);
3378 
3379 			/* Write stamp must only go forward */
3380 			if (save_before > info->after) {
3381 				/*
3382 				 * We do not care about the result, only that
3383 				 * it gets updated atomically.
3384 				 */
3385 				(void)rb_time_cmpxchg(&cpu_buffer->write_stamp,
3386 						      info->after, save_before);
3387 			}
3388 		}
3389 	} else {
3390 		u64 ts;
3391 		/* SLOW PATH - Interrupted between A and C */
3392 		a_ok = rb_time_read(&cpu_buffer->write_stamp, &info->after);
3393 		/* Was interrupted before here, write_stamp must be valid */
3394 		RB_WARN_ON(cpu_buffer, !a_ok);
3395 		ts = rb_time_stamp(cpu_buffer->buffer);
3396 		barrier();
3397  /*E*/		if (write == (local_read(&tail_page->write) & RB_WRITE_MASK) &&
3398 		    info->after < ts &&
3399 		    rb_time_cmpxchg(&cpu_buffer->write_stamp,
3400 				    info->after, ts)) {
3401 			/* Nothing came after this event between C and E */
3402 			info->delta = ts - info->after;
3403 			info->ts = ts;
3404 		} else {
3405 			/*
3406 			 * Interrupted beween C and E:
3407 			 * Lost the previous events time stamp. Just set the
3408 			 * delta to zero, and this will be the same time as
3409 			 * the event this event interrupted. And the events that
3410 			 * came after this will still be correct (as they would
3411 			 * have built their delta on the previous event.
3412 			 */
3413 			info->delta = 0;
3414 		}
3415 		info->add_timestamp &= ~RB_ADD_STAMP_FORCE;
3416 	}
3417 
3418 	/*
3419 	 * If this is the first commit on the page, then it has the same
3420 	 * timestamp as the page itself.
3421 	 */
3422 	if (unlikely(!tail && !(info->add_timestamp &
3423 				(RB_ADD_STAMP_FORCE | RB_ADD_STAMP_ABSOLUTE))))
3424 		info->delta = 0;
3425 
3426 	/* We reserved something on the buffer */
3427 
3428 	event = __rb_page_index(tail_page, tail);
3429 	rb_update_event(cpu_buffer, event, info);
3430 
3431 	local_inc(&tail_page->entries);
3432 
3433 	/*
3434 	 * If this is the first commit on the page, then update
3435 	 * its timestamp.
3436 	 */
3437 	if (unlikely(!tail))
3438 		tail_page->page->time_stamp = info->ts;
3439 
3440 	/* account for these added bytes */
3441 	local_add(info->length, &cpu_buffer->entries_bytes);
3442 
3443 	return event;
3444 }
3445 
3446 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)3447 rb_reserve_next_event(struct trace_buffer *buffer,
3448 		      struct ring_buffer_per_cpu *cpu_buffer,
3449 		      unsigned long length)
3450 {
3451 	struct ring_buffer_event *event;
3452 	struct rb_event_info info;
3453 	int nr_loops = 0;
3454 	int add_ts_default;
3455 
3456 	/* ring buffer does cmpxchg, make sure it is safe in NMI context */
3457 	if (!IS_ENABLED(CONFIG_ARCH_HAVE_NMI_SAFE_CMPXCHG) &&
3458 	    (unlikely(in_nmi()))) {
3459 		return NULL;
3460 	}
3461 
3462 	rb_start_commit(cpu_buffer);
3463 	/* The commit page can not change after this */
3464 
3465 #ifdef CONFIG_RING_BUFFER_ALLOW_SWAP
3466 	/*
3467 	 * Due to the ability to swap a cpu buffer from a buffer
3468 	 * it is possible it was swapped before we committed.
3469 	 * (committing stops a swap). We check for it here and
3470 	 * if it happened, we have to fail the write.
3471 	 */
3472 	barrier();
3473 	if (unlikely(READ_ONCE(cpu_buffer->buffer) != buffer)) {
3474 		local_dec(&cpu_buffer->committing);
3475 		local_dec(&cpu_buffer->commits);
3476 		return NULL;
3477 	}
3478 #endif
3479 
3480 	info.length = rb_calculate_event_length(length);
3481 
3482 	if (ring_buffer_time_stamp_abs(cpu_buffer->buffer)) {
3483 		add_ts_default = RB_ADD_STAMP_ABSOLUTE;
3484 		info.length += RB_LEN_TIME_EXTEND;
3485 		if (info.length > BUF_MAX_DATA_SIZE)
3486 			goto out_fail;
3487 	} else {
3488 		add_ts_default = RB_ADD_STAMP_NONE;
3489 	}
3490 
3491  again:
3492 	info.add_timestamp = add_ts_default;
3493 	info.delta = 0;
3494 
3495 	/*
3496 	 * We allow for interrupts to reenter here and do a trace.
3497 	 * If one does, it will cause this original code to loop
3498 	 * back here. Even with heavy interrupts happening, this
3499 	 * should only happen a few times in a row. If this happens
3500 	 * 1000 times in a row, there must be either an interrupt
3501 	 * storm or we have something buggy.
3502 	 * Bail!
3503 	 */
3504 	if (RB_WARN_ON(cpu_buffer, ++nr_loops > 1000))
3505 		goto out_fail;
3506 
3507 	event = __rb_reserve_next(cpu_buffer, &info);
3508 
3509 	if (unlikely(PTR_ERR(event) == -EAGAIN)) {
3510 		if (info.add_timestamp & (RB_ADD_STAMP_FORCE | RB_ADD_STAMP_EXTEND))
3511 			info.length -= RB_LEN_TIME_EXTEND;
3512 		goto again;
3513 	}
3514 
3515 	if (likely(event))
3516 		return event;
3517  out_fail:
3518 	rb_end_commit(cpu_buffer);
3519 	return NULL;
3520 }
3521 
3522 /**
3523  * ring_buffer_lock_reserve - reserve a part of the buffer
3524  * @buffer: the ring buffer to reserve from
3525  * @length: the length of the data to reserve (excluding event header)
3526  *
3527  * Returns a reserved event on the ring buffer to copy directly to.
3528  * The user of this interface will need to get the body to write into
3529  * and can use the ring_buffer_event_data() interface.
3530  *
3531  * The length is the length of the data needed, not the event length
3532  * which also includes the event header.
3533  *
3534  * Must be paired with ring_buffer_unlock_commit, unless NULL is returned.
3535  * If NULL is returned, then nothing has been allocated or locked.
3536  */
3537 struct ring_buffer_event *
ring_buffer_lock_reserve(struct trace_buffer * buffer,unsigned long length)3538 ring_buffer_lock_reserve(struct trace_buffer *buffer, unsigned long length)
3539 {
3540 	struct ring_buffer_per_cpu *cpu_buffer;
3541 	struct ring_buffer_event *event;
3542 	int cpu;
3543 
3544 	/* If we are tracing schedule, we don't want to recurse */
3545 	preempt_disable_notrace();
3546 
3547 	if (unlikely(atomic_read(&buffer->record_disabled)))
3548 		goto out;
3549 
3550 	cpu = raw_smp_processor_id();
3551 
3552 	if (unlikely(!cpumask_test_cpu(cpu, buffer->cpumask)))
3553 		goto out;
3554 
3555 	cpu_buffer = buffer->buffers[cpu];
3556 
3557 	if (unlikely(atomic_read(&cpu_buffer->record_disabled)))
3558 		goto out;
3559 
3560 	if (unlikely(length > BUF_MAX_DATA_SIZE))
3561 		goto out;
3562 
3563 	if (unlikely(trace_recursive_lock(cpu_buffer)))
3564 		goto out;
3565 
3566 	event = rb_reserve_next_event(buffer, cpu_buffer, length);
3567 	if (!event)
3568 		goto out_unlock;
3569 
3570 	return event;
3571 
3572  out_unlock:
3573 	trace_recursive_unlock(cpu_buffer);
3574  out:
3575 	preempt_enable_notrace();
3576 	return NULL;
3577 }
3578 EXPORT_SYMBOL_GPL(ring_buffer_lock_reserve);
3579 
3580 /*
3581  * Decrement the entries to the page that an event is on.
3582  * The event does not even need to exist, only the pointer
3583  * to the page it is on. This may only be called before the commit
3584  * takes place.
3585  */
3586 static inline void
rb_decrement_entry(struct ring_buffer_per_cpu * cpu_buffer,struct ring_buffer_event * event)3587 rb_decrement_entry(struct ring_buffer_per_cpu *cpu_buffer,
3588 		   struct ring_buffer_event *event)
3589 {
3590 	unsigned long addr = (unsigned long)event;
3591 	struct buffer_page *bpage = cpu_buffer->commit_page;
3592 	struct buffer_page *start;
3593 
3594 	addr &= PAGE_MASK;
3595 
3596 	/* Do the likely case first */
3597 	if (likely(bpage->page == (void *)addr)) {
3598 		local_dec(&bpage->entries);
3599 		return;
3600 	}
3601 
3602 	/*
3603 	 * Because the commit page may be on the reader page we
3604 	 * start with the next page and check the end loop there.
3605 	 */
3606 	rb_inc_page(cpu_buffer, &bpage);
3607 	start = bpage;
3608 	do {
3609 		if (bpage->page == (void *)addr) {
3610 			local_dec(&bpage->entries);
3611 			return;
3612 		}
3613 		rb_inc_page(cpu_buffer, &bpage);
3614 	} while (bpage != start);
3615 
3616 	/* commit not part of this buffer?? */
3617 	RB_WARN_ON(cpu_buffer, 1);
3618 }
3619 
3620 /**
3621  * ring_buffer_commit_discard - discard an event that has not been committed
3622  * @buffer: the ring buffer
3623  * @event: non committed event to discard
3624  *
3625  * Sometimes an event that is in the ring buffer needs to be ignored.
3626  * This function lets the user discard an event in the ring buffer
3627  * and then that event will not be read later.
3628  *
3629  * This function only works if it is called before the item has been
3630  * committed. It will try to free the event from the ring buffer
3631  * if another event has not been added behind it.
3632  *
3633  * If another event has been added behind it, it will set the event
3634  * up as discarded, and perform the commit.
3635  *
3636  * If this function is called, do not call ring_buffer_unlock_commit on
3637  * the event.
3638  */
ring_buffer_discard_commit(struct trace_buffer * buffer,struct ring_buffer_event * event)3639 void ring_buffer_discard_commit(struct trace_buffer *buffer,
3640 				struct ring_buffer_event *event)
3641 {
3642 	struct ring_buffer_per_cpu *cpu_buffer;
3643 	int cpu;
3644 
3645 	/* The event is discarded regardless */
3646 	rb_event_discard(event);
3647 
3648 	cpu = smp_processor_id();
3649 	cpu_buffer = buffer->buffers[cpu];
3650 
3651 	/*
3652 	 * This must only be called if the event has not been
3653 	 * committed yet. Thus we can assume that preemption
3654 	 * is still disabled.
3655 	 */
3656 	RB_WARN_ON(buffer, !local_read(&cpu_buffer->committing));
3657 
3658 	rb_decrement_entry(cpu_buffer, event);
3659 	if (rb_try_to_discard(cpu_buffer, event))
3660 		goto out;
3661 
3662  out:
3663 	rb_end_commit(cpu_buffer);
3664 
3665 	trace_recursive_unlock(cpu_buffer);
3666 
3667 	preempt_enable_notrace();
3668 
3669 }
3670 EXPORT_SYMBOL_GPL(ring_buffer_discard_commit);
3671 
3672 /**
3673  * ring_buffer_write - write data to the buffer without reserving
3674  * @buffer: The ring buffer to write to.
3675  * @length: The length of the data being written (excluding the event header)
3676  * @data: The data to write to the buffer.
3677  *
3678  * This is like ring_buffer_lock_reserve and ring_buffer_unlock_commit as
3679  * one function. If you already have the data to write to the buffer, it
3680  * may be easier to simply call this function.
3681  *
3682  * Note, like ring_buffer_lock_reserve, the length is the length of the data
3683  * and not the length of the event which would hold the header.
3684  */
ring_buffer_write(struct trace_buffer * buffer,unsigned long length,void * data)3685 int ring_buffer_write(struct trace_buffer *buffer,
3686 		      unsigned long length,
3687 		      void *data)
3688 {
3689 	struct ring_buffer_per_cpu *cpu_buffer;
3690 	struct ring_buffer_event *event;
3691 	void *body;
3692 	int ret = -EBUSY;
3693 	int cpu;
3694 
3695 	preempt_disable_notrace();
3696 
3697 	if (atomic_read(&buffer->record_disabled))
3698 		goto out;
3699 
3700 	cpu = raw_smp_processor_id();
3701 
3702 	if (!cpumask_test_cpu(cpu, buffer->cpumask))
3703 		goto out;
3704 
3705 	cpu_buffer = buffer->buffers[cpu];
3706 
3707 	if (atomic_read(&cpu_buffer->record_disabled))
3708 		goto out;
3709 
3710 	if (length > BUF_MAX_DATA_SIZE)
3711 		goto out;
3712 
3713 	if (unlikely(trace_recursive_lock(cpu_buffer)))
3714 		goto out;
3715 
3716 	event = rb_reserve_next_event(buffer, cpu_buffer, length);
3717 	if (!event)
3718 		goto out_unlock;
3719 
3720 	body = rb_event_data(event);
3721 
3722 	memcpy(body, data, length);
3723 
3724 	rb_commit(cpu_buffer, event);
3725 
3726 	rb_wakeups(buffer, cpu_buffer);
3727 
3728 	ret = 0;
3729 
3730  out_unlock:
3731 	trace_recursive_unlock(cpu_buffer);
3732 
3733  out:
3734 	preempt_enable_notrace();
3735 
3736 	return ret;
3737 }
3738 EXPORT_SYMBOL_GPL(ring_buffer_write);
3739 
rb_per_cpu_empty(struct ring_buffer_per_cpu * cpu_buffer)3740 static bool rb_per_cpu_empty(struct ring_buffer_per_cpu *cpu_buffer)
3741 {
3742 	struct buffer_page *reader = cpu_buffer->reader_page;
3743 	struct buffer_page *head = rb_set_head_page(cpu_buffer);
3744 	struct buffer_page *commit = cpu_buffer->commit_page;
3745 
3746 	/* In case of error, head will be NULL */
3747 	if (unlikely(!head))
3748 		return true;
3749 
3750 	/* Reader should exhaust content in reader page */
3751 	if (reader->read != rb_page_commit(reader))
3752 		return false;
3753 
3754 	/*
3755 	 * If writers are committing on the reader page, knowing all
3756 	 * committed content has been read, the ring buffer is empty.
3757 	 */
3758 	if (commit == reader)
3759 		return true;
3760 
3761 	/*
3762 	 * If writers are committing on a page other than reader page
3763 	 * and head page, there should always be content to read.
3764 	 */
3765 	if (commit != head)
3766 		return false;
3767 
3768 	/*
3769 	 * Writers are committing on the head page, we just need
3770 	 * to care about there're committed data, and the reader will
3771 	 * swap reader page with head page when it is to read data.
3772 	 */
3773 	return rb_page_commit(commit) == 0;
3774 }
3775 
3776 /**
3777  * ring_buffer_record_disable - stop all writes into the buffer
3778  * @buffer: The ring buffer to stop writes to.
3779  *
3780  * This prevents all writes to the buffer. Any attempt to write
3781  * to the buffer after this will fail and return NULL.
3782  *
3783  * The caller should call synchronize_rcu() after this.
3784  */
ring_buffer_record_disable(struct trace_buffer * buffer)3785 void ring_buffer_record_disable(struct trace_buffer *buffer)
3786 {
3787 	atomic_inc(&buffer->record_disabled);
3788 }
3789 EXPORT_SYMBOL_GPL(ring_buffer_record_disable);
3790 
3791 /**
3792  * ring_buffer_record_enable - enable writes to the buffer
3793  * @buffer: The ring buffer to enable writes
3794  *
3795  * Note, multiple disables will need the same number of enables
3796  * to truly enable the writing (much like preempt_disable).
3797  */
ring_buffer_record_enable(struct trace_buffer * buffer)3798 void ring_buffer_record_enable(struct trace_buffer *buffer)
3799 {
3800 	atomic_dec(&buffer->record_disabled);
3801 }
3802 EXPORT_SYMBOL_GPL(ring_buffer_record_enable);
3803 
3804 /**
3805  * ring_buffer_record_off - stop all writes into the buffer
3806  * @buffer: The ring buffer to stop writes to.
3807  *
3808  * This prevents all writes to the buffer. Any attempt to write
3809  * to the buffer after this will fail and return NULL.
3810  *
3811  * This is different than ring_buffer_record_disable() as
3812  * it works like an on/off switch, where as the disable() version
3813  * must be paired with a enable().
3814  */
ring_buffer_record_off(struct trace_buffer * buffer)3815 void ring_buffer_record_off(struct trace_buffer *buffer)
3816 {
3817 	unsigned int rd;
3818 	unsigned int new_rd;
3819 
3820 	do {
3821 		rd = atomic_read(&buffer->record_disabled);
3822 		new_rd = rd | RB_BUFFER_OFF;
3823 	} while (atomic_cmpxchg(&buffer->record_disabled, rd, new_rd) != rd);
3824 }
3825 EXPORT_SYMBOL_GPL(ring_buffer_record_off);
3826 
3827 /**
3828  * ring_buffer_record_on - restart writes into the buffer
3829  * @buffer: The ring buffer to start writes to.
3830  *
3831  * This enables all writes to the buffer that was disabled by
3832  * ring_buffer_record_off().
3833  *
3834  * This is different than ring_buffer_record_enable() as
3835  * it works like an on/off switch, where as the enable() version
3836  * must be paired with a disable().
3837  */
ring_buffer_record_on(struct trace_buffer * buffer)3838 void ring_buffer_record_on(struct trace_buffer *buffer)
3839 {
3840 	unsigned int rd;
3841 	unsigned int new_rd;
3842 
3843 	do {
3844 		rd = atomic_read(&buffer->record_disabled);
3845 		new_rd = rd & ~RB_BUFFER_OFF;
3846 	} while (atomic_cmpxchg(&buffer->record_disabled, rd, new_rd) != rd);
3847 }
3848 EXPORT_SYMBOL_GPL(ring_buffer_record_on);
3849 
3850 /**
3851  * ring_buffer_record_is_on - return true if the ring buffer can write
3852  * @buffer: The ring buffer to see if write is enabled
3853  *
3854  * Returns true if the ring buffer is in a state that it accepts writes.
3855  */
ring_buffer_record_is_on(struct trace_buffer * buffer)3856 bool ring_buffer_record_is_on(struct trace_buffer *buffer)
3857 {
3858 	return !atomic_read(&buffer->record_disabled);
3859 }
3860 
3861 /**
3862  * ring_buffer_record_is_set_on - return true if the ring buffer is set writable
3863  * @buffer: The ring buffer to see if write is set enabled
3864  *
3865  * Returns true if the ring buffer is set writable by ring_buffer_record_on().
3866  * Note that this does NOT mean it is in a writable state.
3867  *
3868  * It may return true when the ring buffer has been disabled by
3869  * ring_buffer_record_disable(), as that is a temporary disabling of
3870  * the ring buffer.
3871  */
ring_buffer_record_is_set_on(struct trace_buffer * buffer)3872 bool ring_buffer_record_is_set_on(struct trace_buffer *buffer)
3873 {
3874 	return !(atomic_read(&buffer->record_disabled) & RB_BUFFER_OFF);
3875 }
3876 
3877 /**
3878  * ring_buffer_record_disable_cpu - stop all writes into the cpu_buffer
3879  * @buffer: The ring buffer to stop writes to.
3880  * @cpu: The CPU buffer to stop
3881  *
3882  * This prevents all writes to the buffer. Any attempt to write
3883  * to the buffer after this will fail and return NULL.
3884  *
3885  * The caller should call synchronize_rcu() after this.
3886  */
ring_buffer_record_disable_cpu(struct trace_buffer * buffer,int cpu)3887 void ring_buffer_record_disable_cpu(struct trace_buffer *buffer, int cpu)
3888 {
3889 	struct ring_buffer_per_cpu *cpu_buffer;
3890 
3891 	if (!cpumask_test_cpu(cpu, buffer->cpumask))
3892 		return;
3893 
3894 	cpu_buffer = buffer->buffers[cpu];
3895 	atomic_inc(&cpu_buffer->record_disabled);
3896 }
3897 EXPORT_SYMBOL_GPL(ring_buffer_record_disable_cpu);
3898 
3899 /**
3900  * ring_buffer_record_enable_cpu - enable writes to the buffer
3901  * @buffer: The ring buffer to enable writes
3902  * @cpu: The CPU to enable.
3903  *
3904  * Note, multiple disables will need the same number of enables
3905  * to truly enable the writing (much like preempt_disable).
3906  */
ring_buffer_record_enable_cpu(struct trace_buffer * buffer,int cpu)3907 void ring_buffer_record_enable_cpu(struct trace_buffer *buffer, int cpu)
3908 {
3909 	struct ring_buffer_per_cpu *cpu_buffer;
3910 
3911 	if (!cpumask_test_cpu(cpu, buffer->cpumask))
3912 		return;
3913 
3914 	cpu_buffer = buffer->buffers[cpu];
3915 	atomic_dec(&cpu_buffer->record_disabled);
3916 }
3917 EXPORT_SYMBOL_GPL(ring_buffer_record_enable_cpu);
3918 
3919 /*
3920  * The total entries in the ring buffer is the running counter
3921  * of entries entered into the ring buffer, minus the sum of
3922  * the entries read from the ring buffer and the number of
3923  * entries that were overwritten.
3924  */
3925 static inline unsigned long
rb_num_of_entries(struct ring_buffer_per_cpu * cpu_buffer)3926 rb_num_of_entries(struct ring_buffer_per_cpu *cpu_buffer)
3927 {
3928 	return local_read(&cpu_buffer->entries) -
3929 		(local_read(&cpu_buffer->overrun) + cpu_buffer->read);
3930 }
3931 
3932 /**
3933  * ring_buffer_oldest_event_ts - get the oldest event timestamp from the buffer
3934  * @buffer: The ring buffer
3935  * @cpu: The per CPU buffer to read from.
3936  */
ring_buffer_oldest_event_ts(struct trace_buffer * buffer,int cpu)3937 u64 ring_buffer_oldest_event_ts(struct trace_buffer *buffer, int cpu)
3938 {
3939 	unsigned long flags;
3940 	struct ring_buffer_per_cpu *cpu_buffer;
3941 	struct buffer_page *bpage;
3942 	u64 ret = 0;
3943 
3944 	if (!cpumask_test_cpu(cpu, buffer->cpumask))
3945 		return 0;
3946 
3947 	cpu_buffer = buffer->buffers[cpu];
3948 	raw_spin_lock_irqsave(&cpu_buffer->reader_lock, flags);
3949 	/*
3950 	 * if the tail is on reader_page, oldest time stamp is on the reader
3951 	 * page
3952 	 */
3953 	if (cpu_buffer->tail_page == cpu_buffer->reader_page)
3954 		bpage = cpu_buffer->reader_page;
3955 	else
3956 		bpage = rb_set_head_page(cpu_buffer);
3957 	if (bpage)
3958 		ret = bpage->page->time_stamp;
3959 	raw_spin_unlock_irqrestore(&cpu_buffer->reader_lock, flags);
3960 
3961 	return ret;
3962 }
3963 EXPORT_SYMBOL_GPL(ring_buffer_oldest_event_ts);
3964 
3965 /**
3966  * ring_buffer_bytes_cpu - get the number of bytes unconsumed in a cpu buffer
3967  * @buffer: The ring buffer
3968  * @cpu: The per CPU buffer to read from.
3969  */
ring_buffer_bytes_cpu(struct trace_buffer * buffer,int cpu)3970 unsigned long ring_buffer_bytes_cpu(struct trace_buffer *buffer, int cpu)
3971 {
3972 	struct ring_buffer_per_cpu *cpu_buffer;
3973 	unsigned long ret;
3974 
3975 	if (!cpumask_test_cpu(cpu, buffer->cpumask))
3976 		return 0;
3977 
3978 	cpu_buffer = buffer->buffers[cpu];
3979 	ret = local_read(&cpu_buffer->entries_bytes) - cpu_buffer->read_bytes;
3980 
3981 	return ret;
3982 }
3983 EXPORT_SYMBOL_GPL(ring_buffer_bytes_cpu);
3984 
3985 /**
3986  * ring_buffer_entries_cpu - get the number of entries in a cpu buffer
3987  * @buffer: The ring buffer
3988  * @cpu: The per CPU buffer to get the entries from.
3989  */
ring_buffer_entries_cpu(struct trace_buffer * buffer,int cpu)3990 unsigned long ring_buffer_entries_cpu(struct trace_buffer *buffer, int cpu)
3991 {
3992 	struct ring_buffer_per_cpu *cpu_buffer;
3993 
3994 	if (!cpumask_test_cpu(cpu, buffer->cpumask))
3995 		return 0;
3996 
3997 	cpu_buffer = buffer->buffers[cpu];
3998 
3999 	return rb_num_of_entries(cpu_buffer);
4000 }
4001 EXPORT_SYMBOL_GPL(ring_buffer_entries_cpu);
4002 
4003 /**
4004  * ring_buffer_overrun_cpu - get the number of overruns caused by the ring
4005  * buffer wrapping around (only if RB_FL_OVERWRITE is on).
4006  * @buffer: The ring buffer
4007  * @cpu: The per CPU buffer to get the number of overruns from
4008  */
ring_buffer_overrun_cpu(struct trace_buffer * buffer,int cpu)4009 unsigned long ring_buffer_overrun_cpu(struct trace_buffer *buffer, int cpu)
4010 {
4011 	struct ring_buffer_per_cpu *cpu_buffer;
4012 	unsigned long ret;
4013 
4014 	if (!cpumask_test_cpu(cpu, buffer->cpumask))
4015 		return 0;
4016 
4017 	cpu_buffer = buffer->buffers[cpu];
4018 	ret = local_read(&cpu_buffer->overrun);
4019 
4020 	return ret;
4021 }
4022 EXPORT_SYMBOL_GPL(ring_buffer_overrun_cpu);
4023 
4024 /**
4025  * ring_buffer_commit_overrun_cpu - get the number of overruns caused by
4026  * commits failing due to the buffer wrapping around while there are uncommitted
4027  * events, such as during an interrupt storm.
4028  * @buffer: The ring buffer
4029  * @cpu: The per CPU buffer to get the number of overruns from
4030  */
4031 unsigned long
ring_buffer_commit_overrun_cpu(struct trace_buffer * buffer,int cpu)4032 ring_buffer_commit_overrun_cpu(struct trace_buffer *buffer, int cpu)
4033 {
4034 	struct ring_buffer_per_cpu *cpu_buffer;
4035 	unsigned long ret;
4036 
4037 	if (!cpumask_test_cpu(cpu, buffer->cpumask))
4038 		return 0;
4039 
4040 	cpu_buffer = buffer->buffers[cpu];
4041 	ret = local_read(&cpu_buffer->commit_overrun);
4042 
4043 	return ret;
4044 }
4045 EXPORT_SYMBOL_GPL(ring_buffer_commit_overrun_cpu);
4046 
4047 /**
4048  * ring_buffer_dropped_events_cpu - get the number of dropped events caused by
4049  * the ring buffer filling up (only if RB_FL_OVERWRITE is off).
4050  * @buffer: The ring buffer
4051  * @cpu: The per CPU buffer to get the number of overruns from
4052  */
4053 unsigned long
ring_buffer_dropped_events_cpu(struct trace_buffer * buffer,int cpu)4054 ring_buffer_dropped_events_cpu(struct trace_buffer *buffer, int cpu)
4055 {
4056 	struct ring_buffer_per_cpu *cpu_buffer;
4057 	unsigned long ret;
4058 
4059 	if (!cpumask_test_cpu(cpu, buffer->cpumask))
4060 		return 0;
4061 
4062 	cpu_buffer = buffer->buffers[cpu];
4063 	ret = local_read(&cpu_buffer->dropped_events);
4064 
4065 	return ret;
4066 }
4067 EXPORT_SYMBOL_GPL(ring_buffer_dropped_events_cpu);
4068 
4069 /**
4070  * ring_buffer_read_events_cpu - get the number of events successfully read
4071  * @buffer: The ring buffer
4072  * @cpu: The per CPU buffer to get the number of events read
4073  */
4074 unsigned long
ring_buffer_read_events_cpu(struct trace_buffer * buffer,int cpu)4075 ring_buffer_read_events_cpu(struct trace_buffer *buffer, int cpu)
4076 {
4077 	struct ring_buffer_per_cpu *cpu_buffer;
4078 
4079 	if (!cpumask_test_cpu(cpu, buffer->cpumask))
4080 		return 0;
4081 
4082 	cpu_buffer = buffer->buffers[cpu];
4083 	return cpu_buffer->read;
4084 }
4085 EXPORT_SYMBOL_GPL(ring_buffer_read_events_cpu);
4086 
4087 /**
4088  * ring_buffer_entries - get the number of entries in a buffer
4089  * @buffer: The ring buffer
4090  *
4091  * Returns the total number of entries in the ring buffer
4092  * (all CPU entries)
4093  */
ring_buffer_entries(struct trace_buffer * buffer)4094 unsigned long ring_buffer_entries(struct trace_buffer *buffer)
4095 {
4096 	struct ring_buffer_per_cpu *cpu_buffer;
4097 	unsigned long entries = 0;
4098 	int cpu;
4099 
4100 	/* if you care about this being correct, lock the buffer */
4101 	for_each_buffer_cpu(buffer, cpu) {
4102 		cpu_buffer = buffer->buffers[cpu];
4103 		entries += rb_num_of_entries(cpu_buffer);
4104 	}
4105 
4106 	return entries;
4107 }
4108 EXPORT_SYMBOL_GPL(ring_buffer_entries);
4109 
4110 /**
4111  * ring_buffer_overruns - get the number of overruns in buffer
4112  * @buffer: The ring buffer
4113  *
4114  * Returns the total number of overruns in the ring buffer
4115  * (all CPU entries)
4116  */
ring_buffer_overruns(struct trace_buffer * buffer)4117 unsigned long ring_buffer_overruns(struct trace_buffer *buffer)
4118 {
4119 	struct ring_buffer_per_cpu *cpu_buffer;
4120 	unsigned long overruns = 0;
4121 	int cpu;
4122 
4123 	/* if you care about this being correct, lock the buffer */
4124 	for_each_buffer_cpu(buffer, cpu) {
4125 		cpu_buffer = buffer->buffers[cpu];
4126 		overruns += local_read(&cpu_buffer->overrun);
4127 	}
4128 
4129 	return overruns;
4130 }
4131 EXPORT_SYMBOL_GPL(ring_buffer_overruns);
4132 
rb_iter_reset(struct ring_buffer_iter * iter)4133 static void rb_iter_reset(struct ring_buffer_iter *iter)
4134 {
4135 	struct ring_buffer_per_cpu *cpu_buffer = iter->cpu_buffer;
4136 
4137 	/* Iterator usage is expected to have record disabled */
4138 	iter->head_page = cpu_buffer->reader_page;
4139 	iter->head = cpu_buffer->reader_page->read;
4140 	iter->next_event = iter->head;
4141 
4142 	iter->cache_reader_page = iter->head_page;
4143 	iter->cache_read = cpu_buffer->read;
4144 	iter->cache_pages_removed = cpu_buffer->pages_removed;
4145 
4146 	if (iter->head) {
4147 		iter->read_stamp = cpu_buffer->read_stamp;
4148 		iter->page_stamp = cpu_buffer->reader_page->page->time_stamp;
4149 	} else {
4150 		iter->read_stamp = iter->head_page->page->time_stamp;
4151 		iter->page_stamp = iter->read_stamp;
4152 	}
4153 }
4154 
4155 /**
4156  * ring_buffer_iter_reset - reset an iterator
4157  * @iter: The iterator to reset
4158  *
4159  * Resets the iterator, so that it will start from the beginning
4160  * again.
4161  */
ring_buffer_iter_reset(struct ring_buffer_iter * iter)4162 void ring_buffer_iter_reset(struct ring_buffer_iter *iter)
4163 {
4164 	struct ring_buffer_per_cpu *cpu_buffer;
4165 	unsigned long flags;
4166 
4167 	if (!iter)
4168 		return;
4169 
4170 	cpu_buffer = iter->cpu_buffer;
4171 
4172 	raw_spin_lock_irqsave(&cpu_buffer->reader_lock, flags);
4173 	rb_iter_reset(iter);
4174 	raw_spin_unlock_irqrestore(&cpu_buffer->reader_lock, flags);
4175 }
4176 EXPORT_SYMBOL_GPL(ring_buffer_iter_reset);
4177 
4178 /**
4179  * ring_buffer_iter_empty - check if an iterator has no more to read
4180  * @iter: The iterator to check
4181  */
ring_buffer_iter_empty(struct ring_buffer_iter * iter)4182 int ring_buffer_iter_empty(struct ring_buffer_iter *iter)
4183 {
4184 	struct ring_buffer_per_cpu *cpu_buffer;
4185 	struct buffer_page *reader;
4186 	struct buffer_page *head_page;
4187 	struct buffer_page *commit_page;
4188 	struct buffer_page *curr_commit_page;
4189 	unsigned commit;
4190 	u64 curr_commit_ts;
4191 	u64 commit_ts;
4192 
4193 	cpu_buffer = iter->cpu_buffer;
4194 	reader = cpu_buffer->reader_page;
4195 	head_page = cpu_buffer->head_page;
4196 	commit_page = cpu_buffer->commit_page;
4197 	commit_ts = commit_page->page->time_stamp;
4198 
4199 	/*
4200 	 * When the writer goes across pages, it issues a cmpxchg which
4201 	 * is a mb(), which will synchronize with the rmb here.
4202 	 * (see rb_tail_page_update())
4203 	 */
4204 	smp_rmb();
4205 	commit = rb_page_commit(commit_page);
4206 	/* We want to make sure that the commit page doesn't change */
4207 	smp_rmb();
4208 
4209 	/* Make sure commit page didn't change */
4210 	curr_commit_page = READ_ONCE(cpu_buffer->commit_page);
4211 	curr_commit_ts = READ_ONCE(curr_commit_page->page->time_stamp);
4212 
4213 	/* If the commit page changed, then there's more data */
4214 	if (curr_commit_page != commit_page ||
4215 	    curr_commit_ts != commit_ts)
4216 		return 0;
4217 
4218 	/* Still racy, as it may return a false positive, but that's OK */
4219 	return ((iter->head_page == commit_page && iter->head >= commit) ||
4220 		(iter->head_page == reader && commit_page == head_page &&
4221 		 head_page->read == commit &&
4222 		 iter->head == rb_page_commit(cpu_buffer->reader_page)));
4223 }
4224 EXPORT_SYMBOL_GPL(ring_buffer_iter_empty);
4225 
4226 static void
rb_update_read_stamp(struct ring_buffer_per_cpu * cpu_buffer,struct ring_buffer_event * event)4227 rb_update_read_stamp(struct ring_buffer_per_cpu *cpu_buffer,
4228 		     struct ring_buffer_event *event)
4229 {
4230 	u64 delta;
4231 
4232 	switch (event->type_len) {
4233 	case RINGBUF_TYPE_PADDING:
4234 		return;
4235 
4236 	case RINGBUF_TYPE_TIME_EXTEND:
4237 		delta = ring_buffer_event_time_stamp(event);
4238 		cpu_buffer->read_stamp += delta;
4239 		return;
4240 
4241 	case RINGBUF_TYPE_TIME_STAMP:
4242 		delta = ring_buffer_event_time_stamp(event);
4243 		cpu_buffer->read_stamp = delta;
4244 		return;
4245 
4246 	case RINGBUF_TYPE_DATA:
4247 		cpu_buffer->read_stamp += event->time_delta;
4248 		return;
4249 
4250 	default:
4251 		RB_WARN_ON(cpu_buffer, 1);
4252 	}
4253 	return;
4254 }
4255 
4256 static void
rb_update_iter_read_stamp(struct ring_buffer_iter * iter,struct ring_buffer_event * event)4257 rb_update_iter_read_stamp(struct ring_buffer_iter *iter,
4258 			  struct ring_buffer_event *event)
4259 {
4260 	u64 delta;
4261 
4262 	switch (event->type_len) {
4263 	case RINGBUF_TYPE_PADDING:
4264 		return;
4265 
4266 	case RINGBUF_TYPE_TIME_EXTEND:
4267 		delta = ring_buffer_event_time_stamp(event);
4268 		iter->read_stamp += delta;
4269 		return;
4270 
4271 	case RINGBUF_TYPE_TIME_STAMP:
4272 		delta = ring_buffer_event_time_stamp(event);
4273 		iter->read_stamp = delta;
4274 		return;
4275 
4276 	case RINGBUF_TYPE_DATA:
4277 		iter->read_stamp += event->time_delta;
4278 		return;
4279 
4280 	default:
4281 		RB_WARN_ON(iter->cpu_buffer, 1);
4282 	}
4283 	return;
4284 }
4285 
4286 static struct buffer_page *
rb_get_reader_page(struct ring_buffer_per_cpu * cpu_buffer)4287 rb_get_reader_page(struct ring_buffer_per_cpu *cpu_buffer)
4288 {
4289 	struct buffer_page *reader = NULL;
4290 	unsigned long overwrite;
4291 	unsigned long flags;
4292 	int nr_loops = 0;
4293 	int ret;
4294 
4295 	local_irq_save(flags);
4296 	arch_spin_lock(&cpu_buffer->lock);
4297 
4298  again:
4299 	/*
4300 	 * This should normally only loop twice. But because the
4301 	 * start of the reader inserts an empty page, it causes
4302 	 * a case where we will loop three times. There should be no
4303 	 * reason to loop four times (that I know of).
4304 	 */
4305 	if (RB_WARN_ON(cpu_buffer, ++nr_loops > 3)) {
4306 		reader = NULL;
4307 		goto out;
4308 	}
4309 
4310 	reader = cpu_buffer->reader_page;
4311 
4312 	/* If there's more to read, return this page */
4313 	if (cpu_buffer->reader_page->read < rb_page_size(reader))
4314 		goto out;
4315 
4316 	/* Never should we have an index greater than the size */
4317 	if (RB_WARN_ON(cpu_buffer,
4318 		       cpu_buffer->reader_page->read > rb_page_size(reader)))
4319 		goto out;
4320 
4321 	/* check if we caught up to the tail */
4322 	reader = NULL;
4323 	if (cpu_buffer->commit_page == cpu_buffer->reader_page)
4324 		goto out;
4325 
4326 	/* Don't bother swapping if the ring buffer is empty */
4327 	if (rb_num_of_entries(cpu_buffer) == 0)
4328 		goto out;
4329 
4330 	/*
4331 	 * Reset the reader page to size zero.
4332 	 */
4333 	local_set(&cpu_buffer->reader_page->write, 0);
4334 	local_set(&cpu_buffer->reader_page->entries, 0);
4335 	local_set(&cpu_buffer->reader_page->page->commit, 0);
4336 	cpu_buffer->reader_page->real_end = 0;
4337 
4338  spin:
4339 	/*
4340 	 * Splice the empty reader page into the list around the head.
4341 	 */
4342 	reader = rb_set_head_page(cpu_buffer);
4343 	if (!reader)
4344 		goto out;
4345 	cpu_buffer->reader_page->list.next = rb_list_head(reader->list.next);
4346 	cpu_buffer->reader_page->list.prev = reader->list.prev;
4347 
4348 	/*
4349 	 * cpu_buffer->pages just needs to point to the buffer, it
4350 	 *  has no specific buffer page to point to. Lets move it out
4351 	 *  of our way so we don't accidentally swap it.
4352 	 */
4353 	cpu_buffer->pages = reader->list.prev;
4354 
4355 	/* The reader page will be pointing to the new head */
4356 	rb_set_list_to_head(cpu_buffer, &cpu_buffer->reader_page->list);
4357 
4358 	/*
4359 	 * We want to make sure we read the overruns after we set up our
4360 	 * pointers to the next object. The writer side does a
4361 	 * cmpxchg to cross pages which acts as the mb on the writer
4362 	 * side. Note, the reader will constantly fail the swap
4363 	 * while the writer is updating the pointers, so this
4364 	 * guarantees that the overwrite recorded here is the one we
4365 	 * want to compare with the last_overrun.
4366 	 */
4367 	smp_mb();
4368 	overwrite = local_read(&(cpu_buffer->overrun));
4369 
4370 	/*
4371 	 * Here's the tricky part.
4372 	 *
4373 	 * We need to move the pointer past the header page.
4374 	 * But we can only do that if a writer is not currently
4375 	 * moving it. The page before the header page has the
4376 	 * flag bit '1' set if it is pointing to the page we want.
4377 	 * but if the writer is in the process of moving it
4378 	 * than it will be '2' or already moved '0'.
4379 	 */
4380 
4381 	ret = rb_head_page_replace(reader, cpu_buffer->reader_page);
4382 
4383 	/*
4384 	 * If we did not convert it, then we must try again.
4385 	 */
4386 	if (!ret)
4387 		goto spin;
4388 
4389 	/*
4390 	 * Yay! We succeeded in replacing the page.
4391 	 *
4392 	 * Now make the new head point back to the reader page.
4393 	 */
4394 	rb_list_head(reader->list.next)->prev = &cpu_buffer->reader_page->list;
4395 	rb_inc_page(cpu_buffer, &cpu_buffer->head_page);
4396 
4397 	local_inc(&cpu_buffer->pages_read);
4398 
4399 	/* Finally update the reader page to the new head */
4400 	cpu_buffer->reader_page = reader;
4401 	cpu_buffer->reader_page->read = 0;
4402 
4403 	if (overwrite != cpu_buffer->last_overrun) {
4404 		cpu_buffer->lost_events = overwrite - cpu_buffer->last_overrun;
4405 		cpu_buffer->last_overrun = overwrite;
4406 	}
4407 
4408 	goto again;
4409 
4410  out:
4411 	/* Update the read_stamp on the first event */
4412 	if (reader && reader->read == 0)
4413 		cpu_buffer->read_stamp = reader->page->time_stamp;
4414 
4415 	arch_spin_unlock(&cpu_buffer->lock);
4416 	local_irq_restore(flags);
4417 
4418 	/*
4419 	 * The writer has preempt disable, wait for it. But not forever
4420 	 * Although, 1 second is pretty much "forever"
4421 	 */
4422 #define USECS_WAIT	1000000
4423         for (nr_loops = 0; nr_loops < USECS_WAIT; nr_loops++) {
4424 		/* If the write is past the end of page, a writer is still updating it */
4425 		if (likely(!reader || rb_page_write(reader) <= BUF_PAGE_SIZE))
4426 			break;
4427 
4428 		udelay(1);
4429 
4430 		/* Get the latest version of the reader write value */
4431 		smp_rmb();
4432 	}
4433 
4434 	/* The writer is not moving forward? Something is wrong */
4435 	if (RB_WARN_ON(cpu_buffer, nr_loops == USECS_WAIT))
4436 		reader = NULL;
4437 
4438 	/*
4439 	 * Make sure we see any padding after the write update
4440 	 * (see rb_reset_tail()).
4441 	 *
4442 	 * In addition, a writer may be writing on the reader page
4443 	 * if the page has not been fully filled, so the read barrier
4444 	 * is also needed to make sure we see the content of what is
4445 	 * committed by the writer (see rb_set_commit_to_write()).
4446 	 */
4447 	smp_rmb();
4448 
4449 
4450 	return reader;
4451 }
4452 
rb_advance_reader(struct ring_buffer_per_cpu * cpu_buffer)4453 static void rb_advance_reader(struct ring_buffer_per_cpu *cpu_buffer)
4454 {
4455 	struct ring_buffer_event *event;
4456 	struct buffer_page *reader;
4457 	unsigned length;
4458 
4459 	reader = rb_get_reader_page(cpu_buffer);
4460 
4461 	/* This function should not be called when buffer is empty */
4462 	if (RB_WARN_ON(cpu_buffer, !reader))
4463 		return;
4464 
4465 	event = rb_reader_event(cpu_buffer);
4466 
4467 	if (event->type_len <= RINGBUF_TYPE_DATA_TYPE_LEN_MAX)
4468 		cpu_buffer->read++;
4469 
4470 	rb_update_read_stamp(cpu_buffer, event);
4471 
4472 	length = rb_event_length(event);
4473 	cpu_buffer->reader_page->read += length;
4474 	cpu_buffer->read_bytes += length;
4475 }
4476 
rb_advance_iter(struct ring_buffer_iter * iter)4477 static void rb_advance_iter(struct ring_buffer_iter *iter)
4478 {
4479 	struct ring_buffer_per_cpu *cpu_buffer;
4480 
4481 	cpu_buffer = iter->cpu_buffer;
4482 
4483 	/* If head == next_event then we need to jump to the next event */
4484 	if (iter->head == iter->next_event) {
4485 		/* If the event gets overwritten again, there's nothing to do */
4486 		if (rb_iter_head_event(iter) == NULL)
4487 			return;
4488 	}
4489 
4490 	iter->head = iter->next_event;
4491 
4492 	/*
4493 	 * Check if we are at the end of the buffer.
4494 	 */
4495 	if (iter->next_event >= rb_page_size(iter->head_page)) {
4496 		/* discarded commits can make the page empty */
4497 		if (iter->head_page == cpu_buffer->commit_page)
4498 			return;
4499 		rb_inc_iter(iter);
4500 		return;
4501 	}
4502 
4503 	rb_update_iter_read_stamp(iter, iter->event);
4504 }
4505 
rb_lost_events(struct ring_buffer_per_cpu * cpu_buffer)4506 static int rb_lost_events(struct ring_buffer_per_cpu *cpu_buffer)
4507 {
4508 	return cpu_buffer->lost_events;
4509 }
4510 
4511 static struct ring_buffer_event *
rb_buffer_peek(struct ring_buffer_per_cpu * cpu_buffer,u64 * ts,unsigned long * lost_events)4512 rb_buffer_peek(struct ring_buffer_per_cpu *cpu_buffer, u64 *ts,
4513 	       unsigned long *lost_events)
4514 {
4515 	struct ring_buffer_event *event;
4516 	struct buffer_page *reader;
4517 	int nr_loops = 0;
4518 
4519 	if (ts)
4520 		*ts = 0;
4521  again:
4522 	/*
4523 	 * We repeat when a time extend is encountered.
4524 	 * Since the time extend is always attached to a data event,
4525 	 * we should never loop more than once.
4526 	 * (We never hit the following condition more than twice).
4527 	 */
4528 	if (RB_WARN_ON(cpu_buffer, ++nr_loops > 2))
4529 		return NULL;
4530 
4531 	reader = rb_get_reader_page(cpu_buffer);
4532 	if (!reader)
4533 		return NULL;
4534 
4535 	event = rb_reader_event(cpu_buffer);
4536 
4537 	switch (event->type_len) {
4538 	case RINGBUF_TYPE_PADDING:
4539 		if (rb_null_event(event))
4540 			RB_WARN_ON(cpu_buffer, 1);
4541 		/*
4542 		 * Because the writer could be discarding every
4543 		 * event it creates (which would probably be bad)
4544 		 * if we were to go back to "again" then we may never
4545 		 * catch up, and will trigger the warn on, or lock
4546 		 * the box. Return the padding, and we will release
4547 		 * the current locks, and try again.
4548 		 */
4549 		return event;
4550 
4551 	case RINGBUF_TYPE_TIME_EXTEND:
4552 		/* Internal data, OK to advance */
4553 		rb_advance_reader(cpu_buffer);
4554 		goto again;
4555 
4556 	case RINGBUF_TYPE_TIME_STAMP:
4557 		if (ts) {
4558 			*ts = ring_buffer_event_time_stamp(event);
4559 			ring_buffer_normalize_time_stamp(cpu_buffer->buffer,
4560 							 cpu_buffer->cpu, ts);
4561 		}
4562 		/* Internal data, OK to advance */
4563 		rb_advance_reader(cpu_buffer);
4564 		goto again;
4565 
4566 	case RINGBUF_TYPE_DATA:
4567 		if (ts && !(*ts)) {
4568 			*ts = cpu_buffer->read_stamp + event->time_delta;
4569 			ring_buffer_normalize_time_stamp(cpu_buffer->buffer,
4570 							 cpu_buffer->cpu, ts);
4571 		}
4572 		if (lost_events)
4573 			*lost_events = rb_lost_events(cpu_buffer);
4574 		return event;
4575 
4576 	default:
4577 		RB_WARN_ON(cpu_buffer, 1);
4578 	}
4579 
4580 	return NULL;
4581 }
4582 EXPORT_SYMBOL_GPL(ring_buffer_peek);
4583 
4584 static struct ring_buffer_event *
rb_iter_peek(struct ring_buffer_iter * iter,u64 * ts)4585 rb_iter_peek(struct ring_buffer_iter *iter, u64 *ts)
4586 {
4587 	struct trace_buffer *buffer;
4588 	struct ring_buffer_per_cpu *cpu_buffer;
4589 	struct ring_buffer_event *event;
4590 	int nr_loops = 0;
4591 
4592 	if (ts)
4593 		*ts = 0;
4594 
4595 	cpu_buffer = iter->cpu_buffer;
4596 	buffer = cpu_buffer->buffer;
4597 
4598 	/*
4599 	 * Check if someone performed a consuming read to the buffer
4600 	 * or removed some pages from the buffer. In these cases,
4601 	 * iterator was invalidated and we need to reset it.
4602 	 */
4603 	if (unlikely(iter->cache_read != cpu_buffer->read ||
4604 		     iter->cache_reader_page != cpu_buffer->reader_page ||
4605 		     iter->cache_pages_removed != cpu_buffer->pages_removed))
4606 		rb_iter_reset(iter);
4607 
4608  again:
4609 	if (ring_buffer_iter_empty(iter))
4610 		return NULL;
4611 
4612 	/*
4613 	 * As the writer can mess with what the iterator is trying
4614 	 * to read, just give up if we fail to get an event after
4615 	 * three tries. The iterator is not as reliable when reading
4616 	 * the ring buffer with an active write as the consumer is.
4617 	 * Do not warn if the three failures is reached.
4618 	 */
4619 	if (++nr_loops > 3)
4620 		return NULL;
4621 
4622 	if (rb_per_cpu_empty(cpu_buffer))
4623 		return NULL;
4624 
4625 	if (iter->head >= rb_page_size(iter->head_page)) {
4626 		rb_inc_iter(iter);
4627 		goto again;
4628 	}
4629 
4630 	event = rb_iter_head_event(iter);
4631 	if (!event)
4632 		goto again;
4633 
4634 	switch (event->type_len) {
4635 	case RINGBUF_TYPE_PADDING:
4636 		if (rb_null_event(event)) {
4637 			rb_inc_iter(iter);
4638 			goto again;
4639 		}
4640 		rb_advance_iter(iter);
4641 		return event;
4642 
4643 	case RINGBUF_TYPE_TIME_EXTEND:
4644 		/* Internal data, OK to advance */
4645 		rb_advance_iter(iter);
4646 		goto again;
4647 
4648 	case RINGBUF_TYPE_TIME_STAMP:
4649 		if (ts) {
4650 			*ts = ring_buffer_event_time_stamp(event);
4651 			ring_buffer_normalize_time_stamp(cpu_buffer->buffer,
4652 							 cpu_buffer->cpu, ts);
4653 		}
4654 		/* Internal data, OK to advance */
4655 		rb_advance_iter(iter);
4656 		goto again;
4657 
4658 	case RINGBUF_TYPE_DATA:
4659 		if (ts && !(*ts)) {
4660 			*ts = iter->read_stamp + event->time_delta;
4661 			ring_buffer_normalize_time_stamp(buffer,
4662 							 cpu_buffer->cpu, ts);
4663 		}
4664 		return event;
4665 
4666 	default:
4667 		RB_WARN_ON(cpu_buffer, 1);
4668 	}
4669 
4670 	return NULL;
4671 }
4672 EXPORT_SYMBOL_GPL(ring_buffer_iter_peek);
4673 
rb_reader_lock(struct ring_buffer_per_cpu * cpu_buffer)4674 static inline bool rb_reader_lock(struct ring_buffer_per_cpu *cpu_buffer)
4675 {
4676 	if (likely(!in_nmi())) {
4677 		raw_spin_lock(&cpu_buffer->reader_lock);
4678 		return true;
4679 	}
4680 
4681 	/*
4682 	 * If an NMI die dumps out the content of the ring buffer
4683 	 * trylock must be used to prevent a deadlock if the NMI
4684 	 * preempted a task that holds the ring buffer locks. If
4685 	 * we get the lock then all is fine, if not, then continue
4686 	 * to do the read, but this can corrupt the ring buffer,
4687 	 * so it must be permanently disabled from future writes.
4688 	 * Reading from NMI is a oneshot deal.
4689 	 */
4690 	if (raw_spin_trylock(&cpu_buffer->reader_lock))
4691 		return true;
4692 
4693 	/* Continue without locking, but disable the ring buffer */
4694 	atomic_inc(&cpu_buffer->record_disabled);
4695 	return false;
4696 }
4697 
4698 static inline void
rb_reader_unlock(struct ring_buffer_per_cpu * cpu_buffer,bool locked)4699 rb_reader_unlock(struct ring_buffer_per_cpu *cpu_buffer, bool locked)
4700 {
4701 	if (likely(locked))
4702 		raw_spin_unlock(&cpu_buffer->reader_lock);
4703 	return;
4704 }
4705 
4706 /**
4707  * ring_buffer_peek - peek at the next event to be read
4708  * @buffer: The ring buffer to read
4709  * @cpu: The cpu to peak at
4710  * @ts: The timestamp counter of this event.
4711  * @lost_events: a variable to store if events were lost (may be NULL)
4712  *
4713  * This will return the event that will be read next, but does
4714  * not consume the data.
4715  */
4716 struct ring_buffer_event *
ring_buffer_peek(struct trace_buffer * buffer,int cpu,u64 * ts,unsigned long * lost_events)4717 ring_buffer_peek(struct trace_buffer *buffer, int cpu, u64 *ts,
4718 		 unsigned long *lost_events)
4719 {
4720 	struct ring_buffer_per_cpu *cpu_buffer = buffer->buffers[cpu];
4721 	struct ring_buffer_event *event;
4722 	unsigned long flags;
4723 	bool dolock;
4724 
4725 	if (!cpumask_test_cpu(cpu, buffer->cpumask))
4726 		return NULL;
4727 
4728  again:
4729 	local_irq_save(flags);
4730 	dolock = rb_reader_lock(cpu_buffer);
4731 	event = rb_buffer_peek(cpu_buffer, ts, lost_events);
4732 	if (event && event->type_len == RINGBUF_TYPE_PADDING)
4733 		rb_advance_reader(cpu_buffer);
4734 	rb_reader_unlock(cpu_buffer, dolock);
4735 	local_irq_restore(flags);
4736 
4737 	if (event && event->type_len == RINGBUF_TYPE_PADDING)
4738 		goto again;
4739 
4740 	return event;
4741 }
4742 
4743 /** ring_buffer_iter_dropped - report if there are dropped events
4744  * @iter: The ring buffer iterator
4745  *
4746  * Returns true if there was dropped events since the last peek.
4747  */
ring_buffer_iter_dropped(struct ring_buffer_iter * iter)4748 bool ring_buffer_iter_dropped(struct ring_buffer_iter *iter)
4749 {
4750 	bool ret = iter->missed_events != 0;
4751 
4752 	iter->missed_events = 0;
4753 	return ret;
4754 }
4755 EXPORT_SYMBOL_GPL(ring_buffer_iter_dropped);
4756 
4757 /**
4758  * ring_buffer_iter_peek - peek at the next event to be read
4759  * @iter: The ring buffer iterator
4760  * @ts: The timestamp counter of this event.
4761  *
4762  * This will return the event that will be read next, but does
4763  * not increment the iterator.
4764  */
4765 struct ring_buffer_event *
ring_buffer_iter_peek(struct ring_buffer_iter * iter,u64 * ts)4766 ring_buffer_iter_peek(struct ring_buffer_iter *iter, u64 *ts)
4767 {
4768 	struct ring_buffer_per_cpu *cpu_buffer = iter->cpu_buffer;
4769 	struct ring_buffer_event *event;
4770 	unsigned long flags;
4771 
4772  again:
4773 	raw_spin_lock_irqsave(&cpu_buffer->reader_lock, flags);
4774 	event = rb_iter_peek(iter, ts);
4775 	raw_spin_unlock_irqrestore(&cpu_buffer->reader_lock, flags);
4776 
4777 	if (event && event->type_len == RINGBUF_TYPE_PADDING)
4778 		goto again;
4779 
4780 	return event;
4781 }
4782 
4783 /**
4784  * ring_buffer_consume - return an event and consume it
4785  * @buffer: The ring buffer to get the next event from
4786  * @cpu: the cpu to read the buffer from
4787  * @ts: a variable to store the timestamp (may be NULL)
4788  * @lost_events: a variable to store if events were lost (may be NULL)
4789  *
4790  * Returns the next event in the ring buffer, and that event is consumed.
4791  * Meaning, that sequential reads will keep returning a different event,
4792  * and eventually empty the ring buffer if the producer is slower.
4793  */
4794 struct ring_buffer_event *
ring_buffer_consume(struct trace_buffer * buffer,int cpu,u64 * ts,unsigned long * lost_events)4795 ring_buffer_consume(struct trace_buffer *buffer, int cpu, u64 *ts,
4796 		    unsigned long *lost_events)
4797 {
4798 	struct ring_buffer_per_cpu *cpu_buffer;
4799 	struct ring_buffer_event *event = NULL;
4800 	unsigned long flags;
4801 	bool dolock;
4802 
4803  again:
4804 	/* might be called in atomic */
4805 	preempt_disable();
4806 
4807 	if (!cpumask_test_cpu(cpu, buffer->cpumask))
4808 		goto out;
4809 
4810 	cpu_buffer = buffer->buffers[cpu];
4811 	local_irq_save(flags);
4812 	dolock = rb_reader_lock(cpu_buffer);
4813 
4814 	event = rb_buffer_peek(cpu_buffer, ts, lost_events);
4815 	if (event) {
4816 		cpu_buffer->lost_events = 0;
4817 		rb_advance_reader(cpu_buffer);
4818 	}
4819 
4820 	rb_reader_unlock(cpu_buffer, dolock);
4821 	local_irq_restore(flags);
4822 
4823  out:
4824 	preempt_enable();
4825 
4826 	if (event && event->type_len == RINGBUF_TYPE_PADDING)
4827 		goto again;
4828 
4829 	return event;
4830 }
4831 EXPORT_SYMBOL_GPL(ring_buffer_consume);
4832 
4833 /**
4834  * ring_buffer_read_prepare - Prepare for a non consuming read of the buffer
4835  * @buffer: The ring buffer to read from
4836  * @cpu: The cpu buffer to iterate over
4837  * @flags: gfp flags to use for memory allocation
4838  *
4839  * This performs the initial preparations necessary to iterate
4840  * through the buffer.  Memory is allocated, buffer recording
4841  * is disabled, and the iterator pointer is returned to the caller.
4842  *
4843  * Disabling buffer recording prevents the reading from being
4844  * corrupted. This is not a consuming read, so a producer is not
4845  * expected.
4846  *
4847  * After a sequence of ring_buffer_read_prepare calls, the user is
4848  * expected to make at least one call to ring_buffer_read_prepare_sync.
4849  * Afterwards, ring_buffer_read_start is invoked to get things going
4850  * for real.
4851  *
4852  * This overall must be paired with ring_buffer_read_finish.
4853  */
4854 struct ring_buffer_iter *
ring_buffer_read_prepare(struct trace_buffer * buffer,int cpu,gfp_t flags)4855 ring_buffer_read_prepare(struct trace_buffer *buffer, int cpu, gfp_t flags)
4856 {
4857 	struct ring_buffer_per_cpu *cpu_buffer;
4858 	struct ring_buffer_iter *iter;
4859 
4860 	if (!cpumask_test_cpu(cpu, buffer->cpumask))
4861 		return NULL;
4862 
4863 	iter = kzalloc(sizeof(*iter), flags);
4864 	if (!iter)
4865 		return NULL;
4866 
4867 	/* Holds the entire event: data and meta data */
4868 	iter->event = kmalloc(BUF_PAGE_SIZE, flags);
4869 	if (!iter->event) {
4870 		kfree(iter);
4871 		return NULL;
4872 	}
4873 
4874 	cpu_buffer = buffer->buffers[cpu];
4875 
4876 	iter->cpu_buffer = cpu_buffer;
4877 
4878 	atomic_inc(&cpu_buffer->resize_disabled);
4879 
4880 	return iter;
4881 }
4882 EXPORT_SYMBOL_GPL(ring_buffer_read_prepare);
4883 
4884 /**
4885  * ring_buffer_read_prepare_sync - Synchronize a set of prepare calls
4886  *
4887  * All previously invoked ring_buffer_read_prepare calls to prepare
4888  * iterators will be synchronized.  Afterwards, read_buffer_read_start
4889  * calls on those iterators are allowed.
4890  */
4891 void
ring_buffer_read_prepare_sync(void)4892 ring_buffer_read_prepare_sync(void)
4893 {
4894 	synchronize_rcu();
4895 }
4896 EXPORT_SYMBOL_GPL(ring_buffer_read_prepare_sync);
4897 
4898 /**
4899  * ring_buffer_read_start - start a non consuming read of the buffer
4900  * @iter: The iterator returned by ring_buffer_read_prepare
4901  *
4902  * This finalizes the startup of an iteration through the buffer.
4903  * The iterator comes from a call to ring_buffer_read_prepare and
4904  * an intervening ring_buffer_read_prepare_sync must have been
4905  * performed.
4906  *
4907  * Must be paired with ring_buffer_read_finish.
4908  */
4909 void
ring_buffer_read_start(struct ring_buffer_iter * iter)4910 ring_buffer_read_start(struct ring_buffer_iter *iter)
4911 {
4912 	struct ring_buffer_per_cpu *cpu_buffer;
4913 	unsigned long flags;
4914 
4915 	if (!iter)
4916 		return;
4917 
4918 	cpu_buffer = iter->cpu_buffer;
4919 
4920 	raw_spin_lock_irqsave(&cpu_buffer->reader_lock, flags);
4921 	arch_spin_lock(&cpu_buffer->lock);
4922 	rb_iter_reset(iter);
4923 	arch_spin_unlock(&cpu_buffer->lock);
4924 	raw_spin_unlock_irqrestore(&cpu_buffer->reader_lock, flags);
4925 }
4926 EXPORT_SYMBOL_GPL(ring_buffer_read_start);
4927 
4928 /**
4929  * ring_buffer_read_finish - finish reading the iterator of the buffer
4930  * @iter: The iterator retrieved by ring_buffer_start
4931  *
4932  * This re-enables the recording to the buffer, and frees the
4933  * iterator.
4934  */
4935 void
ring_buffer_read_finish(struct ring_buffer_iter * iter)4936 ring_buffer_read_finish(struct ring_buffer_iter *iter)
4937 {
4938 	struct ring_buffer_per_cpu *cpu_buffer = iter->cpu_buffer;
4939 	unsigned long flags;
4940 
4941 	/*
4942 	 * Ring buffer is disabled from recording, here's a good place
4943 	 * to check the integrity of the ring buffer.
4944 	 * Must prevent readers from trying to read, as the check
4945 	 * clears the HEAD page and readers require it.
4946 	 */
4947 	raw_spin_lock_irqsave(&cpu_buffer->reader_lock, flags);
4948 	rb_check_pages(cpu_buffer);
4949 	raw_spin_unlock_irqrestore(&cpu_buffer->reader_lock, flags);
4950 
4951 	atomic_dec(&cpu_buffer->resize_disabled);
4952 	kfree(iter->event);
4953 	kfree(iter);
4954 }
4955 EXPORT_SYMBOL_GPL(ring_buffer_read_finish);
4956 
4957 /**
4958  * ring_buffer_iter_advance - advance the iterator to the next location
4959  * @iter: The ring buffer iterator
4960  *
4961  * Move the location of the iterator such that the next read will
4962  * be the next location of the iterator.
4963  */
ring_buffer_iter_advance(struct ring_buffer_iter * iter)4964 void ring_buffer_iter_advance(struct ring_buffer_iter *iter)
4965 {
4966 	struct ring_buffer_per_cpu *cpu_buffer = iter->cpu_buffer;
4967 	unsigned long flags;
4968 
4969 	raw_spin_lock_irqsave(&cpu_buffer->reader_lock, flags);
4970 
4971 	rb_advance_iter(iter);
4972 
4973 	raw_spin_unlock_irqrestore(&cpu_buffer->reader_lock, flags);
4974 }
4975 EXPORT_SYMBOL_GPL(ring_buffer_iter_advance);
4976 
4977 /**
4978  * ring_buffer_size - return the size of the ring buffer (in bytes)
4979  * @buffer: The ring buffer.
4980  * @cpu: The CPU to get ring buffer size from.
4981  */
ring_buffer_size(struct trace_buffer * buffer,int cpu)4982 unsigned long ring_buffer_size(struct trace_buffer *buffer, int cpu)
4983 {
4984 	/*
4985 	 * Earlier, this method returned
4986 	 *	BUF_PAGE_SIZE * buffer->nr_pages
4987 	 * Since the nr_pages field is now removed, we have converted this to
4988 	 * return the per cpu buffer value.
4989 	 */
4990 	if (!cpumask_test_cpu(cpu, buffer->cpumask))
4991 		return 0;
4992 
4993 	return BUF_PAGE_SIZE * buffer->buffers[cpu]->nr_pages;
4994 }
4995 EXPORT_SYMBOL_GPL(ring_buffer_size);
4996 
rb_clear_buffer_page(struct buffer_page * page)4997 static void rb_clear_buffer_page(struct buffer_page *page)
4998 {
4999 	local_set(&page->write, 0);
5000 	local_set(&page->entries, 0);
5001 	rb_init_page(page->page);
5002 	page->read = 0;
5003 }
5004 
5005 static void
rb_reset_cpu(struct ring_buffer_per_cpu * cpu_buffer)5006 rb_reset_cpu(struct ring_buffer_per_cpu *cpu_buffer)
5007 {
5008 	struct buffer_page *page;
5009 
5010 	rb_head_page_deactivate(cpu_buffer);
5011 
5012 	cpu_buffer->head_page
5013 		= list_entry(cpu_buffer->pages, struct buffer_page, list);
5014 	rb_clear_buffer_page(cpu_buffer->head_page);
5015 	list_for_each_entry(page, cpu_buffer->pages, list) {
5016 		rb_clear_buffer_page(page);
5017 	}
5018 
5019 	cpu_buffer->tail_page = cpu_buffer->head_page;
5020 	cpu_buffer->commit_page = cpu_buffer->head_page;
5021 
5022 	INIT_LIST_HEAD(&cpu_buffer->reader_page->list);
5023 	INIT_LIST_HEAD(&cpu_buffer->new_pages);
5024 	rb_clear_buffer_page(cpu_buffer->reader_page);
5025 
5026 	local_set(&cpu_buffer->entries_bytes, 0);
5027 	local_set(&cpu_buffer->overrun, 0);
5028 	local_set(&cpu_buffer->commit_overrun, 0);
5029 	local_set(&cpu_buffer->dropped_events, 0);
5030 	local_set(&cpu_buffer->entries, 0);
5031 	local_set(&cpu_buffer->committing, 0);
5032 	local_set(&cpu_buffer->commits, 0);
5033 	local_set(&cpu_buffer->pages_touched, 0);
5034 	local_set(&cpu_buffer->pages_lost, 0);
5035 	local_set(&cpu_buffer->pages_read, 0);
5036 	cpu_buffer->last_pages_touch = 0;
5037 	cpu_buffer->shortest_full = 0;
5038 	cpu_buffer->read = 0;
5039 	cpu_buffer->read_bytes = 0;
5040 
5041 	rb_time_set(&cpu_buffer->write_stamp, 0);
5042 	rb_time_set(&cpu_buffer->before_stamp, 0);
5043 
5044 	cpu_buffer->lost_events = 0;
5045 	cpu_buffer->last_overrun = 0;
5046 
5047 	rb_head_page_activate(cpu_buffer);
5048 	cpu_buffer->pages_removed = 0;
5049 }
5050 
5051 /* Must have disabled the cpu buffer then done a synchronize_rcu */
reset_disabled_cpu_buffer(struct ring_buffer_per_cpu * cpu_buffer)5052 static void reset_disabled_cpu_buffer(struct ring_buffer_per_cpu *cpu_buffer)
5053 {
5054 	unsigned long flags;
5055 
5056 	raw_spin_lock_irqsave(&cpu_buffer->reader_lock, flags);
5057 
5058 	if (RB_WARN_ON(cpu_buffer, local_read(&cpu_buffer->committing)))
5059 		goto out;
5060 
5061 	arch_spin_lock(&cpu_buffer->lock);
5062 
5063 	rb_reset_cpu(cpu_buffer);
5064 
5065 	arch_spin_unlock(&cpu_buffer->lock);
5066 
5067  out:
5068 	raw_spin_unlock_irqrestore(&cpu_buffer->reader_lock, flags);
5069 }
5070 
5071 /**
5072  * ring_buffer_reset_cpu - reset a ring buffer per CPU buffer
5073  * @buffer: The ring buffer to reset a per cpu buffer of
5074  * @cpu: The CPU buffer to be reset
5075  */
ring_buffer_reset_cpu(struct trace_buffer * buffer,int cpu)5076 void ring_buffer_reset_cpu(struct trace_buffer *buffer, int cpu)
5077 {
5078 	struct ring_buffer_per_cpu *cpu_buffer = buffer->buffers[cpu];
5079 
5080 	if (!cpumask_test_cpu(cpu, buffer->cpumask))
5081 		return;
5082 
5083 	/* prevent another thread from changing buffer sizes */
5084 	mutex_lock(&buffer->mutex);
5085 
5086 	atomic_inc(&cpu_buffer->resize_disabled);
5087 	atomic_inc(&cpu_buffer->record_disabled);
5088 
5089 	/* Make sure all commits have finished */
5090 	synchronize_rcu();
5091 
5092 	reset_disabled_cpu_buffer(cpu_buffer);
5093 
5094 	atomic_dec(&cpu_buffer->record_disabled);
5095 	atomic_dec(&cpu_buffer->resize_disabled);
5096 
5097 	mutex_unlock(&buffer->mutex);
5098 }
5099 EXPORT_SYMBOL_GPL(ring_buffer_reset_cpu);
5100 
5101 /* Flag to ensure proper resetting of atomic variables */
5102 #define RESET_BIT	(1 << 30)
5103 
5104 /**
5105  * ring_buffer_reset_cpu - reset a ring buffer per CPU buffer
5106  * @buffer: The ring buffer to reset a per cpu buffer of
5107  * @cpu: The CPU buffer to be reset
5108  */
ring_buffer_reset_online_cpus(struct trace_buffer * buffer)5109 void ring_buffer_reset_online_cpus(struct trace_buffer *buffer)
5110 {
5111 	struct ring_buffer_per_cpu *cpu_buffer;
5112 	int cpu;
5113 
5114 	/* prevent another thread from changing buffer sizes */
5115 	mutex_lock(&buffer->mutex);
5116 
5117 	for_each_online_buffer_cpu(buffer, cpu) {
5118 		cpu_buffer = buffer->buffers[cpu];
5119 
5120 		atomic_add(RESET_BIT, &cpu_buffer->resize_disabled);
5121 		atomic_inc(&cpu_buffer->record_disabled);
5122 	}
5123 
5124 	/* Make sure all commits have finished */
5125 	synchronize_rcu();
5126 
5127 	for_each_buffer_cpu(buffer, cpu) {
5128 		cpu_buffer = buffer->buffers[cpu];
5129 
5130 		/*
5131 		 * If a CPU came online during the synchronize_rcu(), then
5132 		 * ignore it.
5133 		 */
5134 		if (!(atomic_read(&cpu_buffer->resize_disabled) & RESET_BIT))
5135 			continue;
5136 
5137 		reset_disabled_cpu_buffer(cpu_buffer);
5138 
5139 		atomic_dec(&cpu_buffer->record_disabled);
5140 		atomic_sub(RESET_BIT, &cpu_buffer->resize_disabled);
5141 	}
5142 
5143 	mutex_unlock(&buffer->mutex);
5144 }
5145 
5146 /**
5147  * ring_buffer_reset - reset a ring buffer
5148  * @buffer: The ring buffer to reset all cpu buffers
5149  */
ring_buffer_reset(struct trace_buffer * buffer)5150 void ring_buffer_reset(struct trace_buffer *buffer)
5151 {
5152 	struct ring_buffer_per_cpu *cpu_buffer;
5153 	int cpu;
5154 
5155 	/* prevent another thread from changing buffer sizes */
5156 	mutex_lock(&buffer->mutex);
5157 
5158 	for_each_buffer_cpu(buffer, cpu) {
5159 		cpu_buffer = buffer->buffers[cpu];
5160 
5161 		atomic_inc(&cpu_buffer->resize_disabled);
5162 		atomic_inc(&cpu_buffer->record_disabled);
5163 	}
5164 
5165 	/* Make sure all commits have finished */
5166 	synchronize_rcu();
5167 
5168 	for_each_buffer_cpu(buffer, cpu) {
5169 		cpu_buffer = buffer->buffers[cpu];
5170 
5171 		reset_disabled_cpu_buffer(cpu_buffer);
5172 
5173 		atomic_dec(&cpu_buffer->record_disabled);
5174 		atomic_dec(&cpu_buffer->resize_disabled);
5175 	}
5176 
5177 	mutex_unlock(&buffer->mutex);
5178 }
5179 EXPORT_SYMBOL_GPL(ring_buffer_reset);
5180 
5181 /**
5182  * rind_buffer_empty - is the ring buffer empty?
5183  * @buffer: The ring buffer to test
5184  */
ring_buffer_empty(struct trace_buffer * buffer)5185 bool ring_buffer_empty(struct trace_buffer *buffer)
5186 {
5187 	struct ring_buffer_per_cpu *cpu_buffer;
5188 	unsigned long flags;
5189 	bool dolock;
5190 	int cpu;
5191 	int ret;
5192 
5193 	/* yes this is racy, but if you don't like the race, lock the buffer */
5194 	for_each_buffer_cpu(buffer, cpu) {
5195 		cpu_buffer = buffer->buffers[cpu];
5196 		local_irq_save(flags);
5197 		dolock = rb_reader_lock(cpu_buffer);
5198 		ret = rb_per_cpu_empty(cpu_buffer);
5199 		rb_reader_unlock(cpu_buffer, dolock);
5200 		local_irq_restore(flags);
5201 
5202 		if (!ret)
5203 			return false;
5204 	}
5205 
5206 	return true;
5207 }
5208 EXPORT_SYMBOL_GPL(ring_buffer_empty);
5209 
5210 /**
5211  * ring_buffer_empty_cpu - is a cpu buffer of a ring buffer empty?
5212  * @buffer: The ring buffer
5213  * @cpu: The CPU buffer to test
5214  */
ring_buffer_empty_cpu(struct trace_buffer * buffer,int cpu)5215 bool ring_buffer_empty_cpu(struct trace_buffer *buffer, int cpu)
5216 {
5217 	struct ring_buffer_per_cpu *cpu_buffer;
5218 	unsigned long flags;
5219 	bool dolock;
5220 	int ret;
5221 
5222 	if (!cpumask_test_cpu(cpu, buffer->cpumask))
5223 		return true;
5224 
5225 	cpu_buffer = buffer->buffers[cpu];
5226 	local_irq_save(flags);
5227 	dolock = rb_reader_lock(cpu_buffer);
5228 	ret = rb_per_cpu_empty(cpu_buffer);
5229 	rb_reader_unlock(cpu_buffer, dolock);
5230 	local_irq_restore(flags);
5231 
5232 	return ret;
5233 }
5234 EXPORT_SYMBOL_GPL(ring_buffer_empty_cpu);
5235 
5236 #ifdef CONFIG_RING_BUFFER_ALLOW_SWAP
5237 /**
5238  * ring_buffer_swap_cpu - swap a CPU buffer between two ring buffers
5239  * @buffer_a: One buffer to swap with
5240  * @buffer_b: The other buffer to swap with
5241  * @cpu: the CPU of the buffers to swap
5242  *
5243  * This function is useful for tracers that want to take a "snapshot"
5244  * of a CPU buffer and has another back up buffer lying around.
5245  * it is expected that the tracer handles the cpu buffer not being
5246  * used at the moment.
5247  */
ring_buffer_swap_cpu(struct trace_buffer * buffer_a,struct trace_buffer * buffer_b,int cpu)5248 int ring_buffer_swap_cpu(struct trace_buffer *buffer_a,
5249 			 struct trace_buffer *buffer_b, int cpu)
5250 {
5251 	struct ring_buffer_per_cpu *cpu_buffer_a;
5252 	struct ring_buffer_per_cpu *cpu_buffer_b;
5253 	int ret = -EINVAL;
5254 
5255 	if (!cpumask_test_cpu(cpu, buffer_a->cpumask) ||
5256 	    !cpumask_test_cpu(cpu, buffer_b->cpumask))
5257 		goto out;
5258 
5259 	cpu_buffer_a = buffer_a->buffers[cpu];
5260 	cpu_buffer_b = buffer_b->buffers[cpu];
5261 
5262 	/* At least make sure the two buffers are somewhat the same */
5263 	if (cpu_buffer_a->nr_pages != cpu_buffer_b->nr_pages)
5264 		goto out;
5265 
5266 	ret = -EAGAIN;
5267 
5268 	if (atomic_read(&buffer_a->record_disabled))
5269 		goto out;
5270 
5271 	if (atomic_read(&buffer_b->record_disabled))
5272 		goto out;
5273 
5274 	if (atomic_read(&cpu_buffer_a->record_disabled))
5275 		goto out;
5276 
5277 	if (atomic_read(&cpu_buffer_b->record_disabled))
5278 		goto out;
5279 
5280 	/*
5281 	 * We can't do a synchronize_rcu here because this
5282 	 * function can be called in atomic context.
5283 	 * Normally this will be called from the same CPU as cpu.
5284 	 * If not it's up to the caller to protect this.
5285 	 */
5286 	atomic_inc(&cpu_buffer_a->record_disabled);
5287 	atomic_inc(&cpu_buffer_b->record_disabled);
5288 
5289 	ret = -EBUSY;
5290 	if (local_read(&cpu_buffer_a->committing))
5291 		goto out_dec;
5292 	if (local_read(&cpu_buffer_b->committing))
5293 		goto out_dec;
5294 
5295 	/*
5296 	 * When resize is in progress, we cannot swap it because
5297 	 * it will mess the state of the cpu buffer.
5298 	 */
5299 	if (atomic_read(&buffer_a->resizing))
5300 		goto out_dec;
5301 	if (atomic_read(&buffer_b->resizing))
5302 		goto out_dec;
5303 
5304 	buffer_a->buffers[cpu] = cpu_buffer_b;
5305 	buffer_b->buffers[cpu] = cpu_buffer_a;
5306 
5307 	cpu_buffer_b->buffer = buffer_a;
5308 	cpu_buffer_a->buffer = buffer_b;
5309 
5310 	ret = 0;
5311 
5312 out_dec:
5313 	atomic_dec(&cpu_buffer_a->record_disabled);
5314 	atomic_dec(&cpu_buffer_b->record_disabled);
5315 out:
5316 	return ret;
5317 }
5318 EXPORT_SYMBOL_GPL(ring_buffer_swap_cpu);
5319 #endif /* CONFIG_RING_BUFFER_ALLOW_SWAP */
5320 
5321 /**
5322  * ring_buffer_alloc_read_page - allocate a page to read from buffer
5323  * @buffer: the buffer to allocate for.
5324  * @cpu: the cpu buffer to allocate.
5325  *
5326  * This function is used in conjunction with ring_buffer_read_page.
5327  * When reading a full page from the ring buffer, these functions
5328  * can be used to speed up the process. The calling function should
5329  * allocate a few pages first with this function. Then when it
5330  * needs to get pages from the ring buffer, it passes the result
5331  * of this function into ring_buffer_read_page, which will swap
5332  * the page that was allocated, with the read page of the buffer.
5333  *
5334  * Returns:
5335  *  The page allocated, or ERR_PTR
5336  */
ring_buffer_alloc_read_page(struct trace_buffer * buffer,int cpu)5337 void *ring_buffer_alloc_read_page(struct trace_buffer *buffer, int cpu)
5338 {
5339 	struct ring_buffer_per_cpu *cpu_buffer;
5340 	struct buffer_data_page *bpage = NULL;
5341 	unsigned long flags;
5342 	struct page *page;
5343 
5344 	if (!cpumask_test_cpu(cpu, buffer->cpumask))
5345 		return ERR_PTR(-ENODEV);
5346 
5347 	cpu_buffer = buffer->buffers[cpu];
5348 	local_irq_save(flags);
5349 	arch_spin_lock(&cpu_buffer->lock);
5350 
5351 	if (cpu_buffer->free_page) {
5352 		bpage = cpu_buffer->free_page;
5353 		cpu_buffer->free_page = NULL;
5354 	}
5355 
5356 	arch_spin_unlock(&cpu_buffer->lock);
5357 	local_irq_restore(flags);
5358 
5359 	if (bpage)
5360 		goto out;
5361 
5362 	page = alloc_pages_node(cpu_to_node(cpu),
5363 				GFP_KERNEL | __GFP_NORETRY, 0);
5364 	if (!page)
5365 		return ERR_PTR(-ENOMEM);
5366 
5367 	bpage = page_address(page);
5368 
5369  out:
5370 	rb_init_page(bpage);
5371 
5372 	return bpage;
5373 }
5374 EXPORT_SYMBOL_GPL(ring_buffer_alloc_read_page);
5375 
5376 /**
5377  * ring_buffer_free_read_page - free an allocated read page
5378  * @buffer: the buffer the page was allocate for
5379  * @cpu: the cpu buffer the page came from
5380  * @data: the page to free
5381  *
5382  * Free a page allocated from ring_buffer_alloc_read_page.
5383  */
ring_buffer_free_read_page(struct trace_buffer * buffer,int cpu,void * data)5384 void ring_buffer_free_read_page(struct trace_buffer *buffer, int cpu, void *data)
5385 {
5386 	struct ring_buffer_per_cpu *cpu_buffer;
5387 	struct buffer_data_page *bpage = data;
5388 	struct page *page = virt_to_page(bpage);
5389 	unsigned long flags;
5390 
5391 	if (!buffer || !buffer->buffers || !buffer->buffers[cpu])
5392 		return;
5393 
5394 	cpu_buffer = buffer->buffers[cpu];
5395 
5396 	/* If the page is still in use someplace else, we can't reuse it */
5397 	if (page_ref_count(page) > 1)
5398 		goto out;
5399 
5400 	local_irq_save(flags);
5401 	arch_spin_lock(&cpu_buffer->lock);
5402 
5403 	if (!cpu_buffer->free_page) {
5404 		cpu_buffer->free_page = bpage;
5405 		bpage = NULL;
5406 	}
5407 
5408 	arch_spin_unlock(&cpu_buffer->lock);
5409 	local_irq_restore(flags);
5410 
5411  out:
5412 	free_page((unsigned long)bpage);
5413 }
5414 EXPORT_SYMBOL_GPL(ring_buffer_free_read_page);
5415 
5416 /**
5417  * ring_buffer_read_page - extract a page from the ring buffer
5418  * @buffer: buffer to extract from
5419  * @data_page: the page to use allocated from ring_buffer_alloc_read_page
5420  * @len: amount to extract
5421  * @cpu: the cpu of the buffer to extract
5422  * @full: should the extraction only happen when the page is full.
5423  *
5424  * This function will pull out a page from the ring buffer and consume it.
5425  * @data_page must be the address of the variable that was returned
5426  * from ring_buffer_alloc_read_page. This is because the page might be used
5427  * to swap with a page in the ring buffer.
5428  *
5429  * for example:
5430  *	rpage = ring_buffer_alloc_read_page(buffer, cpu);
5431  *	if (IS_ERR(rpage))
5432  *		return PTR_ERR(rpage);
5433  *	ret = ring_buffer_read_page(buffer, &rpage, len, cpu, 0);
5434  *	if (ret >= 0)
5435  *		process_page(rpage, ret);
5436  *
5437  * When @full is set, the function will not return true unless
5438  * the writer is off the reader page.
5439  *
5440  * Note: it is up to the calling functions to handle sleeps and wakeups.
5441  *  The ring buffer can be used anywhere in the kernel and can not
5442  *  blindly call wake_up. The layer that uses the ring buffer must be
5443  *  responsible for that.
5444  *
5445  * Returns:
5446  *  >=0 if data has been transferred, returns the offset of consumed data.
5447  *  <0 if no data has been transferred.
5448  */
ring_buffer_read_page(struct trace_buffer * buffer,void ** data_page,size_t len,int cpu,int full)5449 int ring_buffer_read_page(struct trace_buffer *buffer,
5450 			  void **data_page, size_t len, int cpu, int full)
5451 {
5452 	struct ring_buffer_per_cpu *cpu_buffer = buffer->buffers[cpu];
5453 	struct ring_buffer_event *event;
5454 	struct buffer_data_page *bpage;
5455 	struct buffer_page *reader;
5456 	unsigned long missed_events;
5457 	unsigned long flags;
5458 	unsigned int commit;
5459 	unsigned int read;
5460 	u64 save_timestamp;
5461 	int ret = -1;
5462 
5463 	if (!cpumask_test_cpu(cpu, buffer->cpumask))
5464 		goto out;
5465 
5466 	/*
5467 	 * If len is not big enough to hold the page header, then
5468 	 * we can not copy anything.
5469 	 */
5470 	if (len <= BUF_PAGE_HDR_SIZE)
5471 		goto out;
5472 
5473 	len -= BUF_PAGE_HDR_SIZE;
5474 
5475 	if (!data_page)
5476 		goto out;
5477 
5478 	bpage = *data_page;
5479 	if (!bpage)
5480 		goto out;
5481 
5482 	raw_spin_lock_irqsave(&cpu_buffer->reader_lock, flags);
5483 
5484 	reader = rb_get_reader_page(cpu_buffer);
5485 	if (!reader)
5486 		goto out_unlock;
5487 
5488 	event = rb_reader_event(cpu_buffer);
5489 
5490 	read = reader->read;
5491 	commit = rb_page_commit(reader);
5492 
5493 	/* Check if any events were dropped */
5494 	missed_events = cpu_buffer->lost_events;
5495 
5496 	/*
5497 	 * If this page has been partially read or
5498 	 * if len is not big enough to read the rest of the page or
5499 	 * a writer is still on the page, then
5500 	 * we must copy the data from the page to the buffer.
5501 	 * Otherwise, we can simply swap the page with the one passed in.
5502 	 */
5503 	if (read || (len < (commit - read)) ||
5504 	    cpu_buffer->reader_page == cpu_buffer->commit_page) {
5505 		struct buffer_data_page *rpage = cpu_buffer->reader_page->page;
5506 		unsigned int rpos = read;
5507 		unsigned int pos = 0;
5508 		unsigned int size;
5509 
5510 		/*
5511 		 * If a full page is expected, this can still be returned
5512 		 * if there's been a previous partial read and the
5513 		 * rest of the page can be read and the commit page is off
5514 		 * the reader page.
5515 		 */
5516 		if (full &&
5517 		    (!read || (len < (commit - read)) ||
5518 		     cpu_buffer->reader_page == cpu_buffer->commit_page))
5519 			goto out_unlock;
5520 
5521 		if (len > (commit - read))
5522 			len = (commit - read);
5523 
5524 		/* Always keep the time extend and data together */
5525 		size = rb_event_ts_length(event);
5526 
5527 		if (len < size)
5528 			goto out_unlock;
5529 
5530 		/* save the current timestamp, since the user will need it */
5531 		save_timestamp = cpu_buffer->read_stamp;
5532 
5533 		/* Need to copy one event at a time */
5534 		do {
5535 			/* We need the size of one event, because
5536 			 * rb_advance_reader only advances by one event,
5537 			 * whereas rb_event_ts_length may include the size of
5538 			 * one or two events.
5539 			 * We have already ensured there's enough space if this
5540 			 * is a time extend. */
5541 			size = rb_event_length(event);
5542 			memcpy(bpage->data + pos, rpage->data + rpos, size);
5543 
5544 			len -= size;
5545 
5546 			rb_advance_reader(cpu_buffer);
5547 			rpos = reader->read;
5548 			pos += size;
5549 
5550 			if (rpos >= commit)
5551 				break;
5552 
5553 			event = rb_reader_event(cpu_buffer);
5554 			/* Always keep the time extend and data together */
5555 			size = rb_event_ts_length(event);
5556 		} while (len >= size);
5557 
5558 		/* update bpage */
5559 		local_set(&bpage->commit, pos);
5560 		bpage->time_stamp = save_timestamp;
5561 
5562 		/* we copied everything to the beginning */
5563 		read = 0;
5564 	} else {
5565 		/* update the entry counter */
5566 		cpu_buffer->read += rb_page_entries(reader);
5567 		cpu_buffer->read_bytes += rb_page_commit(reader);
5568 
5569 		/* swap the pages */
5570 		rb_init_page(bpage);
5571 		bpage = reader->page;
5572 		reader->page = *data_page;
5573 		local_set(&reader->write, 0);
5574 		local_set(&reader->entries, 0);
5575 		reader->read = 0;
5576 		*data_page = bpage;
5577 
5578 		/*
5579 		 * Use the real_end for the data size,
5580 		 * This gives us a chance to store the lost events
5581 		 * on the page.
5582 		 */
5583 		if (reader->real_end)
5584 			local_set(&bpage->commit, reader->real_end);
5585 	}
5586 	ret = read;
5587 
5588 	cpu_buffer->lost_events = 0;
5589 
5590 	commit = local_read(&bpage->commit);
5591 	/*
5592 	 * Set a flag in the commit field if we lost events
5593 	 */
5594 	if (missed_events) {
5595 		/* If there is room at the end of the page to save the
5596 		 * missed events, then record it there.
5597 		 */
5598 		if (BUF_PAGE_SIZE - commit >= sizeof(missed_events)) {
5599 			memcpy(&bpage->data[commit], &missed_events,
5600 			       sizeof(missed_events));
5601 			local_add(RB_MISSED_STORED, &bpage->commit);
5602 			commit += sizeof(missed_events);
5603 		}
5604 		local_add(RB_MISSED_EVENTS, &bpage->commit);
5605 	}
5606 
5607 	/*
5608 	 * This page may be off to user land. Zero it out here.
5609 	 */
5610 	if (commit < BUF_PAGE_SIZE)
5611 		memset(&bpage->data[commit], 0, BUF_PAGE_SIZE - commit);
5612 
5613  out_unlock:
5614 	raw_spin_unlock_irqrestore(&cpu_buffer->reader_lock, flags);
5615 
5616  out:
5617 	return ret;
5618 }
5619 EXPORT_SYMBOL_GPL(ring_buffer_read_page);
5620 
5621 /*
5622  * We only allocate new buffers, never free them if the CPU goes down.
5623  * If we were to free the buffer, then the user would lose any trace that was in
5624  * the buffer.
5625  */
trace_rb_cpu_prepare(unsigned int cpu,struct hlist_node * node)5626 int trace_rb_cpu_prepare(unsigned int cpu, struct hlist_node *node)
5627 {
5628 	struct trace_buffer *buffer;
5629 	long nr_pages_same;
5630 	int cpu_i;
5631 	unsigned long nr_pages;
5632 
5633 	buffer = container_of(node, struct trace_buffer, node);
5634 	if (cpumask_test_cpu(cpu, buffer->cpumask))
5635 		return 0;
5636 
5637 	nr_pages = 0;
5638 	nr_pages_same = 1;
5639 	/* check if all cpu sizes are same */
5640 	for_each_buffer_cpu(buffer, cpu_i) {
5641 		/* fill in the size from first enabled cpu */
5642 		if (nr_pages == 0)
5643 			nr_pages = buffer->buffers[cpu_i]->nr_pages;
5644 		if (nr_pages != buffer->buffers[cpu_i]->nr_pages) {
5645 			nr_pages_same = 0;
5646 			break;
5647 		}
5648 	}
5649 	/* allocate minimum pages, user can later expand it */
5650 	if (!nr_pages_same)
5651 		nr_pages = 2;
5652 	buffer->buffers[cpu] =
5653 		rb_allocate_cpu_buffer(buffer, nr_pages, cpu);
5654 	if (!buffer->buffers[cpu]) {
5655 		WARN(1, "failed to allocate ring buffer on CPU %u\n",
5656 		     cpu);
5657 		return -ENOMEM;
5658 	}
5659 	smp_wmb();
5660 	cpumask_set_cpu(cpu, buffer->cpumask);
5661 	return 0;
5662 }
5663 
5664 #ifdef CONFIG_RING_BUFFER_STARTUP_TEST
5665 /*
5666  * This is a basic integrity check of the ring buffer.
5667  * Late in the boot cycle this test will run when configured in.
5668  * It will kick off a thread per CPU that will go into a loop
5669  * writing to the per cpu ring buffer various sizes of data.
5670  * Some of the data will be large items, some small.
5671  *
5672  * Another thread is created that goes into a spin, sending out
5673  * IPIs to the other CPUs to also write into the ring buffer.
5674  * this is to test the nesting ability of the buffer.
5675  *
5676  * Basic stats are recorded and reported. If something in the
5677  * ring buffer should happen that's not expected, a big warning
5678  * is displayed and all ring buffers are disabled.
5679  */
5680 static struct task_struct *rb_threads[NR_CPUS] __initdata;
5681 
5682 struct rb_test_data {
5683 	struct trace_buffer *buffer;
5684 	unsigned long		events;
5685 	unsigned long		bytes_written;
5686 	unsigned long		bytes_alloc;
5687 	unsigned long		bytes_dropped;
5688 	unsigned long		events_nested;
5689 	unsigned long		bytes_written_nested;
5690 	unsigned long		bytes_alloc_nested;
5691 	unsigned long		bytes_dropped_nested;
5692 	int			min_size_nested;
5693 	int			max_size_nested;
5694 	int			max_size;
5695 	int			min_size;
5696 	int			cpu;
5697 	int			cnt;
5698 };
5699 
5700 static struct rb_test_data rb_data[NR_CPUS] __initdata;
5701 
5702 /* 1 meg per cpu */
5703 #define RB_TEST_BUFFER_SIZE	1048576
5704 
5705 static char rb_string[] __initdata =
5706 	"abcdefghijklmnopqrstuvwxyz1234567890!@#$%^&*()?+\\"
5707 	"?+|:';\",.<>/?abcdefghijklmnopqrstuvwxyz1234567890"
5708 	"!@#$%^&*()?+\\?+|:';\",.<>/?abcdefghijklmnopqrstuv";
5709 
5710 static bool rb_test_started __initdata;
5711 
5712 struct rb_item {
5713 	int size;
5714 	char str[];
5715 };
5716 
rb_write_something(struct rb_test_data * data,bool nested)5717 static __init int rb_write_something(struct rb_test_data *data, bool nested)
5718 {
5719 	struct ring_buffer_event *event;
5720 	struct rb_item *item;
5721 	bool started;
5722 	int event_len;
5723 	int size;
5724 	int len;
5725 	int cnt;
5726 
5727 	/* Have nested writes different that what is written */
5728 	cnt = data->cnt + (nested ? 27 : 0);
5729 
5730 	/* Multiply cnt by ~e, to make some unique increment */
5731 	size = (cnt * 68 / 25) % (sizeof(rb_string) - 1);
5732 
5733 	len = size + sizeof(struct rb_item);
5734 
5735 	started = rb_test_started;
5736 	/* read rb_test_started before checking buffer enabled */
5737 	smp_rmb();
5738 
5739 	event = ring_buffer_lock_reserve(data->buffer, len);
5740 	if (!event) {
5741 		/* Ignore dropped events before test starts. */
5742 		if (started) {
5743 			if (nested)
5744 				data->bytes_dropped += len;
5745 			else
5746 				data->bytes_dropped_nested += len;
5747 		}
5748 		return len;
5749 	}
5750 
5751 	event_len = ring_buffer_event_length(event);
5752 
5753 	if (RB_WARN_ON(data->buffer, event_len < len))
5754 		goto out;
5755 
5756 	item = ring_buffer_event_data(event);
5757 	item->size = size;
5758 	memcpy(item->str, rb_string, size);
5759 
5760 	if (nested) {
5761 		data->bytes_alloc_nested += event_len;
5762 		data->bytes_written_nested += len;
5763 		data->events_nested++;
5764 		if (!data->min_size_nested || len < data->min_size_nested)
5765 			data->min_size_nested = len;
5766 		if (len > data->max_size_nested)
5767 			data->max_size_nested = len;
5768 	} else {
5769 		data->bytes_alloc += event_len;
5770 		data->bytes_written += len;
5771 		data->events++;
5772 		if (!data->min_size || len < data->min_size)
5773 			data->max_size = len;
5774 		if (len > data->max_size)
5775 			data->max_size = len;
5776 	}
5777 
5778  out:
5779 	ring_buffer_unlock_commit(data->buffer, event);
5780 
5781 	return 0;
5782 }
5783 
rb_test(void * arg)5784 static __init int rb_test(void *arg)
5785 {
5786 	struct rb_test_data *data = arg;
5787 
5788 	while (!kthread_should_stop()) {
5789 		rb_write_something(data, false);
5790 		data->cnt++;
5791 
5792 		set_current_state(TASK_INTERRUPTIBLE);
5793 		/* Now sleep between a min of 100-300us and a max of 1ms */
5794 		usleep_range(((data->cnt % 3) + 1) * 100, 1000);
5795 	}
5796 
5797 	return 0;
5798 }
5799 
rb_ipi(void * ignore)5800 static __init void rb_ipi(void *ignore)
5801 {
5802 	struct rb_test_data *data;
5803 	int cpu = smp_processor_id();
5804 
5805 	data = &rb_data[cpu];
5806 	rb_write_something(data, true);
5807 }
5808 
rb_hammer_test(void * arg)5809 static __init int rb_hammer_test(void *arg)
5810 {
5811 	while (!kthread_should_stop()) {
5812 
5813 		/* Send an IPI to all cpus to write data! */
5814 		smp_call_function(rb_ipi, NULL, 1);
5815 		/* No sleep, but for non preempt, let others run */
5816 		schedule();
5817 	}
5818 
5819 	return 0;
5820 }
5821 
test_ringbuffer(void)5822 static __init int test_ringbuffer(void)
5823 {
5824 	struct task_struct *rb_hammer;
5825 	struct trace_buffer *buffer;
5826 	int cpu;
5827 	int ret = 0;
5828 
5829 	if (security_locked_down(LOCKDOWN_TRACEFS)) {
5830 		pr_warn("Lockdown is enabled, skipping ring buffer tests\n");
5831 		return 0;
5832 	}
5833 
5834 	pr_info("Running ring buffer tests...\n");
5835 
5836 	buffer = ring_buffer_alloc(RB_TEST_BUFFER_SIZE, RB_FL_OVERWRITE);
5837 	if (WARN_ON(!buffer))
5838 		return 0;
5839 
5840 	/* Disable buffer so that threads can't write to it yet */
5841 	ring_buffer_record_off(buffer);
5842 
5843 	for_each_online_cpu(cpu) {
5844 		rb_data[cpu].buffer = buffer;
5845 		rb_data[cpu].cpu = cpu;
5846 		rb_data[cpu].cnt = cpu;
5847 		rb_threads[cpu] = kthread_create(rb_test, &rb_data[cpu],
5848 						 "rbtester/%d", cpu);
5849 		if (WARN_ON(IS_ERR(rb_threads[cpu]))) {
5850 			pr_cont("FAILED\n");
5851 			ret = PTR_ERR(rb_threads[cpu]);
5852 			goto out_free;
5853 		}
5854 
5855 		kthread_bind(rb_threads[cpu], cpu);
5856  		wake_up_process(rb_threads[cpu]);
5857 	}
5858 
5859 	/* Now create the rb hammer! */
5860 	rb_hammer = kthread_run(rb_hammer_test, NULL, "rbhammer");
5861 	if (WARN_ON(IS_ERR(rb_hammer))) {
5862 		pr_cont("FAILED\n");
5863 		ret = PTR_ERR(rb_hammer);
5864 		goto out_free;
5865 	}
5866 
5867 	ring_buffer_record_on(buffer);
5868 	/*
5869 	 * Show buffer is enabled before setting rb_test_started.
5870 	 * Yes there's a small race window where events could be
5871 	 * dropped and the thread wont catch it. But when a ring
5872 	 * buffer gets enabled, there will always be some kind of
5873 	 * delay before other CPUs see it. Thus, we don't care about
5874 	 * those dropped events. We care about events dropped after
5875 	 * the threads see that the buffer is active.
5876 	 */
5877 	smp_wmb();
5878 	rb_test_started = true;
5879 
5880 	set_current_state(TASK_INTERRUPTIBLE);
5881 	/* Just run for 10 seconds */;
5882 	schedule_timeout(10 * HZ);
5883 
5884 	kthread_stop(rb_hammer);
5885 
5886  out_free:
5887 	for_each_online_cpu(cpu) {
5888 		if (!rb_threads[cpu])
5889 			break;
5890 		kthread_stop(rb_threads[cpu]);
5891 	}
5892 	if (ret) {
5893 		ring_buffer_free(buffer);
5894 		return ret;
5895 	}
5896 
5897 	/* Report! */
5898 	pr_info("finished\n");
5899 	for_each_online_cpu(cpu) {
5900 		struct ring_buffer_event *event;
5901 		struct rb_test_data *data = &rb_data[cpu];
5902 		struct rb_item *item;
5903 		unsigned long total_events;
5904 		unsigned long total_dropped;
5905 		unsigned long total_written;
5906 		unsigned long total_alloc;
5907 		unsigned long total_read = 0;
5908 		unsigned long total_size = 0;
5909 		unsigned long total_len = 0;
5910 		unsigned long total_lost = 0;
5911 		unsigned long lost;
5912 		int big_event_size;
5913 		int small_event_size;
5914 
5915 		ret = -1;
5916 
5917 		total_events = data->events + data->events_nested;
5918 		total_written = data->bytes_written + data->bytes_written_nested;
5919 		total_alloc = data->bytes_alloc + data->bytes_alloc_nested;
5920 		total_dropped = data->bytes_dropped + data->bytes_dropped_nested;
5921 
5922 		big_event_size = data->max_size + data->max_size_nested;
5923 		small_event_size = data->min_size + data->min_size_nested;
5924 
5925 		pr_info("CPU %d:\n", cpu);
5926 		pr_info("              events:    %ld\n", total_events);
5927 		pr_info("       dropped bytes:    %ld\n", total_dropped);
5928 		pr_info("       alloced bytes:    %ld\n", total_alloc);
5929 		pr_info("       written bytes:    %ld\n", total_written);
5930 		pr_info("       biggest event:    %d\n", big_event_size);
5931 		pr_info("      smallest event:    %d\n", small_event_size);
5932 
5933 		if (RB_WARN_ON(buffer, total_dropped))
5934 			break;
5935 
5936 		ret = 0;
5937 
5938 		while ((event = ring_buffer_consume(buffer, cpu, NULL, &lost))) {
5939 			total_lost += lost;
5940 			item = ring_buffer_event_data(event);
5941 			total_len += ring_buffer_event_length(event);
5942 			total_size += item->size + sizeof(struct rb_item);
5943 			if (memcmp(&item->str[0], rb_string, item->size) != 0) {
5944 				pr_info("FAILED!\n");
5945 				pr_info("buffer had: %.*s\n", item->size, item->str);
5946 				pr_info("expected:   %.*s\n", item->size, rb_string);
5947 				RB_WARN_ON(buffer, 1);
5948 				ret = -1;
5949 				break;
5950 			}
5951 			total_read++;
5952 		}
5953 		if (ret)
5954 			break;
5955 
5956 		ret = -1;
5957 
5958 		pr_info("         read events:   %ld\n", total_read);
5959 		pr_info("         lost events:   %ld\n", total_lost);
5960 		pr_info("        total events:   %ld\n", total_lost + total_read);
5961 		pr_info("  recorded len bytes:   %ld\n", total_len);
5962 		pr_info(" recorded size bytes:   %ld\n", total_size);
5963 		if (total_lost)
5964 			pr_info(" With dropped events, record len and size may not match\n"
5965 				" alloced and written from above\n");
5966 		if (!total_lost) {
5967 			if (RB_WARN_ON(buffer, total_len != total_alloc ||
5968 				       total_size != total_written))
5969 				break;
5970 		}
5971 		if (RB_WARN_ON(buffer, total_lost + total_read != total_events))
5972 			break;
5973 
5974 		ret = 0;
5975 	}
5976 	if (!ret)
5977 		pr_info("Ring buffer PASSED!\n");
5978 
5979 	ring_buffer_free(buffer);
5980 	return 0;
5981 }
5982 
5983 late_initcall(test_ringbuffer);
5984 #endif /* CONFIG_RING_BUFFER_STARTUP_TEST */
5985