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