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