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