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