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