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