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