]> Pileus Git - ~andy/linux/blob - kernel/trace/ring_buffer.c
ring-buffer: Add per_cpu ring buffer control files
[~andy/linux] / kernel / trace / ring_buffer.c
1 /*
2  * Generic ring buffer
3  *
4  * Copyright (C) 2008 Steven Rostedt <srostedt@redhat.com>
5  */
6 #include <linux/ring_buffer.h>
7 #include <linux/trace_clock.h>
8 #include <linux/spinlock.h>
9 #include <linux/debugfs.h>
10 #include <linux/uaccess.h>
11 #include <linux/hardirq.h>
12 #include <linux/kmemcheck.h>
13 #include <linux/module.h>
14 #include <linux/percpu.h>
15 #include <linux/mutex.h>
16 #include <linux/slab.h>
17 #include <linux/init.h>
18 #include <linux/hash.h>
19 #include <linux/list.h>
20 #include <linux/cpu.h>
21 #include <linux/fs.h>
22
23 #include <asm/local.h>
24 #include "trace.h"
25
26 /*
27  * The ring buffer header is special. We must manually up keep it.
28  */
29 int ring_buffer_print_entry_header(struct trace_seq *s)
30 {
31         int ret;
32
33         ret = trace_seq_printf(s, "# compressed entry header\n");
34         ret = trace_seq_printf(s, "\ttype_len    :    5 bits\n");
35         ret = trace_seq_printf(s, "\ttime_delta  :   27 bits\n");
36         ret = trace_seq_printf(s, "\tarray       :   32 bits\n");
37         ret = trace_seq_printf(s, "\n");
38         ret = trace_seq_printf(s, "\tpadding     : type == %d\n",
39                                RINGBUF_TYPE_PADDING);
40         ret = trace_seq_printf(s, "\ttime_extend : type == %d\n",
41                                RINGBUF_TYPE_TIME_EXTEND);
42         ret = trace_seq_printf(s, "\tdata max type_len  == %d\n",
43                                RINGBUF_TYPE_DATA_TYPE_LEN_MAX);
44
45         return ret;
46 }
47
48 /*
49  * The ring buffer is made up of a list of pages. A separate list of pages is
50  * allocated for each CPU. A writer may only write to a buffer that is
51  * associated with the CPU it is currently executing on.  A reader may read
52  * from any per cpu buffer.
53  *
54  * The reader is special. For each per cpu buffer, the reader has its own
55  * reader page. When a reader has read the entire reader page, this reader
56  * page is swapped with another page in the ring buffer.
57  *
58  * Now, as long as the writer is off the reader page, the reader can do what
59  * ever it wants with that page. The writer will never write to that page
60  * again (as long as it is out of the ring buffer).
61  *
62  * Here's some silly ASCII art.
63  *
64  *   +------+
65  *   |reader|          RING BUFFER
66  *   |page  |
67  *   +------+        +---+   +---+   +---+
68  *                   |   |-->|   |-->|   |
69  *                   +---+   +---+   +---+
70  *                     ^               |
71  *                     |               |
72  *                     +---------------+
73  *
74  *
75  *   +------+
76  *   |reader|          RING BUFFER
77  *   |page  |------------------v
78  *   +------+        +---+   +---+   +---+
79  *                   |   |-->|   |-->|   |
80  *                   +---+   +---+   +---+
81  *                     ^               |
82  *                     |               |
83  *                     +---------------+
84  *
85  *
86  *   +------+
87  *   |reader|          RING BUFFER
88  *   |page  |------------------v
89  *   +------+        +---+   +---+   +---+
90  *      ^            |   |-->|   |-->|   |
91  *      |            +---+   +---+   +---+
92  *      |                              |
93  *      |                              |
94  *      +------------------------------+
95  *
96  *
97  *   +------+
98  *   |buffer|          RING BUFFER
99  *   |page  |------------------v
100  *   +------+        +---+   +---+   +---+
101  *      ^            |   |   |   |-->|   |
102  *      |   New      +---+   +---+   +---+
103  *      |  Reader------^               |
104  *      |   page                       |
105  *      +------------------------------+
106  *
107  *
108  * After we make this swap, the reader can hand this page off to the splice
109  * code and be done with it. It can even allocate a new page if it needs to
110  * and swap that into the ring buffer.
111  *
112  * We will be using cmpxchg soon to make all this lockless.
113  *
114  */
115
116 /*
117  * A fast way to enable or disable all ring buffers is to
118  * call tracing_on or tracing_off. Turning off the ring buffers
119  * prevents all ring buffers from being recorded to.
120  * Turning this switch on, makes it OK to write to the
121  * ring buffer, if the ring buffer is enabled itself.
122  *
123  * There's three layers that must be on in order to write
124  * to the ring buffer.
125  *
126  * 1) This global flag must be set.
127  * 2) The ring buffer must be enabled for recording.
128  * 3) The per cpu buffer must be enabled for recording.
129  *
130  * In case of an anomaly, this global flag has a bit set that
131  * will permantly disable all ring buffers.
132  */
133
134 /*
135  * Global flag to disable all recording to ring buffers
136  *  This has two bits: ON, DISABLED
137  *
138  *  ON   DISABLED
139  * ---- ----------
140  *   0      0        : ring buffers are off
141  *   1      0        : ring buffers are on
142  *   X      1        : ring buffers are permanently disabled
143  */
144
145 enum {
146         RB_BUFFERS_ON_BIT       = 0,
147         RB_BUFFERS_DISABLED_BIT = 1,
148 };
149
150 enum {
151         RB_BUFFERS_ON           = 1 << RB_BUFFERS_ON_BIT,
152         RB_BUFFERS_DISABLED     = 1 << RB_BUFFERS_DISABLED_BIT,
153 };
154
155 static unsigned long ring_buffer_flags __read_mostly = RB_BUFFERS_ON;
156
157 /* Used for individual buffers (after the counter) */
158 #define RB_BUFFER_OFF           (1 << 20)
159
160 #define BUF_PAGE_HDR_SIZE offsetof(struct buffer_data_page, data)
161
162 /**
163  * tracing_off_permanent - permanently disable ring buffers
164  *
165  * This function, once called, will disable all ring buffers
166  * permanently.
167  */
168 void tracing_off_permanent(void)
169 {
170         set_bit(RB_BUFFERS_DISABLED_BIT, &ring_buffer_flags);
171 }
172
173 #define RB_EVNT_HDR_SIZE (offsetof(struct ring_buffer_event, array))
174 #define RB_ALIGNMENT            4U
175 #define RB_MAX_SMALL_DATA       (RB_ALIGNMENT * RINGBUF_TYPE_DATA_TYPE_LEN_MAX)
176 #define RB_EVNT_MIN_SIZE        8U      /* two 32bit words */
177
178 #if !defined(CONFIG_64BIT) || defined(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS)
179 # define RB_FORCE_8BYTE_ALIGNMENT       0
180 # define RB_ARCH_ALIGNMENT              RB_ALIGNMENT
181 #else
182 # define RB_FORCE_8BYTE_ALIGNMENT       1
183 # define RB_ARCH_ALIGNMENT              8U
184 #endif
185
186 /* define RINGBUF_TYPE_DATA for 'case RINGBUF_TYPE_DATA:' */
187 #define RINGBUF_TYPE_DATA 0 ... RINGBUF_TYPE_DATA_TYPE_LEN_MAX
188
189 enum {
190         RB_LEN_TIME_EXTEND = 8,
191         RB_LEN_TIME_STAMP = 16,
192 };
193
194 #define skip_time_extend(event) \
195         ((struct ring_buffer_event *)((char *)event + RB_LEN_TIME_EXTEND))
196
197 static inline int rb_null_event(struct ring_buffer_event *event)
198 {
199         return event->type_len == RINGBUF_TYPE_PADDING && !event->time_delta;
200 }
201
202 static void rb_event_set_padding(struct ring_buffer_event *event)
203 {
204         /* padding has a NULL time_delta */
205         event->type_len = RINGBUF_TYPE_PADDING;
206         event->time_delta = 0;
207 }
208
209 static unsigned
210 rb_event_data_length(struct ring_buffer_event *event)
211 {
212         unsigned length;
213
214         if (event->type_len)
215                 length = event->type_len * RB_ALIGNMENT;
216         else
217                 length = event->array[0];
218         return length + RB_EVNT_HDR_SIZE;
219 }
220
221 /*
222  * Return the length of the given event. Will return
223  * the length of the time extend if the event is a
224  * time extend.
225  */
226 static inline unsigned
227 rb_event_length(struct ring_buffer_event *event)
228 {
229         switch (event->type_len) {
230         case RINGBUF_TYPE_PADDING:
231                 if (rb_null_event(event))
232                         /* undefined */
233                         return -1;
234                 return  event->array[0] + RB_EVNT_HDR_SIZE;
235
236         case RINGBUF_TYPE_TIME_EXTEND:
237                 return RB_LEN_TIME_EXTEND;
238
239         case RINGBUF_TYPE_TIME_STAMP:
240                 return RB_LEN_TIME_STAMP;
241
242         case RINGBUF_TYPE_DATA:
243                 return rb_event_data_length(event);
244         default:
245                 BUG();
246         }
247         /* not hit */
248         return 0;
249 }
250
251 /*
252  * Return total length of time extend and data,
253  *   or just the event length for all other events.
254  */
255 static inline unsigned
256 rb_event_ts_length(struct ring_buffer_event *event)
257 {
258         unsigned len = 0;
259
260         if (event->type_len == RINGBUF_TYPE_TIME_EXTEND) {
261                 /* time extends include the data event after it */
262                 len = RB_LEN_TIME_EXTEND;
263                 event = skip_time_extend(event);
264         }
265         return len + rb_event_length(event);
266 }
267
268 /**
269  * ring_buffer_event_length - return the length of the event
270  * @event: the event to get the length of
271  *
272  * Returns the size of the data load of a data event.
273  * If the event is something other than a data event, it
274  * returns the size of the event itself. With the exception
275  * of a TIME EXTEND, where it still returns the size of the
276  * data load of the data event after it.
277  */
278 unsigned ring_buffer_event_length(struct ring_buffer_event *event)
279 {
280         unsigned length;
281
282         if (event->type_len == RINGBUF_TYPE_TIME_EXTEND)
283                 event = skip_time_extend(event);
284
285         length = rb_event_length(event);
286         if (event->type_len > RINGBUF_TYPE_DATA_TYPE_LEN_MAX)
287                 return length;
288         length -= RB_EVNT_HDR_SIZE;
289         if (length > RB_MAX_SMALL_DATA + sizeof(event->array[0]))
290                 length -= sizeof(event->array[0]);
291         return length;
292 }
293 EXPORT_SYMBOL_GPL(ring_buffer_event_length);
294
295 /* inline for ring buffer fast paths */
296 static void *
297 rb_event_data(struct ring_buffer_event *event)
298 {
299         if (event->type_len == RINGBUF_TYPE_TIME_EXTEND)
300                 event = skip_time_extend(event);
301         BUG_ON(event->type_len > RINGBUF_TYPE_DATA_TYPE_LEN_MAX);
302         /* If length is in len field, then array[0] has the data */
303         if (event->type_len)
304                 return (void *)&event->array[0];
305         /* Otherwise length is in array[0] and array[1] has the data */
306         return (void *)&event->array[1];
307 }
308
309 /**
310  * ring_buffer_event_data - return the data of the event
311  * @event: the event to get the data from
312  */
313 void *ring_buffer_event_data(struct ring_buffer_event *event)
314 {
315         return rb_event_data(event);
316 }
317 EXPORT_SYMBOL_GPL(ring_buffer_event_data);
318
319 #define for_each_buffer_cpu(buffer, cpu)                \
320         for_each_cpu(cpu, buffer->cpumask)
321
322 #define TS_SHIFT        27
323 #define TS_MASK         ((1ULL << TS_SHIFT) - 1)
324 #define TS_DELTA_TEST   (~TS_MASK)
325
326 /* Flag when events were overwritten */
327 #define RB_MISSED_EVENTS        (1 << 31)
328 /* Missed count stored at end */
329 #define RB_MISSED_STORED        (1 << 30)
330
331 struct buffer_data_page {
332         u64              time_stamp;    /* page time stamp */
333         local_t          commit;        /* write committed index */
334         unsigned char    data[];        /* data of buffer page */
335 };
336
337 /*
338  * Note, the buffer_page list must be first. The buffer pages
339  * are allocated in cache lines, which means that each buffer
340  * page will be at the beginning of a cache line, and thus
341  * the least significant bits will be zero. We use this to
342  * add flags in the list struct pointers, to make the ring buffer
343  * lockless.
344  */
345 struct buffer_page {
346         struct list_head list;          /* list of buffer pages */
347         local_t          write;         /* index for next write */
348         unsigned         read;          /* index for next read */
349         local_t          entries;       /* entries on this page */
350         unsigned long    real_end;      /* real end of data */
351         struct buffer_data_page *page;  /* Actual data page */
352 };
353
354 /*
355  * The buffer page counters, write and entries, must be reset
356  * atomically when crossing page boundaries. To synchronize this
357  * update, two counters are inserted into the number. One is
358  * the actual counter for the write position or count on the page.
359  *
360  * The other is a counter of updaters. Before an update happens
361  * the update partition of the counter is incremented. This will
362  * allow the updater to update the counter atomically.
363  *
364  * The counter is 20 bits, and the state data is 12.
365  */
366 #define RB_WRITE_MASK           0xfffff
367 #define RB_WRITE_INTCNT         (1 << 20)
368
369 static void rb_init_page(struct buffer_data_page *bpage)
370 {
371         local_set(&bpage->commit, 0);
372 }
373
374 /**
375  * ring_buffer_page_len - the size of data on the page.
376  * @page: The page to read
377  *
378  * Returns the amount of data on the page, including buffer page header.
379  */
380 size_t ring_buffer_page_len(void *page)
381 {
382         return local_read(&((struct buffer_data_page *)page)->commit)
383                 + BUF_PAGE_HDR_SIZE;
384 }
385
386 /*
387  * Also stolen from mm/slob.c. Thanks to Mathieu Desnoyers for pointing
388  * this issue out.
389  */
390 static void free_buffer_page(struct buffer_page *bpage)
391 {
392         free_page((unsigned long)bpage->page);
393         kfree(bpage);
394 }
395
396 /*
397  * We need to fit the time_stamp delta into 27 bits.
398  */
399 static inline int test_time_stamp(u64 delta)
400 {
401         if (delta & TS_DELTA_TEST)
402                 return 1;
403         return 0;
404 }
405
406 #define BUF_PAGE_SIZE (PAGE_SIZE - BUF_PAGE_HDR_SIZE)
407
408 /* Max payload is BUF_PAGE_SIZE - header (8bytes) */
409 #define BUF_MAX_DATA_SIZE (BUF_PAGE_SIZE - (sizeof(u32) * 2))
410
411 int ring_buffer_print_page_header(struct trace_seq *s)
412 {
413         struct buffer_data_page field;
414         int ret;
415
416         ret = trace_seq_printf(s, "\tfield: u64 timestamp;\t"
417                                "offset:0;\tsize:%u;\tsigned:%u;\n",
418                                (unsigned int)sizeof(field.time_stamp),
419                                (unsigned int)is_signed_type(u64));
420
421         ret = trace_seq_printf(s, "\tfield: local_t commit;\t"
422                                "offset:%u;\tsize:%u;\tsigned:%u;\n",
423                                (unsigned int)offsetof(typeof(field), commit),
424                                (unsigned int)sizeof(field.commit),
425                                (unsigned int)is_signed_type(long));
426
427         ret = trace_seq_printf(s, "\tfield: int overwrite;\t"
428                                "offset:%u;\tsize:%u;\tsigned:%u;\n",
429                                (unsigned int)offsetof(typeof(field), commit),
430                                1,
431                                (unsigned int)is_signed_type(long));
432
433         ret = trace_seq_printf(s, "\tfield: char data;\t"
434                                "offset:%u;\tsize:%u;\tsigned:%u;\n",
435                                (unsigned int)offsetof(typeof(field), data),
436                                (unsigned int)BUF_PAGE_SIZE,
437                                (unsigned int)is_signed_type(char));
438
439         return ret;
440 }
441
442 /*
443  * head_page == tail_page && head == tail then buffer is empty.
444  */
445 struct ring_buffer_per_cpu {
446         int                             cpu;
447         atomic_t                        record_disabled;
448         struct ring_buffer              *buffer;
449         raw_spinlock_t                  reader_lock;    /* serialize readers */
450         arch_spinlock_t                 lock;
451         struct lock_class_key           lock_key;
452         unsigned int                    nr_pages;
453         struct list_head                *pages;
454         struct buffer_page              *head_page;     /* read from head */
455         struct buffer_page              *tail_page;     /* write to tail */
456         struct buffer_page              *commit_page;   /* committed pages */
457         struct buffer_page              *reader_page;
458         unsigned long                   lost_events;
459         unsigned long                   last_overrun;
460         local_t                         entries_bytes;
461         local_t                         commit_overrun;
462         local_t                         overrun;
463         local_t                         entries;
464         local_t                         committing;
465         local_t                         commits;
466         unsigned long                   read;
467         unsigned long                   read_bytes;
468         u64                             write_stamp;
469         u64                             read_stamp;
470         /* ring buffer pages to update, > 0 to add, < 0 to remove */
471         int                             nr_pages_to_update;
472         struct list_head                new_pages; /* new pages to add */
473 };
474
475 struct ring_buffer {
476         unsigned                        flags;
477         int                             cpus;
478         atomic_t                        record_disabled;
479         cpumask_var_t                   cpumask;
480
481         struct lock_class_key           *reader_lock_key;
482
483         struct mutex                    mutex;
484
485         struct ring_buffer_per_cpu      **buffers;
486
487 #ifdef CONFIG_HOTPLUG_CPU
488         struct notifier_block           cpu_notify;
489 #endif
490         u64                             (*clock)(void);
491 };
492
493 struct ring_buffer_iter {
494         struct ring_buffer_per_cpu      *cpu_buffer;
495         unsigned long                   head;
496         struct buffer_page              *head_page;
497         struct buffer_page              *cache_reader_page;
498         unsigned long                   cache_read;
499         u64                             read_stamp;
500 };
501
502 /* buffer may be either ring_buffer or ring_buffer_per_cpu */
503 #define RB_WARN_ON(b, cond)                                             \
504         ({                                                              \
505                 int _____ret = unlikely(cond);                          \
506                 if (_____ret) {                                         \
507                         if (__same_type(*(b), struct ring_buffer_per_cpu)) { \
508                                 struct ring_buffer_per_cpu *__b =       \
509                                         (void *)b;                      \
510                                 atomic_inc(&__b->buffer->record_disabled); \
511                         } else                                          \
512                                 atomic_inc(&b->record_disabled);        \
513                         WARN_ON(1);                                     \
514                 }                                                       \
515                 _____ret;                                               \
516         })
517
518 /* Up this if you want to test the TIME_EXTENTS and normalization */
519 #define DEBUG_SHIFT 0
520
521 static inline u64 rb_time_stamp(struct ring_buffer *buffer)
522 {
523         /* shift to debug/test normalization and TIME_EXTENTS */
524         return buffer->clock() << DEBUG_SHIFT;
525 }
526
527 u64 ring_buffer_time_stamp(struct ring_buffer *buffer, int cpu)
528 {
529         u64 time;
530
531         preempt_disable_notrace();
532         time = rb_time_stamp(buffer);
533         preempt_enable_no_resched_notrace();
534
535         return time;
536 }
537 EXPORT_SYMBOL_GPL(ring_buffer_time_stamp);
538
539 void ring_buffer_normalize_time_stamp(struct ring_buffer *buffer,
540                                       int cpu, u64 *ts)
541 {
542         /* Just stupid testing the normalize function and deltas */
543         *ts >>= DEBUG_SHIFT;
544 }
545 EXPORT_SYMBOL_GPL(ring_buffer_normalize_time_stamp);
546
547 /*
548  * Making the ring buffer lockless makes things tricky.
549  * Although writes only happen on the CPU that they are on,
550  * and they only need to worry about interrupts. Reads can
551  * happen on any CPU.
552  *
553  * The reader page is always off the ring buffer, but when the
554  * reader finishes with a page, it needs to swap its page with
555  * a new one from the buffer. The reader needs to take from
556  * the head (writes go to the tail). But if a writer is in overwrite
557  * mode and wraps, it must push the head page forward.
558  *
559  * Here lies the problem.
560  *
561  * The reader must be careful to replace only the head page, and
562  * not another one. As described at the top of the file in the
563  * ASCII art, the reader sets its old page to point to the next
564  * page after head. It then sets the page after head to point to
565  * the old reader page. But if the writer moves the head page
566  * during this operation, the reader could end up with the tail.
567  *
568  * We use cmpxchg to help prevent this race. We also do something
569  * special with the page before head. We set the LSB to 1.
570  *
571  * When the writer must push the page forward, it will clear the
572  * bit that points to the head page, move the head, and then set
573  * the bit that points to the new head page.
574  *
575  * We also don't want an interrupt coming in and moving the head
576  * page on another writer. Thus we use the second LSB to catch
577  * that too. Thus:
578  *
579  * head->list->prev->next        bit 1          bit 0
580  *                              -------        -------
581  * Normal page                     0              0
582  * Points to head page             0              1
583  * New head page                   1              0
584  *
585  * Note we can not trust the prev pointer of the head page, because:
586  *
587  * +----+       +-----+        +-----+
588  * |    |------>|  T  |---X--->|  N  |
589  * |    |<------|     |        |     |
590  * +----+       +-----+        +-----+
591  *   ^                           ^ |
592  *   |          +-----+          | |
593  *   +----------|  R  |----------+ |
594  *              |     |<-----------+
595  *              +-----+
596  *
597  * Key:  ---X-->  HEAD flag set in pointer
598  *         T      Tail page
599  *         R      Reader page
600  *         N      Next page
601  *
602  * (see __rb_reserve_next() to see where this happens)
603  *
604  *  What the above shows is that the reader just swapped out
605  *  the reader page with a page in the buffer, but before it
606  *  could make the new header point back to the new page added
607  *  it was preempted by a writer. The writer moved forward onto
608  *  the new page added by the reader and is about to move forward
609  *  again.
610  *
611  *  You can see, it is legitimate for the previous pointer of
612  *  the head (or any page) not to point back to itself. But only
613  *  temporarially.
614  */
615
616 #define RB_PAGE_NORMAL          0UL
617 #define RB_PAGE_HEAD            1UL
618 #define RB_PAGE_UPDATE          2UL
619
620
621 #define RB_FLAG_MASK            3UL
622
623 /* PAGE_MOVED is not part of the mask */
624 #define RB_PAGE_MOVED           4UL
625
626 /*
627  * rb_list_head - remove any bit
628  */
629 static struct list_head *rb_list_head(struct list_head *list)
630 {
631         unsigned long val = (unsigned long)list;
632
633         return (struct list_head *)(val & ~RB_FLAG_MASK);
634 }
635
636 /*
637  * rb_is_head_page - test if the given page is the head page
638  *
639  * Because the reader may move the head_page pointer, we can
640  * not trust what the head page is (it may be pointing to
641  * the reader page). But if the next page is a header page,
642  * its flags will be non zero.
643  */
644 static inline int
645 rb_is_head_page(struct ring_buffer_per_cpu *cpu_buffer,
646                 struct buffer_page *page, struct list_head *list)
647 {
648         unsigned long val;
649
650         val = (unsigned long)list->next;
651
652         if ((val & ~RB_FLAG_MASK) != (unsigned long)&page->list)
653                 return RB_PAGE_MOVED;
654
655         return val & RB_FLAG_MASK;
656 }
657
658 /*
659  * rb_is_reader_page
660  *
661  * The unique thing about the reader page, is that, if the
662  * writer is ever on it, the previous pointer never points
663  * back to the reader page.
664  */
665 static int rb_is_reader_page(struct buffer_page *page)
666 {
667         struct list_head *list = page->list.prev;
668
669         return rb_list_head(list->next) != &page->list;
670 }
671
672 /*
673  * rb_set_list_to_head - set a list_head to be pointing to head.
674  */
675 static void rb_set_list_to_head(struct ring_buffer_per_cpu *cpu_buffer,
676                                 struct list_head *list)
677 {
678         unsigned long *ptr;
679
680         ptr = (unsigned long *)&list->next;
681         *ptr |= RB_PAGE_HEAD;
682         *ptr &= ~RB_PAGE_UPDATE;
683 }
684
685 /*
686  * rb_head_page_activate - sets up head page
687  */
688 static void rb_head_page_activate(struct ring_buffer_per_cpu *cpu_buffer)
689 {
690         struct buffer_page *head;
691
692         head = cpu_buffer->head_page;
693         if (!head)
694                 return;
695
696         /*
697          * Set the previous list pointer to have the HEAD flag.
698          */
699         rb_set_list_to_head(cpu_buffer, head->list.prev);
700 }
701
702 static void rb_list_head_clear(struct list_head *list)
703 {
704         unsigned long *ptr = (unsigned long *)&list->next;
705
706         *ptr &= ~RB_FLAG_MASK;
707 }
708
709 /*
710  * rb_head_page_dactivate - clears head page ptr (for free list)
711  */
712 static void
713 rb_head_page_deactivate(struct ring_buffer_per_cpu *cpu_buffer)
714 {
715         struct list_head *hd;
716
717         /* Go through the whole list and clear any pointers found. */
718         rb_list_head_clear(cpu_buffer->pages);
719
720         list_for_each(hd, cpu_buffer->pages)
721                 rb_list_head_clear(hd);
722 }
723
724 static int rb_head_page_set(struct ring_buffer_per_cpu *cpu_buffer,
725                             struct buffer_page *head,
726                             struct buffer_page *prev,
727                             int old_flag, int new_flag)
728 {
729         struct list_head *list;
730         unsigned long val = (unsigned long)&head->list;
731         unsigned long ret;
732
733         list = &prev->list;
734
735         val &= ~RB_FLAG_MASK;
736
737         ret = cmpxchg((unsigned long *)&list->next,
738                       val | old_flag, val | new_flag);
739
740         /* check if the reader took the page */
741         if ((ret & ~RB_FLAG_MASK) != val)
742                 return RB_PAGE_MOVED;
743
744         return ret & RB_FLAG_MASK;
745 }
746
747 static int rb_head_page_set_update(struct ring_buffer_per_cpu *cpu_buffer,
748                                    struct buffer_page *head,
749                                    struct buffer_page *prev,
750                                    int old_flag)
751 {
752         return rb_head_page_set(cpu_buffer, head, prev,
753                                 old_flag, RB_PAGE_UPDATE);
754 }
755
756 static int rb_head_page_set_head(struct ring_buffer_per_cpu *cpu_buffer,
757                                  struct buffer_page *head,
758                                  struct buffer_page *prev,
759                                  int old_flag)
760 {
761         return rb_head_page_set(cpu_buffer, head, prev,
762                                 old_flag, RB_PAGE_HEAD);
763 }
764
765 static int rb_head_page_set_normal(struct ring_buffer_per_cpu *cpu_buffer,
766                                    struct buffer_page *head,
767                                    struct buffer_page *prev,
768                                    int old_flag)
769 {
770         return rb_head_page_set(cpu_buffer, head, prev,
771                                 old_flag, RB_PAGE_NORMAL);
772 }
773
774 static inline void rb_inc_page(struct ring_buffer_per_cpu *cpu_buffer,
775                                struct buffer_page **bpage)
776 {
777         struct list_head *p = rb_list_head((*bpage)->list.next);
778
779         *bpage = list_entry(p, struct buffer_page, list);
780 }
781
782 static struct buffer_page *
783 rb_set_head_page(struct ring_buffer_per_cpu *cpu_buffer)
784 {
785         struct buffer_page *head;
786         struct buffer_page *page;
787         struct list_head *list;
788         int i;
789
790         if (RB_WARN_ON(cpu_buffer, !cpu_buffer->head_page))
791                 return NULL;
792
793         /* sanity check */
794         list = cpu_buffer->pages;
795         if (RB_WARN_ON(cpu_buffer, rb_list_head(list->prev->next) != list))
796                 return NULL;
797
798         page = head = cpu_buffer->head_page;
799         /*
800          * It is possible that the writer moves the header behind
801          * where we started, and we miss in one loop.
802          * A second loop should grab the header, but we'll do
803          * three loops just because I'm paranoid.
804          */
805         for (i = 0; i < 3; i++) {
806                 do {
807                         if (rb_is_head_page(cpu_buffer, page, page->list.prev)) {
808                                 cpu_buffer->head_page = page;
809                                 return page;
810                         }
811                         rb_inc_page(cpu_buffer, &page);
812                 } while (page != head);
813         }
814
815         RB_WARN_ON(cpu_buffer, 1);
816
817         return NULL;
818 }
819
820 static int rb_head_page_replace(struct buffer_page *old,
821                                 struct buffer_page *new)
822 {
823         unsigned long *ptr = (unsigned long *)&old->list.prev->next;
824         unsigned long val;
825         unsigned long ret;
826
827         val = *ptr & ~RB_FLAG_MASK;
828         val |= RB_PAGE_HEAD;
829
830         ret = cmpxchg(ptr, val, (unsigned long)&new->list);
831
832         return ret == val;
833 }
834
835 /*
836  * rb_tail_page_update - move the tail page forward
837  *
838  * Returns 1 if moved tail page, 0 if someone else did.
839  */
840 static int rb_tail_page_update(struct ring_buffer_per_cpu *cpu_buffer,
841                                struct buffer_page *tail_page,
842                                struct buffer_page *next_page)
843 {
844         struct buffer_page *old_tail;
845         unsigned long old_entries;
846         unsigned long old_write;
847         int ret = 0;
848
849         /*
850          * The tail page now needs to be moved forward.
851          *
852          * We need to reset the tail page, but without messing
853          * with possible erasing of data brought in by interrupts
854          * that have moved the tail page and are currently on it.
855          *
856          * We add a counter to the write field to denote this.
857          */
858         old_write = local_add_return(RB_WRITE_INTCNT, &next_page->write);
859         old_entries = local_add_return(RB_WRITE_INTCNT, &next_page->entries);
860
861         /*
862          * Just make sure we have seen our old_write and synchronize
863          * with any interrupts that come in.
864          */
865         barrier();
866
867         /*
868          * If the tail page is still the same as what we think
869          * it is, then it is up to us to update the tail
870          * pointer.
871          */
872         if (tail_page == cpu_buffer->tail_page) {
873                 /* Zero the write counter */
874                 unsigned long val = old_write & ~RB_WRITE_MASK;
875                 unsigned long eval = old_entries & ~RB_WRITE_MASK;
876
877                 /*
878                  * This will only succeed if an interrupt did
879                  * not come in and change it. In which case, we
880                  * do not want to modify it.
881                  *
882                  * We add (void) to let the compiler know that we do not care
883                  * about the return value of these functions. We use the
884                  * cmpxchg to only update if an interrupt did not already
885                  * do it for us. If the cmpxchg fails, we don't care.
886                  */
887                 (void)local_cmpxchg(&next_page->write, old_write, val);
888                 (void)local_cmpxchg(&next_page->entries, old_entries, eval);
889
890                 /*
891                  * No need to worry about races with clearing out the commit.
892                  * it only can increment when a commit takes place. But that
893                  * only happens in the outer most nested commit.
894                  */
895                 local_set(&next_page->page->commit, 0);
896
897                 old_tail = cmpxchg(&cpu_buffer->tail_page,
898                                    tail_page, next_page);
899
900                 if (old_tail == tail_page)
901                         ret = 1;
902         }
903
904         return ret;
905 }
906
907 static int rb_check_bpage(struct ring_buffer_per_cpu *cpu_buffer,
908                           struct buffer_page *bpage)
909 {
910         unsigned long val = (unsigned long)bpage;
911
912         if (RB_WARN_ON(cpu_buffer, val & RB_FLAG_MASK))
913                 return 1;
914
915         return 0;
916 }
917
918 /**
919  * rb_check_list - make sure a pointer to a list has the last bits zero
920  */
921 static int rb_check_list(struct ring_buffer_per_cpu *cpu_buffer,
922                          struct list_head *list)
923 {
924         if (RB_WARN_ON(cpu_buffer, rb_list_head(list->prev) != list->prev))
925                 return 1;
926         if (RB_WARN_ON(cpu_buffer, rb_list_head(list->next) != list->next))
927                 return 1;
928         return 0;
929 }
930
931 /**
932  * check_pages - integrity check of buffer pages
933  * @cpu_buffer: CPU buffer with pages to test
934  *
935  * As a safety measure we check to make sure the data pages have not
936  * been corrupted.
937  */
938 static int rb_check_pages(struct ring_buffer_per_cpu *cpu_buffer)
939 {
940         struct list_head *head = cpu_buffer->pages;
941         struct buffer_page *bpage, *tmp;
942
943         rb_head_page_deactivate(cpu_buffer);
944
945         if (RB_WARN_ON(cpu_buffer, head->next->prev != head))
946                 return -1;
947         if (RB_WARN_ON(cpu_buffer, head->prev->next != head))
948                 return -1;
949
950         if (rb_check_list(cpu_buffer, head))
951                 return -1;
952
953         list_for_each_entry_safe(bpage, tmp, head, list) {
954                 if (RB_WARN_ON(cpu_buffer,
955                                bpage->list.next->prev != &bpage->list))
956                         return -1;
957                 if (RB_WARN_ON(cpu_buffer,
958                                bpage->list.prev->next != &bpage->list))
959                         return -1;
960                 if (rb_check_list(cpu_buffer, &bpage->list))
961                         return -1;
962         }
963
964         rb_head_page_activate(cpu_buffer);
965
966         return 0;
967 }
968
969 static int __rb_allocate_pages(int nr_pages, struct list_head *pages, int cpu)
970 {
971         int i;
972         struct buffer_page *bpage, *tmp;
973
974         for (i = 0; i < nr_pages; i++) {
975                 struct page *page;
976                 /*
977                  * __GFP_NORETRY flag makes sure that the allocation fails
978                  * gracefully without invoking oom-killer and the system is
979                  * not destabilized.
980                  */
981                 bpage = kzalloc_node(ALIGN(sizeof(*bpage), cache_line_size()),
982                                     GFP_KERNEL | __GFP_NORETRY,
983                                     cpu_to_node(cpu));
984                 if (!bpage)
985                         goto free_pages;
986
987                 list_add(&bpage->list, pages);
988
989                 page = alloc_pages_node(cpu_to_node(cpu),
990                                         GFP_KERNEL | __GFP_NORETRY, 0);
991                 if (!page)
992                         goto free_pages;
993                 bpage->page = page_address(page);
994                 rb_init_page(bpage->page);
995         }
996
997         return 0;
998
999 free_pages:
1000         list_for_each_entry_safe(bpage, tmp, pages, list) {
1001                 list_del_init(&bpage->list);
1002                 free_buffer_page(bpage);
1003         }
1004
1005         return -ENOMEM;
1006 }
1007
1008 static int rb_allocate_pages(struct ring_buffer_per_cpu *cpu_buffer,
1009                              unsigned nr_pages)
1010 {
1011         LIST_HEAD(pages);
1012
1013         WARN_ON(!nr_pages);
1014
1015         if (__rb_allocate_pages(nr_pages, &pages, cpu_buffer->cpu))
1016                 return -ENOMEM;
1017
1018         /*
1019          * The ring buffer page list is a circular list that does not
1020          * start and end with a list head. All page list items point to
1021          * other pages.
1022          */
1023         cpu_buffer->pages = pages.next;
1024         list_del(&pages);
1025
1026         cpu_buffer->nr_pages = nr_pages;
1027
1028         rb_check_pages(cpu_buffer);
1029
1030         return 0;
1031 }
1032
1033 static struct ring_buffer_per_cpu *
1034 rb_allocate_cpu_buffer(struct ring_buffer *buffer, int nr_pages, int cpu)
1035 {
1036         struct ring_buffer_per_cpu *cpu_buffer;
1037         struct buffer_page *bpage;
1038         struct page *page;
1039         int ret;
1040
1041         cpu_buffer = kzalloc_node(ALIGN(sizeof(*cpu_buffer), cache_line_size()),
1042                                   GFP_KERNEL, cpu_to_node(cpu));
1043         if (!cpu_buffer)
1044                 return NULL;
1045
1046         cpu_buffer->cpu = cpu;
1047         cpu_buffer->buffer = buffer;
1048         raw_spin_lock_init(&cpu_buffer->reader_lock);
1049         lockdep_set_class(&cpu_buffer->reader_lock, buffer->reader_lock_key);
1050         cpu_buffer->lock = (arch_spinlock_t)__ARCH_SPIN_LOCK_UNLOCKED;
1051
1052         bpage = kzalloc_node(ALIGN(sizeof(*bpage), cache_line_size()),
1053                             GFP_KERNEL, cpu_to_node(cpu));
1054         if (!bpage)
1055                 goto fail_free_buffer;
1056
1057         rb_check_bpage(cpu_buffer, bpage);
1058
1059         cpu_buffer->reader_page = bpage;
1060         page = alloc_pages_node(cpu_to_node(cpu), GFP_KERNEL, 0);
1061         if (!page)
1062                 goto fail_free_reader;
1063         bpage->page = page_address(page);
1064         rb_init_page(bpage->page);
1065
1066         INIT_LIST_HEAD(&cpu_buffer->reader_page->list);
1067
1068         ret = rb_allocate_pages(cpu_buffer, nr_pages);
1069         if (ret < 0)
1070                 goto fail_free_reader;
1071
1072         cpu_buffer->head_page
1073                 = list_entry(cpu_buffer->pages, struct buffer_page, list);
1074         cpu_buffer->tail_page = cpu_buffer->commit_page = cpu_buffer->head_page;
1075
1076         rb_head_page_activate(cpu_buffer);
1077
1078         return cpu_buffer;
1079
1080  fail_free_reader:
1081         free_buffer_page(cpu_buffer->reader_page);
1082
1083  fail_free_buffer:
1084         kfree(cpu_buffer);
1085         return NULL;
1086 }
1087
1088 static void rb_free_cpu_buffer(struct ring_buffer_per_cpu *cpu_buffer)
1089 {
1090         struct list_head *head = cpu_buffer->pages;
1091         struct buffer_page *bpage, *tmp;
1092
1093         free_buffer_page(cpu_buffer->reader_page);
1094
1095         rb_head_page_deactivate(cpu_buffer);
1096
1097         if (head) {
1098                 list_for_each_entry_safe(bpage, tmp, head, list) {
1099                         list_del_init(&bpage->list);
1100                         free_buffer_page(bpage);
1101                 }
1102                 bpage = list_entry(head, struct buffer_page, list);
1103                 free_buffer_page(bpage);
1104         }
1105
1106         kfree(cpu_buffer);
1107 }
1108
1109 #ifdef CONFIG_HOTPLUG_CPU
1110 static int rb_cpu_notify(struct notifier_block *self,
1111                          unsigned long action, void *hcpu);
1112 #endif
1113
1114 /**
1115  * ring_buffer_alloc - allocate a new ring_buffer
1116  * @size: the size in bytes per cpu that is needed.
1117  * @flags: attributes to set for the ring buffer.
1118  *
1119  * Currently the only flag that is available is the RB_FL_OVERWRITE
1120  * flag. This flag means that the buffer will overwrite old data
1121  * when the buffer wraps. If this flag is not set, the buffer will
1122  * drop data when the tail hits the head.
1123  */
1124 struct ring_buffer *__ring_buffer_alloc(unsigned long size, unsigned flags,
1125                                         struct lock_class_key *key)
1126 {
1127         struct ring_buffer *buffer;
1128         int bsize;
1129         int cpu, nr_pages;
1130
1131         /* keep it in its own cache line */
1132         buffer = kzalloc(ALIGN(sizeof(*buffer), cache_line_size()),
1133                          GFP_KERNEL);
1134         if (!buffer)
1135                 return NULL;
1136
1137         if (!alloc_cpumask_var(&buffer->cpumask, GFP_KERNEL))
1138                 goto fail_free_buffer;
1139
1140         nr_pages = DIV_ROUND_UP(size, BUF_PAGE_SIZE);
1141         buffer->flags = flags;
1142         buffer->clock = trace_clock_local;
1143         buffer->reader_lock_key = key;
1144
1145         /* need at least two pages */
1146         if (nr_pages < 2)
1147                 nr_pages = 2;
1148
1149         /*
1150          * In case of non-hotplug cpu, if the ring-buffer is allocated
1151          * in early initcall, it will not be notified of secondary cpus.
1152          * In that off case, we need to allocate for all possible cpus.
1153          */
1154 #ifdef CONFIG_HOTPLUG_CPU
1155         get_online_cpus();
1156         cpumask_copy(buffer->cpumask, cpu_online_mask);
1157 #else
1158         cpumask_copy(buffer->cpumask, cpu_possible_mask);
1159 #endif
1160         buffer->cpus = nr_cpu_ids;
1161
1162         bsize = sizeof(void *) * nr_cpu_ids;
1163         buffer->buffers = kzalloc(ALIGN(bsize, cache_line_size()),
1164                                   GFP_KERNEL);
1165         if (!buffer->buffers)
1166                 goto fail_free_cpumask;
1167
1168         for_each_buffer_cpu(buffer, cpu) {
1169                 buffer->buffers[cpu] =
1170                         rb_allocate_cpu_buffer(buffer, nr_pages, cpu);
1171                 if (!buffer->buffers[cpu])
1172                         goto fail_free_buffers;
1173         }
1174
1175 #ifdef CONFIG_HOTPLUG_CPU
1176         buffer->cpu_notify.notifier_call = rb_cpu_notify;
1177         buffer->cpu_notify.priority = 0;
1178         register_cpu_notifier(&buffer->cpu_notify);
1179 #endif
1180
1181         put_online_cpus();
1182         mutex_init(&buffer->mutex);
1183
1184         return buffer;
1185
1186  fail_free_buffers:
1187         for_each_buffer_cpu(buffer, cpu) {
1188                 if (buffer->buffers[cpu])
1189                         rb_free_cpu_buffer(buffer->buffers[cpu]);
1190         }
1191         kfree(buffer->buffers);
1192
1193  fail_free_cpumask:
1194         free_cpumask_var(buffer->cpumask);
1195         put_online_cpus();
1196
1197  fail_free_buffer:
1198         kfree(buffer);
1199         return NULL;
1200 }
1201 EXPORT_SYMBOL_GPL(__ring_buffer_alloc);
1202
1203 /**
1204  * ring_buffer_free - free a ring buffer.
1205  * @buffer: the buffer to free.
1206  */
1207 void
1208 ring_buffer_free(struct ring_buffer *buffer)
1209 {
1210         int cpu;
1211
1212         get_online_cpus();
1213
1214 #ifdef CONFIG_HOTPLUG_CPU
1215         unregister_cpu_notifier(&buffer->cpu_notify);
1216 #endif
1217
1218         for_each_buffer_cpu(buffer, cpu)
1219                 rb_free_cpu_buffer(buffer->buffers[cpu]);
1220
1221         put_online_cpus();
1222
1223         kfree(buffer->buffers);
1224         free_cpumask_var(buffer->cpumask);
1225
1226         kfree(buffer);
1227 }
1228 EXPORT_SYMBOL_GPL(ring_buffer_free);
1229
1230 void ring_buffer_set_clock(struct ring_buffer *buffer,
1231                            u64 (*clock)(void))
1232 {
1233         buffer->clock = clock;
1234 }
1235
1236 static void rb_reset_cpu(struct ring_buffer_per_cpu *cpu_buffer);
1237
1238 static void
1239 rb_remove_pages(struct ring_buffer_per_cpu *cpu_buffer, unsigned nr_pages)
1240 {
1241         struct buffer_page *bpage;
1242         struct list_head *p;
1243         unsigned i;
1244
1245         raw_spin_lock_irq(&cpu_buffer->reader_lock);
1246         rb_head_page_deactivate(cpu_buffer);
1247
1248         for (i = 0; i < nr_pages; i++) {
1249                 if (RB_WARN_ON(cpu_buffer, list_empty(cpu_buffer->pages)))
1250                         goto out;
1251                 p = cpu_buffer->pages->next;
1252                 bpage = list_entry(p, struct buffer_page, list);
1253                 list_del_init(&bpage->list);
1254                 free_buffer_page(bpage);
1255         }
1256         if (RB_WARN_ON(cpu_buffer, list_empty(cpu_buffer->pages)))
1257                 goto out;
1258
1259         rb_reset_cpu(cpu_buffer);
1260         rb_check_pages(cpu_buffer);
1261
1262 out:
1263         raw_spin_unlock_irq(&cpu_buffer->reader_lock);
1264 }
1265
1266 static void
1267 rb_insert_pages(struct ring_buffer_per_cpu *cpu_buffer,
1268                 struct list_head *pages, unsigned nr_pages)
1269 {
1270         struct buffer_page *bpage;
1271         struct list_head *p;
1272         unsigned i;
1273
1274         raw_spin_lock_irq(&cpu_buffer->reader_lock);
1275         rb_head_page_deactivate(cpu_buffer);
1276
1277         for (i = 0; i < nr_pages; i++) {
1278                 if (RB_WARN_ON(cpu_buffer, list_empty(pages)))
1279                         goto out;
1280                 p = pages->next;
1281                 bpage = list_entry(p, struct buffer_page, list);
1282                 list_del_init(&bpage->list);
1283                 list_add_tail(&bpage->list, cpu_buffer->pages);
1284         }
1285         rb_reset_cpu(cpu_buffer);
1286         rb_check_pages(cpu_buffer);
1287
1288 out:
1289         raw_spin_unlock_irq(&cpu_buffer->reader_lock);
1290 }
1291
1292 static void update_pages_handler(struct ring_buffer_per_cpu *cpu_buffer)
1293 {
1294         if (cpu_buffer->nr_pages_to_update > 0)
1295                 rb_insert_pages(cpu_buffer, &cpu_buffer->new_pages,
1296                                 cpu_buffer->nr_pages_to_update);
1297         else
1298                 rb_remove_pages(cpu_buffer, -cpu_buffer->nr_pages_to_update);
1299         cpu_buffer->nr_pages += cpu_buffer->nr_pages_to_update;
1300         /* reset this value */
1301         cpu_buffer->nr_pages_to_update = 0;
1302 }
1303
1304 /**
1305  * ring_buffer_resize - resize the ring buffer
1306  * @buffer: the buffer to resize.
1307  * @size: the new size.
1308  *
1309  * Minimum size is 2 * BUF_PAGE_SIZE.
1310  *
1311  * Returns -1 on failure.
1312  */
1313 int ring_buffer_resize(struct ring_buffer *buffer, unsigned long size,
1314                         int cpu_id)
1315 {
1316         struct ring_buffer_per_cpu *cpu_buffer;
1317         unsigned nr_pages;
1318         int cpu;
1319
1320         /*
1321          * Always succeed at resizing a non-existent buffer:
1322          */
1323         if (!buffer)
1324                 return size;
1325
1326         size = DIV_ROUND_UP(size, BUF_PAGE_SIZE);
1327         size *= BUF_PAGE_SIZE;
1328
1329         /* we need a minimum of two pages */
1330         if (size < BUF_PAGE_SIZE * 2)
1331                 size = BUF_PAGE_SIZE * 2;
1332
1333         atomic_inc(&buffer->record_disabled);
1334
1335         /* Make sure all writers are done with this buffer. */
1336         synchronize_sched();
1337
1338         mutex_lock(&buffer->mutex);
1339         get_online_cpus();
1340
1341         nr_pages = DIV_ROUND_UP(size, BUF_PAGE_SIZE);
1342
1343         if (cpu_id == RING_BUFFER_ALL_CPUS) {
1344                 /* calculate the pages to update */
1345                 for_each_buffer_cpu(buffer, cpu) {
1346                         cpu_buffer = buffer->buffers[cpu];
1347
1348                         cpu_buffer->nr_pages_to_update = nr_pages -
1349                                                         cpu_buffer->nr_pages;
1350
1351                         /*
1352                          * nothing more to do for removing pages or no update
1353                          */
1354                         if (cpu_buffer->nr_pages_to_update <= 0)
1355                                 continue;
1356
1357                         /*
1358                          * to add pages, make sure all new pages can be
1359                          * allocated without receiving ENOMEM
1360                          */
1361                         INIT_LIST_HEAD(&cpu_buffer->new_pages);
1362                         if (__rb_allocate_pages(cpu_buffer->nr_pages_to_update,
1363                                                 &cpu_buffer->new_pages, cpu))
1364                                 /* not enough memory for new pages */
1365                                 goto no_mem;
1366                 }
1367
1368                 /* wait for all the updates to complete */
1369                 for_each_buffer_cpu(buffer, cpu) {
1370                         cpu_buffer = buffer->buffers[cpu];
1371                         if (cpu_buffer->nr_pages_to_update) {
1372                                 update_pages_handler(cpu_buffer);
1373                         }
1374                 }
1375         } else {
1376                 cpu_buffer = buffer->buffers[cpu_id];
1377                 if (nr_pages == cpu_buffer->nr_pages)
1378                         goto out;
1379
1380                 cpu_buffer->nr_pages_to_update = nr_pages -
1381                                                 cpu_buffer->nr_pages;
1382
1383                 INIT_LIST_HEAD(&cpu_buffer->new_pages);
1384                 if (cpu_buffer->nr_pages_to_update > 0 &&
1385                         __rb_allocate_pages(cpu_buffer->nr_pages_to_update,
1386                                                 &cpu_buffer->new_pages, cpu_id))
1387                         goto no_mem;
1388
1389                 update_pages_handler(cpu_buffer);
1390         }
1391
1392  out:
1393         put_online_cpus();
1394         mutex_unlock(&buffer->mutex);
1395
1396         atomic_dec(&buffer->record_disabled);
1397
1398         return size;
1399
1400  no_mem:
1401         for_each_buffer_cpu(buffer, cpu) {
1402                 struct buffer_page *bpage, *tmp;
1403                 cpu_buffer = buffer->buffers[cpu];
1404                 /* reset this number regardless */
1405                 cpu_buffer->nr_pages_to_update = 0;
1406                 if (list_empty(&cpu_buffer->new_pages))
1407                         continue;
1408                 list_for_each_entry_safe(bpage, tmp, &cpu_buffer->new_pages,
1409                                         list) {
1410                         list_del_init(&bpage->list);
1411                         free_buffer_page(bpage);
1412                 }
1413         }
1414         put_online_cpus();
1415         mutex_unlock(&buffer->mutex);
1416         atomic_dec(&buffer->record_disabled);
1417         return -ENOMEM;
1418 }
1419 EXPORT_SYMBOL_GPL(ring_buffer_resize);
1420
1421 void ring_buffer_change_overwrite(struct ring_buffer *buffer, int val)
1422 {
1423         mutex_lock(&buffer->mutex);
1424         if (val)
1425                 buffer->flags |= RB_FL_OVERWRITE;
1426         else
1427                 buffer->flags &= ~RB_FL_OVERWRITE;
1428         mutex_unlock(&buffer->mutex);
1429 }
1430 EXPORT_SYMBOL_GPL(ring_buffer_change_overwrite);
1431
1432 static inline void *
1433 __rb_data_page_index(struct buffer_data_page *bpage, unsigned index)
1434 {
1435         return bpage->data + index;
1436 }
1437
1438 static inline void *__rb_page_index(struct buffer_page *bpage, unsigned index)
1439 {
1440         return bpage->page->data + index;
1441 }
1442
1443 static inline struct ring_buffer_event *
1444 rb_reader_event(struct ring_buffer_per_cpu *cpu_buffer)
1445 {
1446         return __rb_page_index(cpu_buffer->reader_page,
1447                                cpu_buffer->reader_page->read);
1448 }
1449
1450 static inline struct ring_buffer_event *
1451 rb_iter_head_event(struct ring_buffer_iter *iter)
1452 {
1453         return __rb_page_index(iter->head_page, iter->head);
1454 }
1455
1456 static inline unsigned long rb_page_write(struct buffer_page *bpage)
1457 {
1458         return local_read(&bpage->write) & RB_WRITE_MASK;
1459 }
1460
1461 static inline unsigned rb_page_commit(struct buffer_page *bpage)
1462 {
1463         return local_read(&bpage->page->commit);
1464 }
1465
1466 static inline unsigned long rb_page_entries(struct buffer_page *bpage)
1467 {
1468         return local_read(&bpage->entries) & RB_WRITE_MASK;
1469 }
1470
1471 /* Size is determined by what has been committed */
1472 static inline unsigned rb_page_size(struct buffer_page *bpage)
1473 {
1474         return rb_page_commit(bpage);
1475 }
1476
1477 static inline unsigned
1478 rb_commit_index(struct ring_buffer_per_cpu *cpu_buffer)
1479 {
1480         return rb_page_commit(cpu_buffer->commit_page);
1481 }
1482
1483 static inline unsigned
1484 rb_event_index(struct ring_buffer_event *event)
1485 {
1486         unsigned long addr = (unsigned long)event;
1487
1488         return (addr & ~PAGE_MASK) - BUF_PAGE_HDR_SIZE;
1489 }
1490
1491 static inline int
1492 rb_event_is_commit(struct ring_buffer_per_cpu *cpu_buffer,
1493                    struct ring_buffer_event *event)
1494 {
1495         unsigned long addr = (unsigned long)event;
1496         unsigned long index;
1497
1498         index = rb_event_index(event);
1499         addr &= PAGE_MASK;
1500
1501         return cpu_buffer->commit_page->page == (void *)addr &&
1502                 rb_commit_index(cpu_buffer) == index;
1503 }
1504
1505 static void
1506 rb_set_commit_to_write(struct ring_buffer_per_cpu *cpu_buffer)
1507 {
1508         unsigned long max_count;
1509
1510         /*
1511          * We only race with interrupts and NMIs on this CPU.
1512          * If we own the commit event, then we can commit
1513          * all others that interrupted us, since the interruptions
1514          * are in stack format (they finish before they come
1515          * back to us). This allows us to do a simple loop to
1516          * assign the commit to the tail.
1517          */
1518  again:
1519         max_count = cpu_buffer->nr_pages * 100;
1520
1521         while (cpu_buffer->commit_page != cpu_buffer->tail_page) {
1522                 if (RB_WARN_ON(cpu_buffer, !(--max_count)))
1523                         return;
1524                 if (RB_WARN_ON(cpu_buffer,
1525                                rb_is_reader_page(cpu_buffer->tail_page)))
1526                         return;
1527                 local_set(&cpu_buffer->commit_page->page->commit,
1528                           rb_page_write(cpu_buffer->commit_page));
1529                 rb_inc_page(cpu_buffer, &cpu_buffer->commit_page);
1530                 cpu_buffer->write_stamp =
1531                         cpu_buffer->commit_page->page->time_stamp;
1532                 /* add barrier to keep gcc from optimizing too much */
1533                 barrier();
1534         }
1535         while (rb_commit_index(cpu_buffer) !=
1536                rb_page_write(cpu_buffer->commit_page)) {
1537
1538                 local_set(&cpu_buffer->commit_page->page->commit,
1539                           rb_page_write(cpu_buffer->commit_page));
1540                 RB_WARN_ON(cpu_buffer,
1541                            local_read(&cpu_buffer->commit_page->page->commit) &
1542                            ~RB_WRITE_MASK);
1543                 barrier();
1544         }
1545
1546         /* again, keep gcc from optimizing */
1547         barrier();
1548
1549         /*
1550          * If an interrupt came in just after the first while loop
1551          * and pushed the tail page forward, we will be left with
1552          * a dangling commit that will never go forward.
1553          */
1554         if (unlikely(cpu_buffer->commit_page != cpu_buffer->tail_page))
1555                 goto again;
1556 }
1557
1558 static void rb_reset_reader_page(struct ring_buffer_per_cpu *cpu_buffer)
1559 {
1560         cpu_buffer->read_stamp = cpu_buffer->reader_page->page->time_stamp;
1561         cpu_buffer->reader_page->read = 0;
1562 }
1563
1564 static void rb_inc_iter(struct ring_buffer_iter *iter)
1565 {
1566         struct ring_buffer_per_cpu *cpu_buffer = iter->cpu_buffer;
1567
1568         /*
1569          * The iterator could be on the reader page (it starts there).
1570          * But the head could have moved, since the reader was
1571          * found. Check for this case and assign the iterator
1572          * to the head page instead of next.
1573          */
1574         if (iter->head_page == cpu_buffer->reader_page)
1575                 iter->head_page = rb_set_head_page(cpu_buffer);
1576         else
1577                 rb_inc_page(cpu_buffer, &iter->head_page);
1578
1579         iter->read_stamp = iter->head_page->page->time_stamp;
1580         iter->head = 0;
1581 }
1582
1583 /* Slow path, do not inline */
1584 static noinline struct ring_buffer_event *
1585 rb_add_time_stamp(struct ring_buffer_event *event, u64 delta)
1586 {
1587         event->type_len = RINGBUF_TYPE_TIME_EXTEND;
1588
1589         /* Not the first event on the page? */
1590         if (rb_event_index(event)) {
1591                 event->time_delta = delta & TS_MASK;
1592                 event->array[0] = delta >> TS_SHIFT;
1593         } else {
1594                 /* nope, just zero it */
1595                 event->time_delta = 0;
1596                 event->array[0] = 0;
1597         }
1598
1599         return skip_time_extend(event);
1600 }
1601
1602 /**
1603  * ring_buffer_update_event - update event type and data
1604  * @event: the even to update
1605  * @type: the type of event
1606  * @length: the size of the event field in the ring buffer
1607  *
1608  * Update the type and data fields of the event. The length
1609  * is the actual size that is written to the ring buffer,
1610  * and with this, we can determine what to place into the
1611  * data field.
1612  */
1613 static void
1614 rb_update_event(struct ring_buffer_per_cpu *cpu_buffer,
1615                 struct ring_buffer_event *event, unsigned length,
1616                 int add_timestamp, u64 delta)
1617 {
1618         /* Only a commit updates the timestamp */
1619         if (unlikely(!rb_event_is_commit(cpu_buffer, event)))
1620                 delta = 0;
1621
1622         /*
1623          * If we need to add a timestamp, then we
1624          * add it to the start of the resevered space.
1625          */
1626         if (unlikely(add_timestamp)) {
1627                 event = rb_add_time_stamp(event, delta);
1628                 length -= RB_LEN_TIME_EXTEND;
1629                 delta = 0;
1630         }
1631
1632         event->time_delta = delta;
1633         length -= RB_EVNT_HDR_SIZE;
1634         if (length > RB_MAX_SMALL_DATA || RB_FORCE_8BYTE_ALIGNMENT) {
1635                 event->type_len = 0;
1636                 event->array[0] = length;
1637         } else
1638                 event->type_len = DIV_ROUND_UP(length, RB_ALIGNMENT);
1639 }
1640
1641 /*
1642  * rb_handle_head_page - writer hit the head page
1643  *
1644  * Returns: +1 to retry page
1645  *           0 to continue
1646  *          -1 on error
1647  */
1648 static int
1649 rb_handle_head_page(struct ring_buffer_per_cpu *cpu_buffer,
1650                     struct buffer_page *tail_page,
1651                     struct buffer_page *next_page)
1652 {
1653         struct buffer_page *new_head;
1654         int entries;
1655         int type;
1656         int ret;
1657
1658         entries = rb_page_entries(next_page);
1659
1660         /*
1661          * The hard part is here. We need to move the head
1662          * forward, and protect against both readers on
1663          * other CPUs and writers coming in via interrupts.
1664          */
1665         type = rb_head_page_set_update(cpu_buffer, next_page, tail_page,
1666                                        RB_PAGE_HEAD);
1667
1668         /*
1669          * type can be one of four:
1670          *  NORMAL - an interrupt already moved it for us
1671          *  HEAD   - we are the first to get here.
1672          *  UPDATE - we are the interrupt interrupting
1673          *           a current move.
1674          *  MOVED  - a reader on another CPU moved the next
1675          *           pointer to its reader page. Give up
1676          *           and try again.
1677          */
1678
1679         switch (type) {
1680         case RB_PAGE_HEAD:
1681                 /*
1682                  * We changed the head to UPDATE, thus
1683                  * it is our responsibility to update
1684                  * the counters.
1685                  */
1686                 local_add(entries, &cpu_buffer->overrun);
1687                 local_sub(BUF_PAGE_SIZE, &cpu_buffer->entries_bytes);
1688
1689                 /*
1690                  * The entries will be zeroed out when we move the
1691                  * tail page.
1692                  */
1693
1694                 /* still more to do */
1695                 break;
1696
1697         case RB_PAGE_UPDATE:
1698                 /*
1699                  * This is an interrupt that interrupt the
1700                  * previous update. Still more to do.
1701                  */
1702                 break;
1703         case RB_PAGE_NORMAL:
1704                 /*
1705                  * An interrupt came in before the update
1706                  * and processed this for us.
1707                  * Nothing left to do.
1708                  */
1709                 return 1;
1710         case RB_PAGE_MOVED:
1711                 /*
1712                  * The reader is on another CPU and just did
1713                  * a swap with our next_page.
1714                  * Try again.
1715                  */
1716                 return 1;
1717         default:
1718                 RB_WARN_ON(cpu_buffer, 1); /* WTF??? */
1719                 return -1;
1720         }
1721
1722         /*
1723          * Now that we are here, the old head pointer is
1724          * set to UPDATE. This will keep the reader from
1725          * swapping the head page with the reader page.
1726          * The reader (on another CPU) will spin till
1727          * we are finished.
1728          *
1729          * We just need to protect against interrupts
1730          * doing the job. We will set the next pointer
1731          * to HEAD. After that, we set the old pointer
1732          * to NORMAL, but only if it was HEAD before.
1733          * otherwise we are an interrupt, and only
1734          * want the outer most commit to reset it.
1735          */
1736         new_head = next_page;
1737         rb_inc_page(cpu_buffer, &new_head);
1738
1739         ret = rb_head_page_set_head(cpu_buffer, new_head, next_page,
1740                                     RB_PAGE_NORMAL);
1741
1742         /*
1743          * Valid returns are:
1744          *  HEAD   - an interrupt came in and already set it.
1745          *  NORMAL - One of two things:
1746          *            1) We really set it.
1747          *            2) A bunch of interrupts came in and moved
1748          *               the page forward again.
1749          */
1750         switch (ret) {
1751         case RB_PAGE_HEAD:
1752         case RB_PAGE_NORMAL:
1753                 /* OK */
1754                 break;
1755         default:
1756                 RB_WARN_ON(cpu_buffer, 1);
1757                 return -1;
1758         }
1759
1760         /*
1761          * It is possible that an interrupt came in,
1762          * set the head up, then more interrupts came in
1763          * and moved it again. When we get back here,
1764          * the page would have been set to NORMAL but we
1765          * just set it back to HEAD.
1766          *
1767          * How do you detect this? Well, if that happened
1768          * the tail page would have moved.
1769          */
1770         if (ret == RB_PAGE_NORMAL) {
1771                 /*
1772                  * If the tail had moved passed next, then we need
1773                  * to reset the pointer.
1774                  */
1775                 if (cpu_buffer->tail_page != tail_page &&
1776                     cpu_buffer->tail_page != next_page)
1777                         rb_head_page_set_normal(cpu_buffer, new_head,
1778                                                 next_page,
1779                                                 RB_PAGE_HEAD);
1780         }
1781
1782         /*
1783          * If this was the outer most commit (the one that
1784          * changed the original pointer from HEAD to UPDATE),
1785          * then it is up to us to reset it to NORMAL.
1786          */
1787         if (type == RB_PAGE_HEAD) {
1788                 ret = rb_head_page_set_normal(cpu_buffer, next_page,
1789                                               tail_page,
1790                                               RB_PAGE_UPDATE);
1791                 if (RB_WARN_ON(cpu_buffer,
1792                                ret != RB_PAGE_UPDATE))
1793                         return -1;
1794         }
1795
1796         return 0;
1797 }
1798
1799 static unsigned rb_calculate_event_length(unsigned length)
1800 {
1801         struct ring_buffer_event event; /* Used only for sizeof array */
1802
1803         /* zero length can cause confusions */
1804         if (!length)
1805                 length = 1;
1806
1807         if (length > RB_MAX_SMALL_DATA || RB_FORCE_8BYTE_ALIGNMENT)
1808                 length += sizeof(event.array[0]);
1809
1810         length += RB_EVNT_HDR_SIZE;
1811         length = ALIGN(length, RB_ARCH_ALIGNMENT);
1812
1813         return length;
1814 }
1815
1816 static inline void
1817 rb_reset_tail(struct ring_buffer_per_cpu *cpu_buffer,
1818               struct buffer_page *tail_page,
1819               unsigned long tail, unsigned long length)
1820 {
1821         struct ring_buffer_event *event;
1822
1823         /*
1824          * Only the event that crossed the page boundary
1825          * must fill the old tail_page with padding.
1826          */
1827         if (tail >= BUF_PAGE_SIZE) {
1828                 /*
1829                  * If the page was filled, then we still need
1830                  * to update the real_end. Reset it to zero
1831                  * and the reader will ignore it.
1832                  */
1833                 if (tail == BUF_PAGE_SIZE)
1834                         tail_page->real_end = 0;
1835
1836                 local_sub(length, &tail_page->write);
1837                 return;
1838         }
1839
1840         event = __rb_page_index(tail_page, tail);
1841         kmemcheck_annotate_bitfield(event, bitfield);
1842
1843         /* account for padding bytes */
1844         local_add(BUF_PAGE_SIZE - tail, &cpu_buffer->entries_bytes);
1845
1846         /*
1847          * Save the original length to the meta data.
1848          * This will be used by the reader to add lost event
1849          * counter.
1850          */
1851         tail_page->real_end = tail;
1852
1853         /*
1854          * If this event is bigger than the minimum size, then
1855          * we need to be careful that we don't subtract the
1856          * write counter enough to allow another writer to slip
1857          * in on this page.
1858          * We put in a discarded commit instead, to make sure
1859          * that this space is not used again.
1860          *
1861          * If we are less than the minimum size, we don't need to
1862          * worry about it.
1863          */
1864         if (tail > (BUF_PAGE_SIZE - RB_EVNT_MIN_SIZE)) {
1865                 /* No room for any events */
1866
1867                 /* Mark the rest of the page with padding */
1868                 rb_event_set_padding(event);
1869
1870                 /* Set the write back to the previous setting */
1871                 local_sub(length, &tail_page->write);
1872                 return;
1873         }
1874
1875         /* Put in a discarded event */
1876         event->array[0] = (BUF_PAGE_SIZE - tail) - RB_EVNT_HDR_SIZE;
1877         event->type_len = RINGBUF_TYPE_PADDING;
1878         /* time delta must be non zero */
1879         event->time_delta = 1;
1880
1881         /* Set write to end of buffer */
1882         length = (tail + length) - BUF_PAGE_SIZE;
1883         local_sub(length, &tail_page->write);
1884 }
1885
1886 /*
1887  * This is the slow path, force gcc not to inline it.
1888  */
1889 static noinline struct ring_buffer_event *
1890 rb_move_tail(struct ring_buffer_per_cpu *cpu_buffer,
1891              unsigned long length, unsigned long tail,
1892              struct buffer_page *tail_page, u64 ts)
1893 {
1894         struct buffer_page *commit_page = cpu_buffer->commit_page;
1895         struct ring_buffer *buffer = cpu_buffer->buffer;
1896         struct buffer_page *next_page;
1897         int ret;
1898
1899         next_page = tail_page;
1900
1901         rb_inc_page(cpu_buffer, &next_page);
1902
1903         /*
1904          * If for some reason, we had an interrupt storm that made
1905          * it all the way around the buffer, bail, and warn
1906          * about it.
1907          */
1908         if (unlikely(next_page == commit_page)) {
1909                 local_inc(&cpu_buffer->commit_overrun);
1910                 goto out_reset;
1911         }
1912
1913         /*
1914          * This is where the fun begins!
1915          *
1916          * We are fighting against races between a reader that
1917          * could be on another CPU trying to swap its reader
1918          * page with the buffer head.
1919          *
1920          * We are also fighting against interrupts coming in and
1921          * moving the head or tail on us as well.
1922          *
1923          * If the next page is the head page then we have filled
1924          * the buffer, unless the commit page is still on the
1925          * reader page.
1926          */
1927         if (rb_is_head_page(cpu_buffer, next_page, &tail_page->list)) {
1928
1929                 /*
1930                  * If the commit is not on the reader page, then
1931                  * move the header page.
1932                  */
1933                 if (!rb_is_reader_page(cpu_buffer->commit_page)) {
1934                         /*
1935                          * If we are not in overwrite mode,
1936                          * this is easy, just stop here.
1937                          */
1938                         if (!(buffer->flags & RB_FL_OVERWRITE))
1939                                 goto out_reset;
1940
1941                         ret = rb_handle_head_page(cpu_buffer,
1942                                                   tail_page,
1943                                                   next_page);
1944                         if (ret < 0)
1945                                 goto out_reset;
1946                         if (ret)
1947                                 goto out_again;
1948                 } else {
1949                         /*
1950                          * We need to be careful here too. The
1951                          * commit page could still be on the reader
1952                          * page. We could have a small buffer, and
1953                          * have filled up the buffer with events
1954                          * from interrupts and such, and wrapped.
1955                          *
1956                          * Note, if the tail page is also the on the
1957                          * reader_page, we let it move out.
1958                          */
1959                         if (unlikely((cpu_buffer->commit_page !=
1960                                       cpu_buffer->tail_page) &&
1961                                      (cpu_buffer->commit_page ==
1962                                       cpu_buffer->reader_page))) {
1963                                 local_inc(&cpu_buffer->commit_overrun);
1964                                 goto out_reset;
1965                         }
1966                 }
1967         }
1968
1969         ret = rb_tail_page_update(cpu_buffer, tail_page, next_page);
1970         if (ret) {
1971                 /*
1972                  * Nested commits always have zero deltas, so
1973                  * just reread the time stamp
1974                  */
1975                 ts = rb_time_stamp(buffer);
1976                 next_page->page->time_stamp = ts;
1977         }
1978
1979  out_again:
1980
1981         rb_reset_tail(cpu_buffer, tail_page, tail, length);
1982
1983         /* fail and let the caller try again */
1984         return ERR_PTR(-EAGAIN);
1985
1986  out_reset:
1987         /* reset write */
1988         rb_reset_tail(cpu_buffer, tail_page, tail, length);
1989
1990         return NULL;
1991 }
1992
1993 static struct ring_buffer_event *
1994 __rb_reserve_next(struct ring_buffer_per_cpu *cpu_buffer,
1995                   unsigned long length, u64 ts,
1996                   u64 delta, int add_timestamp)
1997 {
1998         struct buffer_page *tail_page;
1999         struct ring_buffer_event *event;
2000         unsigned long tail, write;
2001
2002         /*
2003          * If the time delta since the last event is too big to
2004          * hold in the time field of the event, then we append a
2005          * TIME EXTEND event ahead of the data event.
2006          */
2007         if (unlikely(add_timestamp))
2008                 length += RB_LEN_TIME_EXTEND;
2009
2010         tail_page = cpu_buffer->tail_page;
2011         write = local_add_return(length, &tail_page->write);
2012
2013         /* set write to only the index of the write */
2014         write &= RB_WRITE_MASK;
2015         tail = write - length;
2016
2017         /* See if we shot pass the end of this buffer page */
2018         if (unlikely(write > BUF_PAGE_SIZE))
2019                 return rb_move_tail(cpu_buffer, length, tail,
2020                                     tail_page, ts);
2021
2022         /* We reserved something on the buffer */
2023
2024         event = __rb_page_index(tail_page, tail);
2025         kmemcheck_annotate_bitfield(event, bitfield);
2026         rb_update_event(cpu_buffer, event, length, add_timestamp, delta);
2027
2028         local_inc(&tail_page->entries);
2029
2030         /*
2031          * If this is the first commit on the page, then update
2032          * its timestamp.
2033          */
2034         if (!tail)
2035                 tail_page->page->time_stamp = ts;
2036
2037         /* account for these added bytes */
2038         local_add(length, &cpu_buffer->entries_bytes);
2039
2040         return event;
2041 }
2042
2043 static inline int
2044 rb_try_to_discard(struct ring_buffer_per_cpu *cpu_buffer,
2045                   struct ring_buffer_event *event)
2046 {
2047         unsigned long new_index, old_index;
2048         struct buffer_page *bpage;
2049         unsigned long index;
2050         unsigned long addr;
2051
2052         new_index = rb_event_index(event);
2053         old_index = new_index + rb_event_ts_length(event);
2054         addr = (unsigned long)event;
2055         addr &= PAGE_MASK;
2056
2057         bpage = cpu_buffer->tail_page;
2058
2059         if (bpage->page == (void *)addr && rb_page_write(bpage) == old_index) {
2060                 unsigned long write_mask =
2061                         local_read(&bpage->write) & ~RB_WRITE_MASK;
2062                 unsigned long event_length = rb_event_length(event);
2063                 /*
2064                  * This is on the tail page. It is possible that
2065                  * a write could come in and move the tail page
2066                  * and write to the next page. That is fine
2067                  * because we just shorten what is on this page.
2068                  */
2069                 old_index += write_mask;
2070                 new_index += write_mask;
2071                 index = local_cmpxchg(&bpage->write, old_index, new_index);
2072                 if (index == old_index) {
2073                         /* update counters */
2074                         local_sub(event_length, &cpu_buffer->entries_bytes);
2075                         return 1;
2076                 }
2077         }
2078
2079         /* could not discard */
2080         return 0;
2081 }
2082
2083 static void rb_start_commit(struct ring_buffer_per_cpu *cpu_buffer)
2084 {
2085         local_inc(&cpu_buffer->committing);
2086         local_inc(&cpu_buffer->commits);
2087 }
2088
2089 static inline void rb_end_commit(struct ring_buffer_per_cpu *cpu_buffer)
2090 {
2091         unsigned long commits;
2092
2093         if (RB_WARN_ON(cpu_buffer,
2094                        !local_read(&cpu_buffer->committing)))
2095                 return;
2096
2097  again:
2098         commits = local_read(&cpu_buffer->commits);
2099         /* synchronize with interrupts */
2100         barrier();
2101         if (local_read(&cpu_buffer->committing) == 1)
2102                 rb_set_commit_to_write(cpu_buffer);
2103
2104         local_dec(&cpu_buffer->committing);
2105
2106         /* synchronize with interrupts */
2107         barrier();
2108
2109         /*
2110          * Need to account for interrupts coming in between the
2111          * updating of the commit page and the clearing of the
2112          * committing counter.
2113          */
2114         if (unlikely(local_read(&cpu_buffer->commits) != commits) &&
2115             !local_read(&cpu_buffer->committing)) {
2116                 local_inc(&cpu_buffer->committing);
2117                 goto again;
2118         }
2119 }
2120
2121 static struct ring_buffer_event *
2122 rb_reserve_next_event(struct ring_buffer *buffer,
2123                       struct ring_buffer_per_cpu *cpu_buffer,
2124                       unsigned long length)
2125 {
2126         struct ring_buffer_event *event;
2127         u64 ts, delta;
2128         int nr_loops = 0;
2129         int add_timestamp;
2130         u64 diff;
2131
2132         rb_start_commit(cpu_buffer);
2133
2134 #ifdef CONFIG_RING_BUFFER_ALLOW_SWAP
2135         /*
2136          * Due to the ability to swap a cpu buffer from a buffer
2137          * it is possible it was swapped before we committed.
2138          * (committing stops a swap). We check for it here and
2139          * if it happened, we have to fail the write.
2140          */
2141         barrier();
2142         if (unlikely(ACCESS_ONCE(cpu_buffer->buffer) != buffer)) {
2143                 local_dec(&cpu_buffer->committing);
2144                 local_dec(&cpu_buffer->commits);
2145                 return NULL;
2146         }
2147 #endif
2148
2149         length = rb_calculate_event_length(length);
2150  again:
2151         add_timestamp = 0;
2152         delta = 0;
2153
2154         /*
2155          * We allow for interrupts to reenter here and do a trace.
2156          * If one does, it will cause this original code to loop
2157          * back here. Even with heavy interrupts happening, this
2158          * should only happen a few times in a row. If this happens
2159          * 1000 times in a row, there must be either an interrupt
2160          * storm or we have something buggy.
2161          * Bail!
2162          */
2163         if (RB_WARN_ON(cpu_buffer, ++nr_loops > 1000))
2164                 goto out_fail;
2165
2166         ts = rb_time_stamp(cpu_buffer->buffer);
2167         diff = ts - cpu_buffer->write_stamp;
2168
2169         /* make sure this diff is calculated here */
2170         barrier();
2171
2172         /* Did the write stamp get updated already? */
2173         if (likely(ts >= cpu_buffer->write_stamp)) {
2174                 delta = diff;
2175                 if (unlikely(test_time_stamp(delta))) {
2176                         int local_clock_stable = 1;
2177 #ifdef CONFIG_HAVE_UNSTABLE_SCHED_CLOCK
2178                         local_clock_stable = sched_clock_stable;
2179 #endif
2180                         WARN_ONCE(delta > (1ULL << 59),
2181                                   KERN_WARNING "Delta way too big! %llu ts=%llu write stamp = %llu\n%s",
2182                                   (unsigned long long)delta,
2183                                   (unsigned long long)ts,
2184                                   (unsigned long long)cpu_buffer->write_stamp,
2185                                   local_clock_stable ? "" :
2186                                   "If you just came from a suspend/resume,\n"
2187                                   "please switch to the trace global clock:\n"
2188                                   "  echo global > /sys/kernel/debug/tracing/trace_clock\n");
2189                         add_timestamp = 1;
2190                 }
2191         }
2192
2193         event = __rb_reserve_next(cpu_buffer, length, ts,
2194                                   delta, add_timestamp);
2195         if (unlikely(PTR_ERR(event) == -EAGAIN))
2196                 goto again;
2197
2198         if (!event)
2199                 goto out_fail;
2200
2201         return event;
2202
2203  out_fail:
2204         rb_end_commit(cpu_buffer);
2205         return NULL;
2206 }
2207
2208 #ifdef CONFIG_TRACING
2209
2210 #define TRACE_RECURSIVE_DEPTH 16
2211
2212 /* Keep this code out of the fast path cache */
2213 static noinline void trace_recursive_fail(void)
2214 {
2215         /* Disable all tracing before we do anything else */
2216         tracing_off_permanent();
2217
2218         printk_once(KERN_WARNING "Tracing recursion: depth[%ld]:"
2219                     "HC[%lu]:SC[%lu]:NMI[%lu]\n",
2220                     trace_recursion_buffer(),
2221                     hardirq_count() >> HARDIRQ_SHIFT,
2222                     softirq_count() >> SOFTIRQ_SHIFT,
2223                     in_nmi());
2224
2225         WARN_ON_ONCE(1);
2226 }
2227
2228 static inline int trace_recursive_lock(void)
2229 {
2230         trace_recursion_inc();
2231
2232         if (likely(trace_recursion_buffer() < TRACE_RECURSIVE_DEPTH))
2233                 return 0;
2234
2235         trace_recursive_fail();
2236
2237         return -1;
2238 }
2239
2240 static inline void trace_recursive_unlock(void)
2241 {
2242         WARN_ON_ONCE(!trace_recursion_buffer());
2243
2244         trace_recursion_dec();
2245 }
2246
2247 #else
2248
2249 #define trace_recursive_lock()          (0)
2250 #define trace_recursive_unlock()        do { } while (0)
2251
2252 #endif
2253
2254 /**
2255  * ring_buffer_lock_reserve - reserve a part of the buffer
2256  * @buffer: the ring buffer to reserve from
2257  * @length: the length of the data to reserve (excluding event header)
2258  *
2259  * Returns a reseverd event on the ring buffer to copy directly to.
2260  * The user of this interface will need to get the body to write into
2261  * and can use the ring_buffer_event_data() interface.
2262  *
2263  * The length is the length of the data needed, not the event length
2264  * which also includes the event header.
2265  *
2266  * Must be paired with ring_buffer_unlock_commit, unless NULL is returned.
2267  * If NULL is returned, then nothing has been allocated or locked.
2268  */
2269 struct ring_buffer_event *
2270 ring_buffer_lock_reserve(struct ring_buffer *buffer, unsigned long length)
2271 {
2272         struct ring_buffer_per_cpu *cpu_buffer;
2273         struct ring_buffer_event *event;
2274         int cpu;
2275
2276         if (ring_buffer_flags != RB_BUFFERS_ON)
2277                 return NULL;
2278
2279         /* If we are tracing schedule, we don't want to recurse */
2280         preempt_disable_notrace();
2281
2282         if (atomic_read(&buffer->record_disabled))
2283                 goto out_nocheck;
2284
2285         if (trace_recursive_lock())
2286                 goto out_nocheck;
2287
2288         cpu = raw_smp_processor_id();
2289
2290         if (!cpumask_test_cpu(cpu, buffer->cpumask))
2291                 goto out;
2292
2293         cpu_buffer = buffer->buffers[cpu];
2294
2295         if (atomic_read(&cpu_buffer->record_disabled))
2296                 goto out;
2297
2298         if (length > BUF_MAX_DATA_SIZE)
2299                 goto out;
2300
2301         event = rb_reserve_next_event(buffer, cpu_buffer, length);
2302         if (!event)
2303                 goto out;
2304
2305         return event;
2306
2307  out:
2308         trace_recursive_unlock();
2309
2310  out_nocheck:
2311         preempt_enable_notrace();
2312         return NULL;
2313 }
2314 EXPORT_SYMBOL_GPL(ring_buffer_lock_reserve);
2315
2316 static void
2317 rb_update_write_stamp(struct ring_buffer_per_cpu *cpu_buffer,
2318                       struct ring_buffer_event *event)
2319 {
2320         u64 delta;
2321
2322         /*
2323          * The event first in the commit queue updates the
2324          * time stamp.
2325          */
2326         if (rb_event_is_commit(cpu_buffer, event)) {
2327                 /*
2328                  * A commit event that is first on a page
2329                  * updates the write timestamp with the page stamp
2330                  */
2331                 if (!rb_event_index(event))
2332                         cpu_buffer->write_stamp =
2333                                 cpu_buffer->commit_page->page->time_stamp;
2334                 else if (event->type_len == RINGBUF_TYPE_TIME_EXTEND) {
2335                         delta = event->array[0];
2336                         delta <<= TS_SHIFT;
2337                         delta += event->time_delta;
2338                         cpu_buffer->write_stamp += delta;
2339                 } else
2340                         cpu_buffer->write_stamp += event->time_delta;
2341         }
2342 }
2343
2344 static void rb_commit(struct ring_buffer_per_cpu *cpu_buffer,
2345                       struct ring_buffer_event *event)
2346 {
2347         local_inc(&cpu_buffer->entries);
2348         rb_update_write_stamp(cpu_buffer, event);
2349         rb_end_commit(cpu_buffer);
2350 }
2351
2352 /**
2353  * ring_buffer_unlock_commit - commit a reserved
2354  * @buffer: The buffer to commit to
2355  * @event: The event pointer to commit.
2356  *
2357  * This commits the data to the ring buffer, and releases any locks held.
2358  *
2359  * Must be paired with ring_buffer_lock_reserve.
2360  */
2361 int ring_buffer_unlock_commit(struct ring_buffer *buffer,
2362                               struct ring_buffer_event *event)
2363 {
2364         struct ring_buffer_per_cpu *cpu_buffer;
2365         int cpu = raw_smp_processor_id();
2366
2367         cpu_buffer = buffer->buffers[cpu];
2368
2369         rb_commit(cpu_buffer, event);
2370
2371         trace_recursive_unlock();
2372
2373         preempt_enable_notrace();
2374
2375         return 0;
2376 }
2377 EXPORT_SYMBOL_GPL(ring_buffer_unlock_commit);
2378
2379 static inline void rb_event_discard(struct ring_buffer_event *event)
2380 {
2381         if (event->type_len == RINGBUF_TYPE_TIME_EXTEND)
2382                 event = skip_time_extend(event);
2383
2384         /* array[0] holds the actual length for the discarded event */
2385         event->array[0] = rb_event_data_length(event) - RB_EVNT_HDR_SIZE;
2386         event->type_len = RINGBUF_TYPE_PADDING;
2387         /* time delta must be non zero */
2388         if (!event->time_delta)
2389                 event->time_delta = 1;
2390 }
2391
2392 /*
2393  * Decrement the entries to the page that an event is on.
2394  * The event does not even need to exist, only the pointer
2395  * to the page it is on. This may only be called before the commit
2396  * takes place.
2397  */
2398 static inline void
2399 rb_decrement_entry(struct ring_buffer_per_cpu *cpu_buffer,
2400                    struct ring_buffer_event *event)
2401 {
2402         unsigned long addr = (unsigned long)event;
2403         struct buffer_page *bpage = cpu_buffer->commit_page;
2404         struct buffer_page *start;
2405
2406         addr &= PAGE_MASK;
2407
2408         /* Do the likely case first */
2409         if (likely(bpage->page == (void *)addr)) {
2410                 local_dec(&bpage->entries);
2411                 return;
2412         }
2413
2414         /*
2415          * Because the commit page may be on the reader page we
2416          * start with the next page and check the end loop there.
2417          */
2418         rb_inc_page(cpu_buffer, &bpage);
2419         start = bpage;
2420         do {
2421                 if (bpage->page == (void *)addr) {
2422                         local_dec(&bpage->entries);
2423                         return;
2424                 }
2425                 rb_inc_page(cpu_buffer, &bpage);
2426         } while (bpage != start);
2427
2428         /* commit not part of this buffer?? */
2429         RB_WARN_ON(cpu_buffer, 1);
2430 }
2431
2432 /**
2433  * ring_buffer_commit_discard - discard an event that has not been committed
2434  * @buffer: the ring buffer
2435  * @event: non committed event to discard
2436  *
2437  * Sometimes an event that is in the ring buffer needs to be ignored.
2438  * This function lets the user discard an event in the ring buffer
2439  * and then that event will not be read later.
2440  *
2441  * This function only works if it is called before the the item has been
2442  * committed. It will try to free the event from the ring buffer
2443  * if another event has not been added behind it.
2444  *
2445  * If another event has been added behind it, it will set the event
2446  * up as discarded, and perform the commit.
2447  *
2448  * If this function is called, do not call ring_buffer_unlock_commit on
2449  * the event.
2450  */
2451 void ring_buffer_discard_commit(struct ring_buffer *buffer,
2452                                 struct ring_buffer_event *event)
2453 {
2454         struct ring_buffer_per_cpu *cpu_buffer;
2455         int cpu;
2456
2457         /* The event is discarded regardless */
2458         rb_event_discard(event);
2459
2460         cpu = smp_processor_id();
2461         cpu_buffer = buffer->buffers[cpu];
2462
2463         /*
2464          * This must only be called if the event has not been
2465          * committed yet. Thus we can assume that preemption
2466          * is still disabled.
2467          */
2468         RB_WARN_ON(buffer, !local_read(&cpu_buffer->committing));
2469
2470         rb_decrement_entry(cpu_buffer, event);
2471         if (rb_try_to_discard(cpu_buffer, event))
2472                 goto out;
2473
2474         /*
2475          * The commit is still visible by the reader, so we
2476          * must still update the timestamp.
2477          */
2478         rb_update_write_stamp(cpu_buffer, event);
2479  out:
2480         rb_end_commit(cpu_buffer);
2481
2482         trace_recursive_unlock();
2483
2484         preempt_enable_notrace();
2485
2486 }
2487 EXPORT_SYMBOL_GPL(ring_buffer_discard_commit);
2488
2489 /**
2490  * ring_buffer_write - write data to the buffer without reserving
2491  * @buffer: The ring buffer to write to.
2492  * @length: The length of the data being written (excluding the event header)
2493  * @data: The data to write to the buffer.
2494  *
2495  * This is like ring_buffer_lock_reserve and ring_buffer_unlock_commit as
2496  * one function. If you already have the data to write to the buffer, it
2497  * may be easier to simply call this function.
2498  *
2499  * Note, like ring_buffer_lock_reserve, the length is the length of the data
2500  * and not the length of the event which would hold the header.
2501  */
2502 int ring_buffer_write(struct ring_buffer *buffer,
2503                         unsigned long length,
2504                         void *data)
2505 {
2506         struct ring_buffer_per_cpu *cpu_buffer;
2507         struct ring_buffer_event *event;
2508         void *body;
2509         int ret = -EBUSY;
2510         int cpu;
2511
2512         if (ring_buffer_flags != RB_BUFFERS_ON)
2513                 return -EBUSY;
2514
2515         preempt_disable_notrace();
2516
2517         if (atomic_read(&buffer->record_disabled))
2518                 goto out;
2519
2520         cpu = raw_smp_processor_id();
2521
2522         if (!cpumask_test_cpu(cpu, buffer->cpumask))
2523                 goto out;
2524
2525         cpu_buffer = buffer->buffers[cpu];
2526
2527         if (atomic_read(&cpu_buffer->record_disabled))
2528                 goto out;
2529
2530         if (length > BUF_MAX_DATA_SIZE)
2531                 goto out;
2532
2533         event = rb_reserve_next_event(buffer, cpu_buffer, length);
2534         if (!event)
2535                 goto out;
2536
2537         body = rb_event_data(event);
2538
2539         memcpy(body, data, length);
2540
2541         rb_commit(cpu_buffer, event);
2542
2543         ret = 0;
2544  out:
2545         preempt_enable_notrace();
2546
2547         return ret;
2548 }
2549 EXPORT_SYMBOL_GPL(ring_buffer_write);
2550
2551 static int rb_per_cpu_empty(struct ring_buffer_per_cpu *cpu_buffer)
2552 {
2553         struct buffer_page *reader = cpu_buffer->reader_page;
2554         struct buffer_page *head = rb_set_head_page(cpu_buffer);
2555         struct buffer_page *commit = cpu_buffer->commit_page;
2556
2557         /* In case of error, head will be NULL */
2558         if (unlikely(!head))
2559                 return 1;
2560
2561         return reader->read == rb_page_commit(reader) &&
2562                 (commit == reader ||
2563                  (commit == head &&
2564                   head->read == rb_page_commit(commit)));
2565 }
2566
2567 /**
2568  * ring_buffer_record_disable - stop all writes into the buffer
2569  * @buffer: The ring buffer to stop writes to.
2570  *
2571  * This prevents all writes to the buffer. Any attempt to write
2572  * to the buffer after this will fail and return NULL.
2573  *
2574  * The caller should call synchronize_sched() after this.
2575  */
2576 void ring_buffer_record_disable(struct ring_buffer *buffer)
2577 {
2578         atomic_inc(&buffer->record_disabled);
2579 }
2580 EXPORT_SYMBOL_GPL(ring_buffer_record_disable);
2581
2582 /**
2583  * ring_buffer_record_enable - enable writes to the buffer
2584  * @buffer: The ring buffer to enable writes
2585  *
2586  * Note, multiple disables will need the same number of enables
2587  * to truly enable the writing (much like preempt_disable).
2588  */
2589 void ring_buffer_record_enable(struct ring_buffer *buffer)
2590 {
2591         atomic_dec(&buffer->record_disabled);
2592 }
2593 EXPORT_SYMBOL_GPL(ring_buffer_record_enable);
2594
2595 /**
2596  * ring_buffer_record_off - stop all writes into the buffer
2597  * @buffer: The ring buffer to stop writes to.
2598  *
2599  * This prevents all writes to the buffer. Any attempt to write
2600  * to the buffer after this will fail and return NULL.
2601  *
2602  * This is different than ring_buffer_record_disable() as
2603  * it works like an on/off switch, where as the disable() verison
2604  * must be paired with a enable().
2605  */
2606 void ring_buffer_record_off(struct ring_buffer *buffer)
2607 {
2608         unsigned int rd;
2609         unsigned int new_rd;
2610
2611         do {
2612                 rd = atomic_read(&buffer->record_disabled);
2613                 new_rd = rd | RB_BUFFER_OFF;
2614         } while (atomic_cmpxchg(&buffer->record_disabled, rd, new_rd) != rd);
2615 }
2616 EXPORT_SYMBOL_GPL(ring_buffer_record_off);
2617
2618 /**
2619  * ring_buffer_record_on - restart writes into the buffer
2620  * @buffer: The ring buffer to start writes to.
2621  *
2622  * This enables all writes to the buffer that was disabled by
2623  * ring_buffer_record_off().
2624  *
2625  * This is different than ring_buffer_record_enable() as
2626  * it works like an on/off switch, where as the enable() verison
2627  * must be paired with a disable().
2628  */
2629 void ring_buffer_record_on(struct ring_buffer *buffer)
2630 {
2631         unsigned int rd;
2632         unsigned int new_rd;
2633
2634         do {
2635                 rd = atomic_read(&buffer->record_disabled);
2636                 new_rd = rd & ~RB_BUFFER_OFF;
2637         } while (atomic_cmpxchg(&buffer->record_disabled, rd, new_rd) != rd);
2638 }
2639 EXPORT_SYMBOL_GPL(ring_buffer_record_on);
2640
2641 /**
2642  * ring_buffer_record_is_on - return true if the ring buffer can write
2643  * @buffer: The ring buffer to see if write is enabled
2644  *
2645  * Returns true if the ring buffer is in a state that it accepts writes.
2646  */
2647 int ring_buffer_record_is_on(struct ring_buffer *buffer)
2648 {
2649         return !atomic_read(&buffer->record_disabled);
2650 }
2651
2652 /**
2653  * ring_buffer_record_disable_cpu - stop all writes into the cpu_buffer
2654  * @buffer: The ring buffer to stop writes to.
2655  * @cpu: The CPU buffer to stop
2656  *
2657  * This prevents all writes to the buffer. Any attempt to write
2658  * to the buffer after this will fail and return NULL.
2659  *
2660  * The caller should call synchronize_sched() after this.
2661  */
2662 void ring_buffer_record_disable_cpu(struct ring_buffer *buffer, int cpu)
2663 {
2664         struct ring_buffer_per_cpu *cpu_buffer;
2665
2666         if (!cpumask_test_cpu(cpu, buffer->cpumask))
2667                 return;
2668
2669         cpu_buffer = buffer->buffers[cpu];
2670         atomic_inc(&cpu_buffer->record_disabled);
2671 }
2672 EXPORT_SYMBOL_GPL(ring_buffer_record_disable_cpu);
2673
2674 /**
2675  * ring_buffer_record_enable_cpu - enable writes to the buffer
2676  * @buffer: The ring buffer to enable writes
2677  * @cpu: The CPU to enable.
2678  *
2679  * Note, multiple disables will need the same number of enables
2680  * to truly enable the writing (much like preempt_disable).
2681  */
2682 void ring_buffer_record_enable_cpu(struct ring_buffer *buffer, int cpu)
2683 {
2684         struct ring_buffer_per_cpu *cpu_buffer;
2685
2686         if (!cpumask_test_cpu(cpu, buffer->cpumask))
2687                 return;
2688
2689         cpu_buffer = buffer->buffers[cpu];
2690         atomic_dec(&cpu_buffer->record_disabled);
2691 }
2692 EXPORT_SYMBOL_GPL(ring_buffer_record_enable_cpu);
2693
2694 /*
2695  * The total entries in the ring buffer is the running counter
2696  * of entries entered into the ring buffer, minus the sum of
2697  * the entries read from the ring buffer and the number of
2698  * entries that were overwritten.
2699  */
2700 static inline unsigned long
2701 rb_num_of_entries(struct ring_buffer_per_cpu *cpu_buffer)
2702 {
2703         return local_read(&cpu_buffer->entries) -
2704                 (local_read(&cpu_buffer->overrun) + cpu_buffer->read);
2705 }
2706
2707 /**
2708  * ring_buffer_oldest_event_ts - get the oldest event timestamp from the buffer
2709  * @buffer: The ring buffer
2710  * @cpu: The per CPU buffer to read from.
2711  */
2712 unsigned long ring_buffer_oldest_event_ts(struct ring_buffer *buffer, int cpu)
2713 {
2714         unsigned long flags;
2715         struct ring_buffer_per_cpu *cpu_buffer;
2716         struct buffer_page *bpage;
2717         unsigned long ret;
2718
2719         if (!cpumask_test_cpu(cpu, buffer->cpumask))
2720                 return 0;
2721
2722         cpu_buffer = buffer->buffers[cpu];
2723         raw_spin_lock_irqsave(&cpu_buffer->reader_lock, flags);
2724         /*
2725          * if the tail is on reader_page, oldest time stamp is on the reader
2726          * page
2727          */
2728         if (cpu_buffer->tail_page == cpu_buffer->reader_page)
2729                 bpage = cpu_buffer->reader_page;
2730         else
2731                 bpage = rb_set_head_page(cpu_buffer);
2732         ret = bpage->page->time_stamp;
2733         raw_spin_unlock_irqrestore(&cpu_buffer->reader_lock, flags);
2734
2735         return ret;
2736 }
2737 EXPORT_SYMBOL_GPL(ring_buffer_oldest_event_ts);
2738
2739 /**
2740  * ring_buffer_bytes_cpu - get the number of bytes consumed in a cpu buffer
2741  * @buffer: The ring buffer
2742  * @cpu: The per CPU buffer to read from.
2743  */
2744 unsigned long ring_buffer_bytes_cpu(struct ring_buffer *buffer, int cpu)
2745 {
2746         struct ring_buffer_per_cpu *cpu_buffer;
2747         unsigned long ret;
2748
2749         if (!cpumask_test_cpu(cpu, buffer->cpumask))
2750                 return 0;
2751
2752         cpu_buffer = buffer->buffers[cpu];
2753         ret = local_read(&cpu_buffer->entries_bytes) - cpu_buffer->read_bytes;
2754
2755         return ret;
2756 }
2757 EXPORT_SYMBOL_GPL(ring_buffer_bytes_cpu);
2758
2759 /**
2760  * ring_buffer_entries_cpu - get the number of entries in a cpu buffer
2761  * @buffer: The ring buffer
2762  * @cpu: The per CPU buffer to get the entries from.
2763  */
2764 unsigned long ring_buffer_entries_cpu(struct ring_buffer *buffer, int cpu)
2765 {
2766         struct ring_buffer_per_cpu *cpu_buffer;
2767
2768         if (!cpumask_test_cpu(cpu, buffer->cpumask))
2769                 return 0;
2770
2771         cpu_buffer = buffer->buffers[cpu];
2772
2773         return rb_num_of_entries(cpu_buffer);
2774 }
2775 EXPORT_SYMBOL_GPL(ring_buffer_entries_cpu);
2776
2777 /**
2778  * ring_buffer_overrun_cpu - get the number of overruns in a cpu_buffer
2779  * @buffer: The ring buffer
2780  * @cpu: The per CPU buffer to get the number of overruns from
2781  */
2782 unsigned long ring_buffer_overrun_cpu(struct ring_buffer *buffer, int cpu)
2783 {
2784         struct ring_buffer_per_cpu *cpu_buffer;
2785         unsigned long ret;
2786
2787         if (!cpumask_test_cpu(cpu, buffer->cpumask))
2788                 return 0;
2789
2790         cpu_buffer = buffer->buffers[cpu];
2791         ret = local_read(&cpu_buffer->overrun);
2792
2793         return ret;
2794 }
2795 EXPORT_SYMBOL_GPL(ring_buffer_overrun_cpu);
2796
2797 /**
2798  * ring_buffer_commit_overrun_cpu - get the number of overruns caused by commits
2799  * @buffer: The ring buffer
2800  * @cpu: The per CPU buffer to get the number of overruns from
2801  */
2802 unsigned long
2803 ring_buffer_commit_overrun_cpu(struct ring_buffer *buffer, int cpu)
2804 {
2805         struct ring_buffer_per_cpu *cpu_buffer;
2806         unsigned long ret;
2807
2808         if (!cpumask_test_cpu(cpu, buffer->cpumask))
2809                 return 0;
2810
2811         cpu_buffer = buffer->buffers[cpu];
2812         ret = local_read(&cpu_buffer->commit_overrun);
2813
2814         return ret;
2815 }
2816 EXPORT_SYMBOL_GPL(ring_buffer_commit_overrun_cpu);
2817
2818 /**
2819  * ring_buffer_entries - get the number of entries in a buffer
2820  * @buffer: The ring buffer
2821  *
2822  * Returns the total number of entries in the ring buffer
2823  * (all CPU entries)
2824  */
2825 unsigned long ring_buffer_entries(struct ring_buffer *buffer)
2826 {
2827         struct ring_buffer_per_cpu *cpu_buffer;
2828         unsigned long entries = 0;
2829         int cpu;
2830
2831         /* if you care about this being correct, lock the buffer */
2832         for_each_buffer_cpu(buffer, cpu) {
2833                 cpu_buffer = buffer->buffers[cpu];
2834                 entries += rb_num_of_entries(cpu_buffer);
2835         }
2836
2837         return entries;
2838 }
2839 EXPORT_SYMBOL_GPL(ring_buffer_entries);
2840
2841 /**
2842  * ring_buffer_overruns - get the number of overruns in buffer
2843  * @buffer: The ring buffer
2844  *
2845  * Returns the total number of overruns in the ring buffer
2846  * (all CPU entries)
2847  */
2848 unsigned long ring_buffer_overruns(struct ring_buffer *buffer)
2849 {
2850         struct ring_buffer_per_cpu *cpu_buffer;
2851         unsigned long overruns = 0;
2852         int cpu;
2853
2854         /* if you care about this being correct, lock the buffer */
2855         for_each_buffer_cpu(buffer, cpu) {
2856                 cpu_buffer = buffer->buffers[cpu];
2857                 overruns += local_read(&cpu_buffer->overrun);
2858         }
2859
2860         return overruns;
2861 }
2862 EXPORT_SYMBOL_GPL(ring_buffer_overruns);
2863
2864 static void rb_iter_reset(struct ring_buffer_iter *iter)
2865 {
2866         struct ring_buffer_per_cpu *cpu_buffer = iter->cpu_buffer;
2867
2868         /* Iterator usage is expected to have record disabled */
2869         if (list_empty(&cpu_buffer->reader_page->list)) {
2870                 iter->head_page = rb_set_head_page(cpu_buffer);
2871                 if (unlikely(!iter->head_page))
2872                         return;
2873                 iter->head = iter->head_page->read;
2874         } else {
2875                 iter->head_page = cpu_buffer->reader_page;
2876                 iter->head = cpu_buffer->reader_page->read;
2877         }
2878         if (iter->head)
2879                 iter->read_stamp = cpu_buffer->read_stamp;
2880         else
2881                 iter->read_stamp = iter->head_page->page->time_stamp;
2882         iter->cache_reader_page = cpu_buffer->reader_page;
2883         iter->cache_read = cpu_buffer->read;
2884 }
2885
2886 /**
2887  * ring_buffer_iter_reset - reset an iterator
2888  * @iter: The iterator to reset
2889  *
2890  * Resets the iterator, so that it will start from the beginning
2891  * again.
2892  */
2893 void ring_buffer_iter_reset(struct ring_buffer_iter *iter)
2894 {
2895         struct ring_buffer_per_cpu *cpu_buffer;
2896         unsigned long flags;
2897
2898         if (!iter)
2899                 return;
2900
2901         cpu_buffer = iter->cpu_buffer;
2902
2903         raw_spin_lock_irqsave(&cpu_buffer->reader_lock, flags);
2904         rb_iter_reset(iter);
2905         raw_spin_unlock_irqrestore(&cpu_buffer->reader_lock, flags);
2906 }
2907 EXPORT_SYMBOL_GPL(ring_buffer_iter_reset);
2908
2909 /**
2910  * ring_buffer_iter_empty - check if an iterator has no more to read
2911  * @iter: The iterator to check
2912  */
2913 int ring_buffer_iter_empty(struct ring_buffer_iter *iter)
2914 {
2915         struct ring_buffer_per_cpu *cpu_buffer;
2916
2917         cpu_buffer = iter->cpu_buffer;
2918
2919         return iter->head_page == cpu_buffer->commit_page &&
2920                 iter->head == rb_commit_index(cpu_buffer);
2921 }
2922 EXPORT_SYMBOL_GPL(ring_buffer_iter_empty);
2923
2924 static void
2925 rb_update_read_stamp(struct ring_buffer_per_cpu *cpu_buffer,
2926                      struct ring_buffer_event *event)
2927 {
2928         u64 delta;
2929
2930         switch (event->type_len) {
2931         case RINGBUF_TYPE_PADDING:
2932                 return;
2933
2934         case RINGBUF_TYPE_TIME_EXTEND:
2935                 delta = event->array[0];
2936                 delta <<= TS_SHIFT;
2937                 delta += event->time_delta;
2938                 cpu_buffer->read_stamp += delta;
2939                 return;
2940
2941         case RINGBUF_TYPE_TIME_STAMP:
2942                 /* FIXME: not implemented */
2943                 return;
2944
2945         case RINGBUF_TYPE_DATA:
2946                 cpu_buffer->read_stamp += event->time_delta;
2947                 return;
2948
2949         default:
2950                 BUG();
2951         }
2952         return;
2953 }
2954
2955 static void
2956 rb_update_iter_read_stamp(struct ring_buffer_iter *iter,
2957                           struct ring_buffer_event *event)
2958 {
2959         u64 delta;
2960
2961         switch (event->type_len) {
2962         case RINGBUF_TYPE_PADDING:
2963                 return;
2964
2965         case RINGBUF_TYPE_TIME_EXTEND:
2966                 delta = event->array[0];
2967                 delta <<= TS_SHIFT;
2968                 delta += event->time_delta;
2969                 iter->read_stamp += delta;
2970                 return;
2971
2972         case RINGBUF_TYPE_TIME_STAMP:
2973                 /* FIXME: not implemented */
2974                 return;
2975
2976         case RINGBUF_TYPE_DATA:
2977                 iter->read_stamp += event->time_delta;
2978                 return;
2979
2980         default:
2981                 BUG();
2982         }
2983         return;
2984 }
2985
2986 static struct buffer_page *
2987 rb_get_reader_page(struct ring_buffer_per_cpu *cpu_buffer)
2988 {
2989         struct buffer_page *reader = NULL;
2990         unsigned long overwrite;
2991         unsigned long flags;
2992         int nr_loops = 0;
2993         int ret;
2994
2995         local_irq_save(flags);
2996         arch_spin_lock(&cpu_buffer->lock);
2997
2998  again:
2999         /*
3000          * This should normally only loop twice. But because the
3001          * start of the reader inserts an empty page, it causes
3002          * a case where we will loop three times. There should be no
3003          * reason to loop four times (that I know of).
3004          */
3005         if (RB_WARN_ON(cpu_buffer, ++nr_loops > 3)) {
3006                 reader = NULL;
3007                 goto out;
3008         }
3009
3010         reader = cpu_buffer->reader_page;
3011
3012         /* If there's more to read, return this page */
3013         if (cpu_buffer->reader_page->read < rb_page_size(reader))
3014                 goto out;
3015
3016         /* Never should we have an index greater than the size */
3017         if (RB_WARN_ON(cpu_buffer,
3018                        cpu_buffer->reader_page->read > rb_page_size(reader)))
3019                 goto out;
3020
3021         /* check if we caught up to the tail */
3022         reader = NULL;
3023         if (cpu_buffer->commit_page == cpu_buffer->reader_page)
3024                 goto out;
3025
3026         /*
3027          * Reset the reader page to size zero.
3028          */
3029         local_set(&cpu_buffer->reader_page->write, 0);
3030         local_set(&cpu_buffer->reader_page->entries, 0);
3031         local_set(&cpu_buffer->reader_page->page->commit, 0);
3032         cpu_buffer->reader_page->real_end = 0;
3033
3034  spin:
3035         /*
3036          * Splice the empty reader page into the list around the head.
3037          */
3038         reader = rb_set_head_page(cpu_buffer);
3039         cpu_buffer->reader_page->list.next = rb_list_head(reader->list.next);
3040         cpu_buffer->reader_page->list.prev = reader->list.prev;
3041
3042         /*
3043          * cpu_buffer->pages just needs to point to the buffer, it
3044          *  has no specific buffer page to point to. Lets move it out
3045          *  of our way so we don't accidentally swap it.
3046          */
3047         cpu_buffer->pages = reader->list.prev;
3048
3049         /* The reader page will be pointing to the new head */
3050         rb_set_list_to_head(cpu_buffer, &cpu_buffer->reader_page->list);
3051
3052         /*
3053          * We want to make sure we read the overruns after we set up our
3054          * pointers to the next object. The writer side does a
3055          * cmpxchg to cross pages which acts as the mb on the writer
3056          * side. Note, the reader will constantly fail the swap
3057          * while the writer is updating the pointers, so this
3058          * guarantees that the overwrite recorded here is the one we
3059          * want to compare with the last_overrun.
3060          */
3061         smp_mb();
3062         overwrite = local_read(&(cpu_buffer->overrun));
3063
3064         /*
3065          * Here's the tricky part.
3066          *
3067          * We need to move the pointer past the header page.
3068          * But we can only do that if a writer is not currently
3069          * moving it. The page before the header page has the
3070          * flag bit '1' set if it is pointing to the page we want.
3071          * but if the writer is in the process of moving it
3072          * than it will be '2' or already moved '0'.
3073          */
3074
3075         ret = rb_head_page_replace(reader, cpu_buffer->reader_page);
3076
3077         /*
3078          * If we did not convert it, then we must try again.
3079          */
3080         if (!ret)
3081                 goto spin;
3082
3083         /*
3084          * Yeah! We succeeded in replacing the page.
3085          *
3086          * Now make the new head point back to the reader page.
3087          */
3088         rb_list_head(reader->list.next)->prev = &cpu_buffer->reader_page->list;
3089         rb_inc_page(cpu_buffer, &cpu_buffer->head_page);
3090
3091         /* Finally update the reader page to the new head */
3092         cpu_buffer->reader_page = reader;
3093         rb_reset_reader_page(cpu_buffer);
3094
3095         if (overwrite != cpu_buffer->last_overrun) {
3096                 cpu_buffer->lost_events = overwrite - cpu_buffer->last_overrun;
3097                 cpu_buffer->last_overrun = overwrite;
3098         }
3099
3100         goto again;
3101
3102  out:
3103         arch_spin_unlock(&cpu_buffer->lock);
3104         local_irq_restore(flags);
3105
3106         return reader;
3107 }
3108
3109 static void rb_advance_reader(struct ring_buffer_per_cpu *cpu_buffer)
3110 {
3111         struct ring_buffer_event *event;
3112         struct buffer_page *reader;
3113         unsigned length;
3114
3115         reader = rb_get_reader_page(cpu_buffer);
3116
3117         /* This function should not be called when buffer is empty */
3118         if (RB_WARN_ON(cpu_buffer, !reader))
3119                 return;
3120
3121         event = rb_reader_event(cpu_buffer);
3122
3123         if (event->type_len <= RINGBUF_TYPE_DATA_TYPE_LEN_MAX)
3124                 cpu_buffer->read++;
3125
3126         rb_update_read_stamp(cpu_buffer, event);
3127
3128         length = rb_event_length(event);
3129         cpu_buffer->reader_page->read += length;
3130 }
3131
3132 static void rb_advance_iter(struct ring_buffer_iter *iter)
3133 {
3134         struct ring_buffer_per_cpu *cpu_buffer;
3135         struct ring_buffer_event *event;
3136         unsigned length;
3137
3138         cpu_buffer = iter->cpu_buffer;
3139
3140         /*
3141          * Check if we are at the end of the buffer.
3142          */
3143         if (iter->head >= rb_page_size(iter->head_page)) {
3144                 /* discarded commits can make the page empty */
3145                 if (iter->head_page == cpu_buffer->commit_page)
3146                         return;
3147                 rb_inc_iter(iter);
3148                 return;
3149         }
3150
3151         event = rb_iter_head_event(iter);
3152
3153         length = rb_event_length(event);
3154
3155         /*
3156          * This should not be called to advance the header if we are
3157          * at the tail of the buffer.
3158          */
3159         if (RB_WARN_ON(cpu_buffer,
3160                        (iter->head_page == cpu_buffer->commit_page) &&
3161                        (iter->head + length > rb_commit_index(cpu_buffer))))
3162                 return;
3163
3164         rb_update_iter_read_stamp(iter, event);
3165
3166         iter->head += length;
3167
3168         /* check for end of page padding */
3169         if ((iter->head >= rb_page_size(iter->head_page)) &&
3170             (iter->head_page != cpu_buffer->commit_page))
3171                 rb_advance_iter(iter);
3172 }
3173
3174 static int rb_lost_events(struct ring_buffer_per_cpu *cpu_buffer)
3175 {
3176         return cpu_buffer->lost_events;
3177 }
3178
3179 static struct ring_buffer_event *
3180 rb_buffer_peek(struct ring_buffer_per_cpu *cpu_buffer, u64 *ts,
3181                unsigned long *lost_events)
3182 {
3183         struct ring_buffer_event *event;
3184         struct buffer_page *reader;
3185         int nr_loops = 0;
3186
3187  again:
3188         /*
3189          * We repeat when a time extend is encountered.
3190          * Since the time extend is always attached to a data event,
3191          * we should never loop more than once.
3192          * (We never hit the following condition more than twice).
3193          */
3194         if (RB_WARN_ON(cpu_buffer, ++nr_loops > 2))
3195                 return NULL;
3196
3197         reader = rb_get_reader_page(cpu_buffer);
3198         if (!reader)
3199                 return NULL;
3200
3201         event = rb_reader_event(cpu_buffer);
3202
3203         switch (event->type_len) {
3204         case RINGBUF_TYPE_PADDING:
3205                 if (rb_null_event(event))
3206                         RB_WARN_ON(cpu_buffer, 1);
3207                 /*
3208                  * Because the writer could be discarding every
3209                  * event it creates (which would probably be bad)
3210                  * if we were to go back to "again" then we may never
3211                  * catch up, and will trigger the warn on, or lock
3212                  * the box. Return the padding, and we will release
3213                  * the current locks, and try again.
3214                  */
3215                 return event;
3216
3217         case RINGBUF_TYPE_TIME_EXTEND:
3218                 /* Internal data, OK to advance */
3219                 rb_advance_reader(cpu_buffer);
3220                 goto again;
3221
3222         case RINGBUF_TYPE_TIME_STAMP:
3223                 /* FIXME: not implemented */
3224                 rb_advance_reader(cpu_buffer);
3225                 goto again;
3226
3227         case RINGBUF_TYPE_DATA:
3228                 if (ts) {
3229                         *ts = cpu_buffer->read_stamp + event->time_delta;
3230                         ring_buffer_normalize_time_stamp(cpu_buffer->buffer,
3231                                                          cpu_buffer->cpu, ts);
3232                 }
3233                 if (lost_events)
3234                         *lost_events = rb_lost_events(cpu_buffer);
3235                 return event;
3236
3237         default:
3238                 BUG();
3239         }
3240
3241         return NULL;
3242 }
3243 EXPORT_SYMBOL_GPL(ring_buffer_peek);
3244
3245 static struct ring_buffer_event *
3246 rb_iter_peek(struct ring_buffer_iter *iter, u64 *ts)
3247 {
3248         struct ring_buffer *buffer;
3249         struct ring_buffer_per_cpu *cpu_buffer;
3250         struct ring_buffer_event *event;
3251         int nr_loops = 0;
3252
3253         cpu_buffer = iter->cpu_buffer;
3254         buffer = cpu_buffer->buffer;
3255
3256         /*
3257          * Check if someone performed a consuming read to
3258          * the buffer. A consuming read invalidates the iterator
3259          * and we need to reset the iterator in this case.
3260          */
3261         if (unlikely(iter->cache_read != cpu_buffer->read ||
3262                      iter->cache_reader_page != cpu_buffer->reader_page))
3263                 rb_iter_reset(iter);
3264
3265  again:
3266         if (ring_buffer_iter_empty(iter))
3267                 return NULL;
3268
3269         /*
3270          * We repeat when a time extend is encountered.
3271          * Since the time extend is always attached to a data event,
3272          * we should never loop more than once.
3273          * (We never hit the following condition more than twice).
3274          */
3275         if (RB_WARN_ON(cpu_buffer, ++nr_loops > 2))
3276                 return NULL;
3277
3278         if (rb_per_cpu_empty(cpu_buffer))
3279                 return NULL;
3280
3281         if (iter->head >= local_read(&iter->head_page->page->commit)) {
3282                 rb_inc_iter(iter);
3283                 goto again;
3284         }
3285
3286         event = rb_iter_head_event(iter);
3287
3288         switch (event->type_len) {
3289         case RINGBUF_TYPE_PADDING:
3290                 if (rb_null_event(event)) {
3291                         rb_inc_iter(iter);
3292                         goto again;
3293                 }
3294                 rb_advance_iter(iter);
3295                 return event;
3296
3297         case RINGBUF_TYPE_TIME_EXTEND:
3298                 /* Internal data, OK to advance */
3299                 rb_advance_iter(iter);
3300                 goto again;
3301
3302         case RINGBUF_TYPE_TIME_STAMP:
3303                 /* FIXME: not implemented */
3304                 rb_advance_iter(iter);
3305                 goto again;
3306
3307         case RINGBUF_TYPE_DATA:
3308                 if (ts) {
3309                         *ts = iter->read_stamp + event->time_delta;
3310                         ring_buffer_normalize_time_stamp(buffer,
3311                                                          cpu_buffer->cpu, ts);
3312                 }
3313                 return event;
3314
3315         default:
3316                 BUG();
3317         }
3318
3319         return NULL;
3320 }
3321 EXPORT_SYMBOL_GPL(ring_buffer_iter_peek);
3322
3323 static inline int rb_ok_to_lock(void)
3324 {
3325         /*
3326          * If an NMI die dumps out the content of the ring buffer
3327          * do not grab locks. We also permanently disable the ring
3328          * buffer too. A one time deal is all you get from reading
3329          * the ring buffer from an NMI.
3330          */
3331         if (likely(!in_nmi()))
3332                 return 1;
3333
3334         tracing_off_permanent();
3335         return 0;
3336 }
3337
3338 /**
3339  * ring_buffer_peek - peek at the next event to be read
3340  * @buffer: The ring buffer to read
3341  * @cpu: The cpu to peak at
3342  * @ts: The timestamp counter of this event.
3343  * @lost_events: a variable to store if events were lost (may be NULL)
3344  *
3345  * This will return the event that will be read next, but does
3346  * not consume the data.
3347  */
3348 struct ring_buffer_event *
3349 ring_buffer_peek(struct ring_buffer *buffer, int cpu, u64 *ts,
3350                  unsigned long *lost_events)
3351 {
3352         struct ring_buffer_per_cpu *cpu_buffer = buffer->buffers[cpu];
3353         struct ring_buffer_event *event;
3354         unsigned long flags;
3355         int dolock;
3356
3357         if (!cpumask_test_cpu(cpu, buffer->cpumask))
3358                 return NULL;
3359
3360         dolock = rb_ok_to_lock();
3361  again:
3362         local_irq_save(flags);
3363         if (dolock)
3364                 raw_spin_lock(&cpu_buffer->reader_lock);
3365         event = rb_buffer_peek(cpu_buffer, ts, lost_events);
3366         if (event && event->type_len == RINGBUF_TYPE_PADDING)
3367                 rb_advance_reader(cpu_buffer);
3368         if (dolock)
3369                 raw_spin_unlock(&cpu_buffer->reader_lock);
3370         local_irq_restore(flags);
3371
3372         if (event && event->type_len == RINGBUF_TYPE_PADDING)
3373                 goto again;
3374
3375         return event;
3376 }
3377
3378 /**
3379  * ring_buffer_iter_peek - peek at the next event to be read
3380  * @iter: The ring buffer iterator
3381  * @ts: The timestamp counter of this event.
3382  *
3383  * This will return the event that will be read next, but does
3384  * not increment the iterator.
3385  */
3386 struct ring_buffer_event *
3387 ring_buffer_iter_peek(struct ring_buffer_iter *iter, u64 *ts)
3388 {
3389         struct ring_buffer_per_cpu *cpu_buffer = iter->cpu_buffer;
3390         struct ring_buffer_event *event;
3391         unsigned long flags;
3392
3393  again:
3394         raw_spin_lock_irqsave(&cpu_buffer->reader_lock, flags);
3395         event = rb_iter_peek(iter, ts);
3396         raw_spin_unlock_irqrestore(&cpu_buffer->reader_lock, flags);
3397
3398         if (event && event->type_len == RINGBUF_TYPE_PADDING)
3399                 goto again;
3400
3401         return event;
3402 }
3403
3404 /**
3405  * ring_buffer_consume - return an event and consume it
3406  * @buffer: The ring buffer to get the next event from
3407  * @cpu: the cpu to read the buffer from
3408  * @ts: a variable to store the timestamp (may be NULL)
3409  * @lost_events: a variable to store if events were lost (may be NULL)
3410  *
3411  * Returns the next event in the ring buffer, and that event is consumed.
3412  * Meaning, that sequential reads will keep returning a different event,
3413  * and eventually empty the ring buffer if the producer is slower.
3414  */
3415 struct ring_buffer_event *
3416 ring_buffer_consume(struct ring_buffer *buffer, int cpu, u64 *ts,
3417                     unsigned long *lost_events)
3418 {
3419         struct ring_buffer_per_cpu *cpu_buffer;
3420         struct ring_buffer_event *event = NULL;
3421         unsigned long flags;
3422         int dolock;
3423
3424         dolock = rb_ok_to_lock();
3425
3426  again:
3427         /* might be called in atomic */
3428         preempt_disable();
3429
3430         if (!cpumask_test_cpu(cpu, buffer->cpumask))
3431                 goto out;
3432
3433         cpu_buffer = buffer->buffers[cpu];
3434         local_irq_save(flags);
3435         if (dolock)
3436                 raw_spin_lock(&cpu_buffer->reader_lock);
3437
3438         event = rb_buffer_peek(cpu_buffer, ts, lost_events);
3439         if (event) {
3440                 cpu_buffer->lost_events = 0;
3441                 rb_advance_reader(cpu_buffer);
3442         }
3443
3444         if (dolock)
3445                 raw_spin_unlock(&cpu_buffer->reader_lock);
3446         local_irq_restore(flags);
3447
3448  out:
3449         preempt_enable();
3450
3451         if (event && event->type_len == RINGBUF_TYPE_PADDING)
3452                 goto again;
3453
3454         return event;
3455 }
3456 EXPORT_SYMBOL_GPL(ring_buffer_consume);
3457
3458 /**
3459  * ring_buffer_read_prepare - Prepare for a non consuming read of the buffer
3460  * @buffer: The ring buffer to read from
3461  * @cpu: The cpu buffer to iterate over
3462  *
3463  * This performs the initial preparations necessary to iterate
3464  * through the buffer.  Memory is allocated, buffer recording
3465  * is disabled, and the iterator pointer is returned to the caller.
3466  *
3467  * Disabling buffer recordng prevents the reading from being
3468  * corrupted. This is not a consuming read, so a producer is not
3469  * expected.
3470  *
3471  * After a sequence of ring_buffer_read_prepare calls, the user is
3472  * expected to make at least one call to ring_buffer_prepare_sync.
3473  * Afterwards, ring_buffer_read_start is invoked to get things going
3474  * for real.
3475  *
3476  * This overall must be paired with ring_buffer_finish.
3477  */
3478 struct ring_buffer_iter *
3479 ring_buffer_read_prepare(struct ring_buffer *buffer, int cpu)
3480 {
3481         struct ring_buffer_per_cpu *cpu_buffer;
3482         struct ring_buffer_iter *iter;
3483
3484         if (!cpumask_test_cpu(cpu, buffer->cpumask))
3485                 return NULL;
3486
3487         iter = kmalloc(sizeof(*iter), GFP_KERNEL);
3488         if (!iter)
3489                 return NULL;
3490
3491         cpu_buffer = buffer->buffers[cpu];
3492
3493         iter->cpu_buffer = cpu_buffer;
3494
3495         atomic_inc(&cpu_buffer->record_disabled);
3496
3497         return iter;
3498 }
3499 EXPORT_SYMBOL_GPL(ring_buffer_read_prepare);
3500
3501 /**
3502  * ring_buffer_read_prepare_sync - Synchronize a set of prepare calls
3503  *
3504  * All previously invoked ring_buffer_read_prepare calls to prepare
3505  * iterators will be synchronized.  Afterwards, read_buffer_read_start
3506  * calls on those iterators are allowed.
3507  */
3508 void
3509 ring_buffer_read_prepare_sync(void)
3510 {
3511         synchronize_sched();
3512 }
3513 EXPORT_SYMBOL_GPL(ring_buffer_read_prepare_sync);
3514
3515 /**
3516  * ring_buffer_read_start - start a non consuming read of the buffer
3517  * @iter: The iterator returned by ring_buffer_read_prepare
3518  *
3519  * This finalizes the startup of an iteration through the buffer.
3520  * The iterator comes from a call to ring_buffer_read_prepare and
3521  * an intervening ring_buffer_read_prepare_sync must have been
3522  * performed.
3523  *
3524  * Must be paired with ring_buffer_finish.
3525  */
3526 void
3527 ring_buffer_read_start(struct ring_buffer_iter *iter)
3528 {
3529         struct ring_buffer_per_cpu *cpu_buffer;
3530         unsigned long flags;
3531
3532         if (!iter)
3533                 return;
3534
3535         cpu_buffer = iter->cpu_buffer;
3536
3537         raw_spin_lock_irqsave(&cpu_buffer->reader_lock, flags);
3538         arch_spin_lock(&cpu_buffer->lock);
3539         rb_iter_reset(iter);
3540         arch_spin_unlock(&cpu_buffer->lock);
3541         raw_spin_unlock_irqrestore(&cpu_buffer->reader_lock, flags);
3542 }
3543 EXPORT_SYMBOL_GPL(ring_buffer_read_start);
3544
3545 /**
3546  * ring_buffer_finish - finish reading the iterator of the buffer
3547  * @iter: The iterator retrieved by ring_buffer_start
3548  *
3549  * This re-enables the recording to the buffer, and frees the
3550  * iterator.
3551  */
3552 void
3553 ring_buffer_read_finish(struct ring_buffer_iter *iter)
3554 {
3555         struct ring_buffer_per_cpu *cpu_buffer = iter->cpu_buffer;
3556
3557         atomic_dec(&cpu_buffer->record_disabled);
3558         kfree(iter);
3559 }
3560 EXPORT_SYMBOL_GPL(ring_buffer_read_finish);
3561
3562 /**
3563  * ring_buffer_read - read the next item in the ring buffer by the iterator
3564  * @iter: The ring buffer iterator
3565  * @ts: The time stamp of the event read.
3566  *
3567  * This reads the next event in the ring buffer and increments the iterator.
3568  */
3569 struct ring_buffer_event *
3570 ring_buffer_read(struct ring_buffer_iter *iter, u64 *ts)
3571 {
3572         struct ring_buffer_event *event;
3573         struct ring_buffer_per_cpu *cpu_buffer = iter->cpu_buffer;
3574         unsigned long flags;
3575
3576         raw_spin_lock_irqsave(&cpu_buffer->reader_lock, flags);
3577  again:
3578         event = rb_iter_peek(iter, ts);
3579         if (!event)
3580                 goto out;
3581
3582         if (event->type_len == RINGBUF_TYPE_PADDING)
3583                 goto again;
3584
3585         rb_advance_iter(iter);
3586  out:
3587         raw_spin_unlock_irqrestore(&cpu_buffer->reader_lock, flags);
3588
3589         return event;
3590 }
3591 EXPORT_SYMBOL_GPL(ring_buffer_read);
3592
3593 /**
3594  * ring_buffer_size - return the size of the ring buffer (in bytes)
3595  * @buffer: The ring buffer.
3596  */
3597 unsigned long ring_buffer_size(struct ring_buffer *buffer, int cpu)
3598 {
3599         /*
3600          * Earlier, this method returned
3601          *      BUF_PAGE_SIZE * buffer->nr_pages
3602          * Since the nr_pages field is now removed, we have converted this to
3603          * return the per cpu buffer value.
3604          */
3605         if (!cpumask_test_cpu(cpu, buffer->cpumask))
3606                 return 0;
3607
3608         return BUF_PAGE_SIZE * buffer->buffers[cpu]->nr_pages;
3609 }
3610 EXPORT_SYMBOL_GPL(ring_buffer_size);
3611
3612 static void
3613 rb_reset_cpu(struct ring_buffer_per_cpu *cpu_buffer)
3614 {
3615         rb_head_page_deactivate(cpu_buffer);
3616
3617         cpu_buffer->head_page
3618                 = list_entry(cpu_buffer->pages, struct buffer_page, list);
3619         local_set(&cpu_buffer->head_page->write, 0);
3620         local_set(&cpu_buffer->head_page->entries, 0);
3621         local_set(&cpu_buffer->head_page->page->commit, 0);
3622
3623         cpu_buffer->head_page->read = 0;
3624
3625         cpu_buffer->tail_page = cpu_buffer->head_page;
3626         cpu_buffer->commit_page = cpu_buffer->head_page;
3627
3628         INIT_LIST_HEAD(&cpu_buffer->reader_page->list);
3629         local_set(&cpu_buffer->reader_page->write, 0);
3630         local_set(&cpu_buffer->reader_page->entries, 0);
3631         local_set(&cpu_buffer->reader_page->page->commit, 0);
3632         cpu_buffer->reader_page->read = 0;
3633
3634         local_set(&cpu_buffer->commit_overrun, 0);
3635         local_set(&cpu_buffer->entries_bytes, 0);
3636         local_set(&cpu_buffer->overrun, 0);
3637         local_set(&cpu_buffer->entries, 0);
3638         local_set(&cpu_buffer->committing, 0);
3639         local_set(&cpu_buffer->commits, 0);
3640         cpu_buffer->read = 0;
3641         cpu_buffer->read_bytes = 0;
3642
3643         cpu_buffer->write_stamp = 0;
3644         cpu_buffer->read_stamp = 0;
3645
3646         cpu_buffer->lost_events = 0;
3647         cpu_buffer->last_overrun = 0;
3648
3649         rb_head_page_activate(cpu_buffer);
3650 }
3651
3652 /**
3653  * ring_buffer_reset_cpu - reset a ring buffer per CPU buffer
3654  * @buffer: The ring buffer to reset a per cpu buffer of
3655  * @cpu: The CPU buffer to be reset
3656  */
3657 void ring_buffer_reset_cpu(struct ring_buffer *buffer, int cpu)
3658 {
3659         struct ring_buffer_per_cpu *cpu_buffer = buffer->buffers[cpu];
3660         unsigned long flags;
3661
3662         if (!cpumask_test_cpu(cpu, buffer->cpumask))
3663                 return;
3664
3665         atomic_inc(&cpu_buffer->record_disabled);
3666
3667         raw_spin_lock_irqsave(&cpu_buffer->reader_lock, flags);
3668
3669         if (RB_WARN_ON(cpu_buffer, local_read(&cpu_buffer->committing)))
3670                 goto out;
3671
3672         arch_spin_lock(&cpu_buffer->lock);
3673
3674         rb_reset_cpu(cpu_buffer);
3675
3676         arch_spin_unlock(&cpu_buffer->lock);
3677
3678  out:
3679         raw_spin_unlock_irqrestore(&cpu_buffer->reader_lock, flags);
3680
3681         atomic_dec(&cpu_buffer->record_disabled);
3682 }
3683 EXPORT_SYMBOL_GPL(ring_buffer_reset_cpu);
3684
3685 /**
3686  * ring_buffer_reset - reset a ring buffer
3687  * @buffer: The ring buffer to reset all cpu buffers
3688  */
3689 void ring_buffer_reset(struct ring_buffer *buffer)
3690 {
3691         int cpu;
3692
3693         for_each_buffer_cpu(buffer, cpu)
3694                 ring_buffer_reset_cpu(buffer, cpu);
3695 }
3696 EXPORT_SYMBOL_GPL(ring_buffer_reset);
3697
3698 /**
3699  * rind_buffer_empty - is the ring buffer empty?
3700  * @buffer: The ring buffer to test
3701  */
3702 int ring_buffer_empty(struct ring_buffer *buffer)
3703 {
3704         struct ring_buffer_per_cpu *cpu_buffer;
3705         unsigned long flags;
3706         int dolock;
3707         int cpu;
3708         int ret;
3709
3710         dolock = rb_ok_to_lock();
3711
3712         /* yes this is racy, but if you don't like the race, lock the buffer */
3713         for_each_buffer_cpu(buffer, cpu) {
3714                 cpu_buffer = buffer->buffers[cpu];
3715                 local_irq_save(flags);
3716                 if (dolock)
3717                         raw_spin_lock(&cpu_buffer->reader_lock);
3718                 ret = rb_per_cpu_empty(cpu_buffer);
3719                 if (dolock)
3720                         raw_spin_unlock(&cpu_buffer->reader_lock);
3721                 local_irq_restore(flags);
3722
3723                 if (!ret)
3724                         return 0;
3725         }
3726
3727         return 1;
3728 }
3729 EXPORT_SYMBOL_GPL(ring_buffer_empty);
3730
3731 /**
3732  * ring_buffer_empty_cpu - is a cpu buffer of a ring buffer empty?
3733  * @buffer: The ring buffer
3734  * @cpu: The CPU buffer to test
3735  */
3736 int ring_buffer_empty_cpu(struct ring_buffer *buffer, int cpu)
3737 {
3738         struct ring_buffer_per_cpu *cpu_buffer;
3739         unsigned long flags;
3740         int dolock;
3741         int ret;
3742
3743         if (!cpumask_test_cpu(cpu, buffer->cpumask))
3744                 return 1;
3745
3746         dolock = rb_ok_to_lock();
3747
3748         cpu_buffer = buffer->buffers[cpu];
3749         local_irq_save(flags);
3750         if (dolock)
3751                 raw_spin_lock(&cpu_buffer->reader_lock);
3752         ret = rb_per_cpu_empty(cpu_buffer);
3753         if (dolock)
3754                 raw_spin_unlock(&cpu_buffer->reader_lock);
3755         local_irq_restore(flags);
3756
3757         return ret;
3758 }
3759 EXPORT_SYMBOL_GPL(ring_buffer_empty_cpu);
3760
3761 #ifdef CONFIG_RING_BUFFER_ALLOW_SWAP
3762 /**
3763  * ring_buffer_swap_cpu - swap a CPU buffer between two ring buffers
3764  * @buffer_a: One buffer to swap with
3765  * @buffer_b: The other buffer to swap with
3766  *
3767  * This function is useful for tracers that want to take a "snapshot"
3768  * of a CPU buffer and has another back up buffer lying around.
3769  * it is expected that the tracer handles the cpu buffer not being
3770  * used at the moment.
3771  */
3772 int ring_buffer_swap_cpu(struct ring_buffer *buffer_a,
3773                          struct ring_buffer *buffer_b, int cpu)
3774 {
3775         struct ring_buffer_per_cpu *cpu_buffer_a;
3776         struct ring_buffer_per_cpu *cpu_buffer_b;
3777         int ret = -EINVAL;
3778
3779         if (!cpumask_test_cpu(cpu, buffer_a->cpumask) ||
3780             !cpumask_test_cpu(cpu, buffer_b->cpumask))
3781                 goto out;
3782
3783         cpu_buffer_a = buffer_a->buffers[cpu];
3784         cpu_buffer_b = buffer_b->buffers[cpu];
3785
3786         /* At least make sure the two buffers are somewhat the same */
3787         if (cpu_buffer_a->nr_pages != cpu_buffer_b->nr_pages)
3788                 goto out;
3789
3790         ret = -EAGAIN;
3791
3792         if (ring_buffer_flags != RB_BUFFERS_ON)
3793                 goto out;
3794
3795         if (atomic_read(&buffer_a->record_disabled))
3796                 goto out;
3797
3798         if (atomic_read(&buffer_b->record_disabled))
3799                 goto out;
3800
3801         if (atomic_read(&cpu_buffer_a->record_disabled))
3802                 goto out;
3803
3804         if (atomic_read(&cpu_buffer_b->record_disabled))
3805                 goto out;
3806
3807         /*
3808          * We can't do a synchronize_sched here because this
3809          * function can be called in atomic context.
3810          * Normally this will be called from the same CPU as cpu.
3811          * If not it's up to the caller to protect this.
3812          */
3813         atomic_inc(&cpu_buffer_a->record_disabled);
3814         atomic_inc(&cpu_buffer_b->record_disabled);
3815
3816         ret = -EBUSY;
3817         if (local_read(&cpu_buffer_a->committing))
3818                 goto out_dec;
3819         if (local_read(&cpu_buffer_b->committing))
3820                 goto out_dec;
3821
3822         buffer_a->buffers[cpu] = cpu_buffer_b;
3823         buffer_b->buffers[cpu] = cpu_buffer_a;
3824
3825         cpu_buffer_b->buffer = buffer_a;
3826         cpu_buffer_a->buffer = buffer_b;
3827
3828         ret = 0;
3829
3830 out_dec:
3831         atomic_dec(&cpu_buffer_a->record_disabled);
3832         atomic_dec(&cpu_buffer_b->record_disabled);
3833 out:
3834         return ret;
3835 }
3836 EXPORT_SYMBOL_GPL(ring_buffer_swap_cpu);
3837 #endif /* CONFIG_RING_BUFFER_ALLOW_SWAP */
3838
3839 /**
3840  * ring_buffer_alloc_read_page - allocate a page to read from buffer
3841  * @buffer: the buffer to allocate for.
3842  *
3843  * This function is used in conjunction with ring_buffer_read_page.
3844  * When reading a full page from the ring buffer, these functions
3845  * can be used to speed up the process. The calling function should
3846  * allocate a few pages first with this function. Then when it
3847  * needs to get pages from the ring buffer, it passes the result
3848  * of this function into ring_buffer_read_page, which will swap
3849  * the page that was allocated, with the read page of the buffer.
3850  *
3851  * Returns:
3852  *  The page allocated, or NULL on error.
3853  */
3854 void *ring_buffer_alloc_read_page(struct ring_buffer *buffer, int cpu)
3855 {
3856         struct buffer_data_page *bpage;
3857         struct page *page;
3858
3859         page = alloc_pages_node(cpu_to_node(cpu),
3860                                 GFP_KERNEL | __GFP_NORETRY, 0);
3861         if (!page)
3862                 return NULL;
3863
3864         bpage = page_address(page);
3865
3866         rb_init_page(bpage);
3867
3868         return bpage;
3869 }
3870 EXPORT_SYMBOL_GPL(ring_buffer_alloc_read_page);
3871
3872 /**
3873  * ring_buffer_free_read_page - free an allocated read page
3874  * @buffer: the buffer the page was allocate for
3875  * @data: the page to free
3876  *
3877  * Free a page allocated from ring_buffer_alloc_read_page.
3878  */
3879 void ring_buffer_free_read_page(struct ring_buffer *buffer, void *data)
3880 {
3881         free_page((unsigned long)data);
3882 }
3883 EXPORT_SYMBOL_GPL(ring_buffer_free_read_page);
3884
3885 /**
3886  * ring_buffer_read_page - extract a page from the ring buffer
3887  * @buffer: buffer to extract from
3888  * @data_page: the page to use allocated from ring_buffer_alloc_read_page
3889  * @len: amount to extract
3890  * @cpu: the cpu of the buffer to extract
3891  * @full: should the extraction only happen when the page is full.
3892  *
3893  * This function will pull out a page from the ring buffer and consume it.
3894  * @data_page must be the address of the variable that was returned
3895  * from ring_buffer_alloc_read_page. This is because the page might be used
3896  * to swap with a page in the ring buffer.
3897  *
3898  * for example:
3899  *      rpage = ring_buffer_alloc_read_page(buffer);
3900  *      if (!rpage)
3901  *              return error;
3902  *      ret = ring_buffer_read_page(buffer, &rpage, len, cpu, 0);
3903  *      if (ret >= 0)
3904  *              process_page(rpage, ret);
3905  *
3906  * When @full is set, the function will not return true unless
3907  * the writer is off the reader page.
3908  *
3909  * Note: it is up to the calling functions to handle sleeps and wakeups.
3910  *  The ring buffer can be used anywhere in the kernel and can not
3911  *  blindly call wake_up. The layer that uses the ring buffer must be
3912  *  responsible for that.
3913  *
3914  * Returns:
3915  *  >=0 if data has been transferred, returns the offset of consumed data.
3916  *  <0 if no data has been transferred.
3917  */
3918 int ring_buffer_read_page(struct ring_buffer *buffer,
3919                           void **data_page, size_t len, int cpu, int full)
3920 {
3921         struct ring_buffer_per_cpu *cpu_buffer = buffer->buffers[cpu];
3922         struct ring_buffer_event *event;
3923         struct buffer_data_page *bpage;
3924         struct buffer_page *reader;
3925         unsigned long missed_events;
3926         unsigned long flags;
3927         unsigned int commit;
3928         unsigned int read;
3929         u64 save_timestamp;
3930         int ret = -1;
3931
3932         if (!cpumask_test_cpu(cpu, buffer->cpumask))
3933                 goto out;
3934
3935         /*
3936          * If len is not big enough to hold the page header, then
3937          * we can not copy anything.
3938          */
3939         if (len <= BUF_PAGE_HDR_SIZE)
3940                 goto out;
3941
3942         len -= BUF_PAGE_HDR_SIZE;
3943
3944         if (!data_page)
3945                 goto out;
3946
3947         bpage = *data_page;
3948         if (!bpage)
3949                 goto out;
3950
3951         raw_spin_lock_irqsave(&cpu_buffer->reader_lock, flags);
3952
3953         reader = rb_get_reader_page(cpu_buffer);
3954         if (!reader)
3955                 goto out_unlock;
3956
3957         event = rb_reader_event(cpu_buffer);
3958
3959         read = reader->read;
3960         commit = rb_page_commit(reader);
3961
3962         /* Check if any events were dropped */
3963         missed_events = cpu_buffer->lost_events;
3964
3965         /*
3966          * If this page has been partially read or
3967          * if len is not big enough to read the rest of the page or
3968          * a writer is still on the page, then
3969          * we must copy the data from the page to the buffer.
3970          * Otherwise, we can simply swap the page with the one passed in.
3971          */
3972         if (read || (len < (commit - read)) ||
3973             cpu_buffer->reader_page == cpu_buffer->commit_page) {
3974                 struct buffer_data_page *rpage = cpu_buffer->reader_page->page;
3975                 unsigned int rpos = read;
3976                 unsigned int pos = 0;
3977                 unsigned int size;
3978
3979                 if (full)
3980                         goto out_unlock;
3981
3982                 if (len > (commit - read))
3983                         len = (commit - read);
3984
3985                 /* Always keep the time extend and data together */
3986                 size = rb_event_ts_length(event);
3987
3988                 if (len < size)
3989                         goto out_unlock;
3990
3991                 /* save the current timestamp, since the user will need it */
3992                 save_timestamp = cpu_buffer->read_stamp;
3993
3994                 /* Need to copy one event at a time */
3995                 do {
3996                         /* We need the size of one event, because
3997                          * rb_advance_reader only advances by one event,
3998                          * whereas rb_event_ts_length may include the size of
3999                          * one or two events.
4000                          * We have already ensured there's enough space if this
4001                          * is a time extend. */
4002                         size = rb_event_length(event);
4003                         memcpy(bpage->data + pos, rpage->data + rpos, size);
4004
4005                         len -= size;
4006
4007                         rb_advance_reader(cpu_buffer);
4008                         rpos = reader->read;
4009                         pos += size;
4010
4011                         if (rpos >= commit)
4012                                 break;
4013
4014                         event = rb_reader_event(cpu_buffer);
4015                         /* Always keep the time extend and data together */
4016                         size = rb_event_ts_length(event);
4017                 } while (len >= size);
4018
4019                 /* update bpage */
4020                 local_set(&bpage->commit, pos);
4021                 bpage->time_stamp = save_timestamp;
4022
4023                 /* we copied everything to the beginning */
4024                 read = 0;
4025         } else {
4026                 /* update the entry counter */
4027                 cpu_buffer->read += rb_page_entries(reader);
4028                 cpu_buffer->read_bytes += BUF_PAGE_SIZE;
4029
4030                 /* swap the pages */
4031                 rb_init_page(bpage);
4032                 bpage = reader->page;
4033                 reader->page = *data_page;
4034                 local_set(&reader->write, 0);
4035                 local_set(&reader->entries, 0);
4036                 reader->read = 0;
4037                 *data_page = bpage;
4038
4039                 /*
4040                  * Use the real_end for the data size,
4041                  * This gives us a chance to store the lost events
4042                  * on the page.
4043                  */
4044                 if (reader->real_end)
4045                         local_set(&bpage->commit, reader->real_end);
4046         }
4047         ret = read;
4048
4049         cpu_buffer->lost_events = 0;
4050
4051         commit = local_read(&bpage->commit);
4052         /*
4053          * Set a flag in the commit field if we lost events
4054          */
4055         if (missed_events) {
4056                 /* If there is room at the end of the page to save the
4057                  * missed events, then record it there.
4058                  */
4059                 if (BUF_PAGE_SIZE - commit >= sizeof(missed_events)) {
4060                         memcpy(&bpage->data[commit], &missed_events,
4061                                sizeof(missed_events));
4062                         local_add(RB_MISSED_STORED, &bpage->commit);
4063                         commit += sizeof(missed_events);
4064                 }
4065                 local_add(RB_MISSED_EVENTS, &bpage->commit);
4066         }
4067
4068         /*
4069          * This page may be off to user land. Zero it out here.
4070          */
4071         if (commit < BUF_PAGE_SIZE)
4072                 memset(&bpage->data[commit], 0, BUF_PAGE_SIZE - commit);
4073
4074  out_unlock:
4075         raw_spin_unlock_irqrestore(&cpu_buffer->reader_lock, flags);
4076
4077  out:
4078         return ret;
4079 }
4080 EXPORT_SYMBOL_GPL(ring_buffer_read_page);
4081
4082 #ifdef CONFIG_HOTPLUG_CPU
4083 static int rb_cpu_notify(struct notifier_block *self,
4084                          unsigned long action, void *hcpu)
4085 {
4086         struct ring_buffer *buffer =
4087                 container_of(self, struct ring_buffer, cpu_notify);
4088         long cpu = (long)hcpu;
4089         int cpu_i, nr_pages_same;
4090         unsigned int nr_pages;
4091
4092         switch (action) {
4093         case CPU_UP_PREPARE:
4094         case CPU_UP_PREPARE_FROZEN:
4095                 if (cpumask_test_cpu(cpu, buffer->cpumask))
4096                         return NOTIFY_OK;
4097
4098                 nr_pages = 0;
4099                 nr_pages_same = 1;
4100                 /* check if all cpu sizes are same */
4101                 for_each_buffer_cpu(buffer, cpu_i) {
4102                         /* fill in the size from first enabled cpu */
4103                         if (nr_pages == 0)
4104                                 nr_pages = buffer->buffers[cpu_i]->nr_pages;
4105                         if (nr_pages != buffer->buffers[cpu_i]->nr_pages) {
4106                                 nr_pages_same = 0;
4107                                 break;
4108                         }
4109                 }
4110                 /* allocate minimum pages, user can later expand it */
4111                 if (!nr_pages_same)
4112                         nr_pages = 2;
4113                 buffer->buffers[cpu] =
4114                         rb_allocate_cpu_buffer(buffer, nr_pages, cpu);
4115                 if (!buffer->buffers[cpu]) {
4116                         WARN(1, "failed to allocate ring buffer on CPU %ld\n",
4117                              cpu);
4118                         return NOTIFY_OK;
4119                 }
4120                 smp_wmb();
4121                 cpumask_set_cpu(cpu, buffer->cpumask);
4122                 break;
4123         case CPU_DOWN_PREPARE:
4124         case CPU_DOWN_PREPARE_FROZEN:
4125                 /*
4126                  * Do nothing.
4127                  *  If we were to free the buffer, then the user would
4128                  *  lose any trace that was in the buffer.
4129                  */
4130                 break;
4131         default:
4132                 break;
4133         }
4134         return NOTIFY_OK;
4135 }
4136 #endif