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