linux-kernel.vger.kernel.org archive mirror
 help / color / mirror / Atom feed
* [PATCH 0/3] [GIT PULL][for 2.6.32] lockless ring buffer
@ 2009-06-10 19:53 Steven Rostedt
  2009-06-10 19:53 ` [PATCH 1/3] ring-buffer: make the buffer a true circular link list Steven Rostedt
                   ` (2 more replies)
  0 siblings, 3 replies; 29+ messages in thread
From: Steven Rostedt @ 2009-06-10 19:53 UTC (permalink / raw)
  To: linux-kernel
  Cc: Ingo Molnar, Andrew Morton, Thomas Gleixner, Peter Zijlstra,
	Frederic Weisbecker, Theodore Tso, Arnaldo Carvalho de Melo,
	Mathieu Desnoyers, Lai Jiangshan, Martin J. Bligh,
	Christoph Hellwig, Li Zefan, Huang Ying, H. Peter Anvin,
	Hidetoshi Seto, Masami Hiramatsu

Ingo,

Here it is, the long awaited lockless ring buffer algorithm.

Please pull the latest tip/tracing/ring-buffer tree, which can be found at:

  git://git.kernel.org/pub/scm/linux/kernel/git/rostedt/linux-2.6-trace.git
tip/tracing/ring-buffer


Steven Rostedt (3):
      ring-buffer: make the buffer a true circular link list
      ring-buffer: make lockless
      ring-buffer: add design document

----
 Documentation/trace/ring-buffer-design.txt |  949 +++++++++++++++++++++++++++
 include/linux/ring_buffer.h                |    1 -
 kernel/trace/ring_buffer.c                 |  951 +++++++++++++++++++++++-----
 kernel/trace/trace.c                       |    3 -
 4 files changed, 1735 insertions(+), 169 deletions(-)
-- 

^ permalink raw reply	[flat|nested] 29+ messages in thread

* [PATCH 1/3] ring-buffer: make the buffer a true circular link list
  2009-06-10 19:53 [PATCH 0/3] [GIT PULL][for 2.6.32] lockless ring buffer Steven Rostedt
@ 2009-06-10 19:53 ` Steven Rostedt
  2009-06-11  1:12   ` Lai Jiangshan
  2009-06-10 19:53 ` [PATCH 2/3] ring-buffer: make lockless Steven Rostedt
  2009-06-10 19:53 ` [PATCH 3/3] ring-buffer: add design document Steven Rostedt
  2 siblings, 1 reply; 29+ messages in thread
From: Steven Rostedt @ 2009-06-10 19:53 UTC (permalink / raw)
  To: linux-kernel
  Cc: Ingo Molnar, Andrew Morton, Thomas Gleixner, Peter Zijlstra,
	Frederic Weisbecker, Theodore Tso, Arnaldo Carvalho de Melo,
	Mathieu Desnoyers, Lai Jiangshan, Martin J. Bligh,
	Christoph Hellwig, Li Zefan, Huang Ying, H. Peter Anvin,
	Hidetoshi Seto, Masami Hiramatsu, Steven Rostedt

[-- Attachment #1: 0001-ring-buffer-make-the-buffer-a-true-circular-link-lis.patch --]
[-- Type: text/plain, Size: 6324 bytes --]

From: Steven Rostedt <srostedt@redhat.com>

This patch changes the ring buffer data pages from using a link list
head pointer, to making each buffer page point to another buffer page
and never back to a "head".

This makes the handling of the ring buffer less complex, since the
traversing of the ring buffer pages no longer needs to account for the
head pointer.

This change also is needed to make the ring buffer lockless.

[ Impact: simplify the ring buffer to help make it lockless ]

Signed-off-by: Steven Rostedt <srostedt@redhat.com>
---
 kernel/trace/ring_buffer.c |   54 ++++++++++++++++++++++++++++++-------------
 1 files changed, 37 insertions(+), 17 deletions(-)

diff --git a/kernel/trace/ring_buffer.c b/kernel/trace/ring_buffer.c
index 2e642b2..d1edd63 100644
--- a/kernel/trace/ring_buffer.c
+++ b/kernel/trace/ring_buffer.c
@@ -404,7 +404,7 @@ struct ring_buffer_per_cpu {
 	spinlock_t			reader_lock; /* serialize readers */
 	raw_spinlock_t			lock;
 	struct lock_class_key		lock_key;
-	struct list_head		pages;
+	struct list_head		*pages;
 	struct buffer_page		*head_page;	/* read from head */
 	struct buffer_page		*tail_page;	/* write to tail */
 	struct buffer_page		*commit_page;	/* committed pages */
@@ -494,7 +494,7 @@ EXPORT_SYMBOL_GPL(ring_buffer_normalize_time_stamp);
  */
 static int rb_check_pages(struct ring_buffer_per_cpu *cpu_buffer)
 {
-	struct list_head *head = &cpu_buffer->pages;
+	struct list_head *head = cpu_buffer->pages;
 	struct buffer_page *bpage, *tmp;
 
 	if (RB_WARN_ON(cpu_buffer, head->next->prev != head))
@@ -517,12 +517,13 @@ static int rb_check_pages(struct ring_buffer_per_cpu *cpu_buffer)
 static int rb_allocate_pages(struct ring_buffer_per_cpu *cpu_buffer,
 			     unsigned nr_pages)
 {
-	struct list_head *head = &cpu_buffer->pages;
 	struct buffer_page *bpage, *tmp;
 	unsigned long addr;
 	LIST_HEAD(pages);
 	unsigned i;
 
+	WARN_ON(!nr_pages);
+
 	for (i = 0; i < nr_pages; i++) {
 		bpage = kzalloc_node(ALIGN(sizeof(*bpage), cache_line_size()),
 				    GFP_KERNEL, cpu_to_node(cpu_buffer->cpu));
@@ -537,7 +538,18 @@ static int rb_allocate_pages(struct ring_buffer_per_cpu *cpu_buffer,
 		rb_init_page(bpage->page);
 	}
 
-	list_splice(&pages, head);
+	/*
+	 * The ring buffer page list is a circular list that does not
+	 * start and end with a list head. All page list items point to
+	 * other pages. Remove one of the pages, init its list head,
+	 * and use list splice to move the rest of the pages to it.
+	 */
+	bpage = list_entry(pages.next, struct buffer_page, list);
+	list_del_init(&bpage->list);
+	cpu_buffer->pages = &bpage->list;
+
+	list_splice(&pages, cpu_buffer->pages);
+
 
 	rb_check_pages(cpu_buffer);
 
@@ -569,7 +581,6 @@ rb_allocate_cpu_buffer(struct ring_buffer *buffer, int cpu)
 	spin_lock_init(&cpu_buffer->reader_lock);
 	lockdep_set_class(&cpu_buffer->reader_lock, buffer->reader_lock_key);
 	cpu_buffer->lock = (raw_spinlock_t)__RAW_SPIN_LOCK_UNLOCKED;
-	INIT_LIST_HEAD(&cpu_buffer->pages);
 
 	bpage = kzalloc_node(ALIGN(sizeof(*bpage), cache_line_size()),
 			    GFP_KERNEL, cpu_to_node(cpu));
@@ -590,7 +601,7 @@ rb_allocate_cpu_buffer(struct ring_buffer *buffer, int cpu)
 		goto fail_free_reader;
 
 	cpu_buffer->head_page
-		= list_entry(cpu_buffer->pages.next, struct buffer_page, list);
+		= list_entry(cpu_buffer->pages, struct buffer_page, list);
 	cpu_buffer->tail_page = cpu_buffer->commit_page = cpu_buffer->head_page;
 
 	return cpu_buffer;
@@ -605,15 +616,20 @@ rb_allocate_cpu_buffer(struct ring_buffer *buffer, int cpu)
 
 static void rb_free_cpu_buffer(struct ring_buffer_per_cpu *cpu_buffer)
 {
-	struct list_head *head = &cpu_buffer->pages;
+	struct list_head *head = cpu_buffer->pages;
 	struct buffer_page *bpage, *tmp;
 
 	free_buffer_page(cpu_buffer->reader_page);
 
-	list_for_each_entry_safe(bpage, tmp, head, list) {
-		list_del_init(&bpage->list);
+	if (head) {
+		list_for_each_entry_safe(bpage, tmp, head, list) {
+			list_del_init(&bpage->list);
+			free_buffer_page(bpage);
+		}
+		bpage = list_entry(head, struct buffer_page, list);
 		free_buffer_page(bpage);
 	}
+
 	kfree(cpu_buffer);
 }
 
@@ -767,14 +783,14 @@ rb_remove_pages(struct ring_buffer_per_cpu *cpu_buffer, unsigned nr_pages)
 	synchronize_sched();
 
 	for (i = 0; i < nr_pages; i++) {
-		if (RB_WARN_ON(cpu_buffer, list_empty(&cpu_buffer->pages)))
+		if (RB_WARN_ON(cpu_buffer, list_empty(cpu_buffer->pages)))
 			return;
-		p = cpu_buffer->pages.next;
+		p = cpu_buffer->pages->next;
 		bpage = list_entry(p, struct buffer_page, list);
 		list_del_init(&bpage->list);
 		free_buffer_page(bpage);
 	}
-	if (RB_WARN_ON(cpu_buffer, list_empty(&cpu_buffer->pages)))
+	if (RB_WARN_ON(cpu_buffer, list_empty(cpu_buffer->pages)))
 		return;
 
 	rb_reset_cpu(cpu_buffer);
@@ -802,7 +818,7 @@ rb_insert_pages(struct ring_buffer_per_cpu *cpu_buffer,
 		p = pages->next;
 		bpage = list_entry(p, struct buffer_page, list);
 		list_del_init(&bpage->list);
-		list_add_tail(&bpage->list, &cpu_buffer->pages);
+		list_add_tail(&bpage->list, cpu_buffer->pages);
 	}
 	rb_reset_cpu(cpu_buffer);
 
@@ -999,9 +1015,6 @@ static inline void rb_inc_page(struct ring_buffer_per_cpu *cpu_buffer,
 {
 	struct list_head *p = (*bpage)->list.next;
 
-	if (p == &cpu_buffer->pages)
-		p = p->next;
-
 	*bpage = list_entry(p, struct buffer_page, list);
 }
 
@@ -2212,6 +2225,13 @@ rb_get_reader_page(struct ring_buffer_per_cpu *cpu_buffer)
 	cpu_buffer->reader_page->list.next = reader->list.next;
 	cpu_buffer->reader_page->list.prev = reader->list.prev;
 
+	/*
+	 * cpu_buffer->pages just needs to point to the buffer, it
+	 *  has no specific buffer page to point to. Lets move it out
+	 *  of our way so we don't accidently swap it.
+	 */
+	cpu_buffer->pages = reader->list.prev;
+
 	local_set(&cpu_buffer->reader_page->write, 0);
 	local_set(&cpu_buffer->reader_page->entries, 0);
 	local_set(&cpu_buffer->reader_page->page->commit, 0);
@@ -2656,7 +2676,7 @@ static void
 rb_reset_cpu(struct ring_buffer_per_cpu *cpu_buffer)
 {
 	cpu_buffer->head_page
-		= list_entry(cpu_buffer->pages.next, struct buffer_page, list);
+		= list_entry(cpu_buffer->pages, struct buffer_page, list);
 	local_set(&cpu_buffer->head_page->write, 0);
 	local_set(&cpu_buffer->head_page->entries, 0);
 	local_set(&cpu_buffer->head_page->page->commit, 0);
-- 
1.6.3.1

-- 

^ permalink raw reply related	[flat|nested] 29+ messages in thread

* [PATCH 2/3] ring-buffer: make lockless
  2009-06-10 19:53 [PATCH 0/3] [GIT PULL][for 2.6.32] lockless ring buffer Steven Rostedt
  2009-06-10 19:53 ` [PATCH 1/3] ring-buffer: make the buffer a true circular link list Steven Rostedt
@ 2009-06-10 19:53 ` Steven Rostedt
  2009-06-10 19:53 ` [PATCH 3/3] ring-buffer: add design document Steven Rostedt
  2 siblings, 0 replies; 29+ messages in thread
From: Steven Rostedt @ 2009-06-10 19:53 UTC (permalink / raw)
  To: linux-kernel
  Cc: Ingo Molnar, Andrew Morton, Thomas Gleixner, Peter Zijlstra,
	Frederic Weisbecker, Theodore Tso, Arnaldo Carvalho de Melo,
	Mathieu Desnoyers, Lai Jiangshan, Martin J. Bligh,
	Christoph Hellwig, Li Zefan, Huang Ying, H. Peter Anvin,
	Hidetoshi Seto, Masami Hiramatsu, Steven Rostedt

[-- Attachment #1: 0002-ring-buffer-make-lockless.patch --]
[-- Type: text/plain, Size: 40876 bytes --]

From: Steven Rostedt <srostedt@redhat.com>

This patch converts the ring buffers into a completely lockless
buffer recording system. The read side still takes locks since
we still serialize readers. But the writers are the ones that
must be lockless (those can happen in NMIs).

The main change is to the "head_page" pointer. We write to the
tail, and read from the head. The "head_page" pointer in the cpu
buffer is now just a reference to where to look. The real head
page is now kept in the head_page->list->prev->next pointer.
That is, in the list head of the previous page we set flags.

The list pages are allocated to be aligned such that the lowest
significant bits are always zero pointing to the list. This gives
us play to put in flags to their pointers.

bit 0: set when the page is a head page
bit 1: set when the writer is moving the page (for overwrite mode)

cmpxchg is used to update the pointer.

When the writer wraps the buffer and the tail meets the head,
in overwrite mode, the writer must move the head page forward.
It first uses cmpxchg to change the pointer flag from 1 to 2.
Once this is done, the reader on another CPU will not take the
page from the buffer.

The writers need to protect against interrupts (we don't bother with
disabling interrupts because NMIs are allowed to write too).

After the writer sets the pointer flag to 2, it takes care to
manage interrupts coming in. This is discribed in detail within the
comments of the code.

[ Impact: lock free writing to the ring buffer ]

Signed-off-by: Steven Rostedt <srostedt@redhat.com>
---
 include/linux/ring_buffer.h |    1 -
 kernel/trace/ring_buffer.c  |  897 ++++++++++++++++++++++++++++++++++++-------
 kernel/trace/trace.c        |    3 -
 3 files changed, 749 insertions(+), 152 deletions(-)

diff --git a/include/linux/ring_buffer.h b/include/linux/ring_buffer.h
index 8670f15..d65885b 100644
--- a/include/linux/ring_buffer.h
+++ b/include/linux/ring_buffer.h
@@ -166,7 +166,6 @@ unsigned long ring_buffer_overruns(struct ring_buffer *buffer);
 unsigned long ring_buffer_entries_cpu(struct ring_buffer *buffer, int cpu);
 unsigned long ring_buffer_overrun_cpu(struct ring_buffer *buffer, int cpu);
 unsigned long ring_buffer_commit_overrun_cpu(struct ring_buffer *buffer, int cpu);
-unsigned long ring_buffer_nmi_dropped_cpu(struct ring_buffer *buffer, int cpu);
 
 u64 ring_buffer_time_stamp(struct ring_buffer *buffer, int cpu);
 void ring_buffer_normalize_time_stamp(struct ring_buffer *buffer,
diff --git a/kernel/trace/ring_buffer.c b/kernel/trace/ring_buffer.c
index d1edd63..c93397a 100644
--- a/kernel/trace/ring_buffer.c
+++ b/kernel/trace/ring_buffer.c
@@ -320,6 +320,14 @@ struct buffer_data_page {
 	unsigned char	 data[];	/* data of buffer page */
 };
 
+/*
+ * Note, the buffer_page list must be first. The buffer pages
+ * are allocated in cache lines, which means that each buffer
+ * page will be at the beginning of a cache line, and thus
+ * the least significant bits will be zero. We use this to
+ * add flags in the list struct pointers, to make the ring buffer
+ * lockless.
+ */
 struct buffer_page {
 	struct list_head list;		/* list of buffer pages */
 	local_t		 write;		/* index for next write */
@@ -328,6 +336,21 @@ struct buffer_page {
 	struct buffer_data_page *page;	/* Actual data page */
 };
 
+/*
+ * The buffer page counters, write and entries, must be reset
+ * atomically when crossing page boundaries. To synchronize this
+ * update, two counters are inserted into the number. One is
+ * the actual counter for the write position or count on the page.
+ *
+ * The other is a counter of updaters. Before an update happens
+ * the update partition of the counter is incremented. This will
+ * allow the updater to update the counter atomically.
+ *
+ * The counter is 20 bits, and the state data is 12.
+ */
+#define RB_WRITE_MASK		0xfffff
+#define RB_WRITE_INTCNT		(1 << 20)
+
 static void rb_init_page(struct buffer_data_page *bpage)
 {
 	local_set(&bpage->commit, 0);
@@ -401,7 +424,7 @@ int ring_buffer_print_page_header(struct trace_seq *s)
 struct ring_buffer_per_cpu {
 	int				cpu;
 	struct ring_buffer		*buffer;
-	spinlock_t			reader_lock; /* serialize readers */
+	spinlock_t			reader_lock;	/* serialize readers */
 	raw_spinlock_t			lock;
 	struct lock_class_key		lock_key;
 	struct list_head		*pages;
@@ -409,11 +432,10 @@ struct ring_buffer_per_cpu {
 	struct buffer_page		*tail_page;	/* write to tail */
 	struct buffer_page		*commit_page;	/* committed pages */
 	struct buffer_page		*reader_page;
-	unsigned long			nmi_dropped;
-	unsigned long			commit_overrun;
-	unsigned long			overrun;
-	unsigned long			read;
+	local_t				commit_overrun;
+	local_t				overrun;
 	local_t				entries;
+	unsigned long			read;
 	u64				write_stamp;
 	u64				read_stamp;
 	atomic_t			record_disabled;
@@ -485,6 +507,392 @@ void ring_buffer_normalize_time_stamp(struct ring_buffer *buffer,
 }
 EXPORT_SYMBOL_GPL(ring_buffer_normalize_time_stamp);
 
+/*
+ * Making the ring buffer lockless makes things tricky.
+ * Although writes only happen on the CPU that they are on,
+ * and they only need to worry about interrupts. Reads can
+ * happen on any CPU.
+ *
+ * The reader page is always off the ring buffer, but when the
+ * reader finishes with a page, it needs to swap its page with
+ * a new one from the buffer. The reader needs to take from
+ * the head (writes go to the tail). But if a writer is in overwrite
+ * mode and wraps, it must push the head page forward.
+ *
+ * Here lies the problem.
+ *
+ * The reader must be careful to replace only the head page, and
+ * not another one. As described at the top of the file in the
+ * ASCII art, the reader sets its old page to point to the next
+ * page after head. It then sets the page after head to point to
+ * the old reader page. But if the writer moves the head page
+ * during this operation, the reader could end up with the tail.
+ *
+ * We use cmpxchg to help prevent this race. We also do something
+ * special with the page before head. We set the LSB to 1.
+ *
+ * When the writer must push the page forward, it will clear the
+ * bit that points to the head page, move the head, and then set
+ * the bit that points to the new head page.
+ *
+ * We also don't want an interrupt coming in and moving the head
+ * page on another writer. Thus we use the second LSB to catch
+ * that too. Thus:
+ *
+ * head->list->prev->next        bit 1          bit 0
+ *                              -------        -------
+ * Normal page                     0              0
+ * Points to head page             0              1
+ * New head page                   1              0
+ *
+ * Note we can not trust the prev pointer of the head page, because:
+ *
+ * +----+       +-----+        +-----+
+ * |    |------>|  T  |---X--->|  N  |
+ * |    |<------|     |        |     |
+ * +----+       +-----+        +-----+
+ *   ^                           ^ |
+ *   |          +-----+          | |
+ *   +----------|  R  |----------+ |
+ *              |     |<-----------+
+ *              +-----+
+ *
+ * Key:  ---X-->  HEAD flag set in pointer
+ *         T      Tail page
+ *         R      Reader page
+ *         N      Next page
+ *
+ * (see __rb_reserve_next() to see where this happens)
+ *
+ *  What the above shows is that the reader just swapped out
+ *  the reader page with a page in the buffer, but before it
+ *  could make the new header point back to the new page added
+ *  it was preempted by a writer. The writer moved forward onto
+ *  the new page added by the reader and is about to move forward
+ *  again.
+ *
+ *  You can see, it is legitimate for the previous pointer of
+ *  the head (or any page) not to point back to itself. But only
+ *  temporarially.
+ */
+
+#define RB_PAGE_NORMAL		0UL
+#define RB_PAGE_HEAD		1UL
+#define RB_PAGE_UPDATE		2UL
+
+
+#define RB_FLAG_MASK		3UL
+
+/* PAGE_MOVED is not part of the mask */
+#define RB_PAGE_MOVED		4UL
+
+/*
+ * rb_list_head - remove any bit
+ */
+static struct list_head *rb_list_head(struct list_head *list)
+{
+	unsigned long val = (unsigned long)list;
+
+	return (struct list_head *)(val & ~RB_FLAG_MASK);
+}
+
+/*
+ * rb_is_head_page - test if the give page is the head page
+ *
+ * Because the reader may move the head_page pointer, we can
+ * not trust what the head page is (it may be pointing to
+ * the reader page). But if the next page is a header page,
+ * its flags will be non zero.
+ */
+static int inline
+rb_is_head_page(struct ring_buffer_per_cpu *cpu_buffer,
+		struct buffer_page *page, struct list_head *list)
+{
+	unsigned long val;
+
+	val = (unsigned long)list->next;
+
+	if ((val & ~RB_FLAG_MASK) != (unsigned long)&page->list)
+		return RB_PAGE_MOVED;
+
+	return val & RB_FLAG_MASK;
+}
+
+/*
+ * rb_is_reader_page
+ *
+ * The unique thing about the reader page, is that, if the
+ * writer is ever on it, the previous pointer never points
+ * back to the reader page.
+ */
+static int rb_is_reader_page(struct buffer_page *page)
+{
+	struct list_head *list = page->list.prev;
+
+	return list->next != &page->list;
+}
+
+/*
+ * rb_set_list_to_head - set a list_head to be pointing to head.
+ */
+static void rb_set_list_to_head(struct ring_buffer_per_cpu *cpu_buffer,
+				struct list_head *list)
+{
+	unsigned long *ptr;
+
+	ptr = (unsigned long *)&list->next;
+	*ptr |= RB_PAGE_HEAD;
+	*ptr &= ~RB_PAGE_UPDATE;
+}
+
+/*
+ * rb_head_page_activate - sets up head page
+ */
+static void rb_head_page_activate(struct ring_buffer_per_cpu *cpu_buffer)
+{
+	struct buffer_page *head;
+
+	head = cpu_buffer->head_page;
+	if (!head)
+		return;
+
+	/*
+	 * Set the previous list pointer to have the HEAD flag.
+	 */
+	rb_set_list_to_head(cpu_buffer, head->list.prev);
+}
+
+static void rb_list_head_clear(struct list_head *list)
+{
+	unsigned long *ptr = (unsigned long *)&list->next;
+
+	*ptr &= ~RB_FLAG_MASK;
+}
+
+/*
+ * rb_head_page_dactivate - clears head page ptr (for free list)
+ */
+static void
+rb_head_page_deactivate(struct ring_buffer_per_cpu *cpu_buffer)
+{
+	struct list_head *hd;
+
+	/* Go through the whole list and clear any pointers found. */
+	rb_list_head_clear(cpu_buffer->pages);
+
+	list_for_each(hd, cpu_buffer->pages)
+		rb_list_head_clear(hd);
+}
+
+static int rb_head_page_set(struct ring_buffer_per_cpu *cpu_buffer,
+			    struct buffer_page *head,
+			    struct buffer_page *prev,
+			    int old_flag, int new_flag)
+{
+	struct list_head *list;
+	unsigned long val = (unsigned long)&head->list;
+	unsigned long ret;
+
+	list = &prev->list;
+
+	val &= ~RB_FLAG_MASK;
+
+	ret = (unsigned long)cmpxchg(&list->next,
+				     val | old_flag, val | new_flag);
+
+	/* check if the reader took the page */
+	if ((ret & ~RB_FLAG_MASK) != val)
+		return RB_PAGE_MOVED;
+
+	return ret & RB_FLAG_MASK;
+}
+
+static int rb_head_page_set_update(struct ring_buffer_per_cpu *cpu_buffer,
+				   struct buffer_page *head,
+				   struct buffer_page *prev,
+				   int old_flag)
+{
+	return rb_head_page_set(cpu_buffer, head, prev,
+				old_flag, RB_PAGE_UPDATE);
+}
+
+static int rb_head_page_set_head(struct ring_buffer_per_cpu *cpu_buffer,
+				 struct buffer_page *head,
+				 struct buffer_page *prev,
+				 int old_flag)
+{
+	return rb_head_page_set(cpu_buffer, head, prev,
+				old_flag, RB_PAGE_HEAD);
+}
+
+static int rb_head_page_set_normal(struct ring_buffer_per_cpu *cpu_buffer,
+				   struct buffer_page *head,
+				   struct buffer_page *prev,
+				   int old_flag)
+{
+	return rb_head_page_set(cpu_buffer, head, prev,
+				old_flag, RB_PAGE_NORMAL);
+}
+
+static inline void rb_inc_page(struct ring_buffer_per_cpu *cpu_buffer,
+			       struct buffer_page **bpage)
+{
+	struct list_head *p = rb_list_head((*bpage)->list.next);
+
+	*bpage = list_entry(p, struct buffer_page, list);
+}
+
+static struct buffer_page *
+rb_set_head_page(struct ring_buffer_per_cpu *cpu_buffer)
+{
+	struct buffer_page *head;
+	struct buffer_page *page;
+	struct list_head *list;
+	int i;
+
+	if (RB_WARN_ON(cpu_buffer, !cpu_buffer->head_page))
+		return NULL;
+
+	/* sanity check */
+	list = cpu_buffer->pages;
+	if (RB_WARN_ON(cpu_buffer, rb_list_head(list->prev->next) != list))
+		return NULL;
+
+	page = head = cpu_buffer->head_page;
+	/*
+	 * It is possible that the writer moves the header behind
+	 * where we started, and we miss in one loop.
+	 * A second loop should grab the header, but we'll do
+	 * three loops just because I'm paranoid.
+	 */
+	for (i = 0; i < 3; i++) {
+		do {
+			if (rb_is_head_page(cpu_buffer, page, page->list.prev)) {
+				cpu_buffer->head_page = page;
+				return page;
+			}
+			rb_inc_page(cpu_buffer, &page);
+		} while (page != head);
+	}
+
+	RB_WARN_ON(cpu_buffer, 1);
+
+	return NULL;
+}
+
+static int rb_head_page_replace(struct buffer_page *old,
+				struct buffer_page *new)
+{
+	unsigned long *ptr = (unsigned long *)&old->list.prev->next;
+	unsigned long val;
+	unsigned long ret;
+
+	val = *ptr & ~RB_FLAG_MASK;
+	val |= RB_PAGE_HEAD;
+
+	ret = cmpxchg(ptr, val, &new->list);
+
+	return ret == val;
+}
+
+/*
+ * rb_tail_page_update - move the tail page forward
+ *
+ * Returns 1 if moved tail page, 0 if someone else did.
+ */
+static int rb_tail_page_update(struct ring_buffer_per_cpu *cpu_buffer,
+			       struct buffer_page *tail_page,
+			       struct buffer_page *next_page)
+{
+	struct buffer_page *old_tail;
+	unsigned long old_entries;
+	unsigned long old_write;
+	int ret = 0;
+
+	/*
+	 * The tail page now needs to be moved forward.
+	 *
+	 * We need to reset the tail page, but without messing
+	 * with possible erasing of data brought in by interrupts
+	 * that have moved the tail page and are currently on it.
+	 *
+	 * We add a counter to the write field to denote this.
+	 */
+	old_write = local_add_return(RB_WRITE_INTCNT, &next_page->write);
+	old_entries = local_add_return(RB_WRITE_INTCNT, &next_page->entries);
+
+	/*
+	 * Just make sure we have seen our old_write and synchronize
+	 * with any interrupts that come in.
+	 */
+	barrier();
+
+	/*
+	 * If the tail page is still the same as what we think
+	 * it is, then it is up to us to update the tail
+	 * pointer.
+	 */
+	if (tail_page == cpu_buffer->tail_page) {
+		/* Zero the write counter */
+		unsigned long val = old_write & ~RB_WRITE_MASK;
+		unsigned long eval = old_entries & ~RB_WRITE_MASK;
+
+		/*
+		 * This will only succeed if an interrupt did
+		 * not come in and change it. In which case, we
+		 * do not want to modify it.
+		 */
+		local_cmpxchg(&next_page->write, old_write, val);
+		local_cmpxchg(&next_page->entries, old_entries, eval);
+
+		/*
+		 * No need to worry about races with clearing out the commit.
+		 * it only can increment when a commit takes place. But that
+		 * only happens in the outer most nested commit.
+		 */
+		local_set(&next_page->page->commit, 0);
+
+		old_tail = cmpxchg(&cpu_buffer->tail_page,
+				   tail_page, next_page);
+
+		if (old_tail == tail_page)
+			ret = 1;
+	}
+
+	/*
+	 * Regrardless of if we cleared out write, we must decrement
+	 * our counter.
+	 */
+	local_sub(RB_WRITE_INTCNT, &next_page->write);
+	local_sub(RB_WRITE_INTCNT, &next_page->entries);
+
+	return ret;
+}
+
+static int rb_check_bpage(struct ring_buffer_per_cpu *cpu_buffer,
+			  struct buffer_page *bpage)
+{
+	unsigned long val = (unsigned long)bpage;
+
+	if (RB_WARN_ON(cpu_buffer, val & RB_FLAG_MASK))
+		return 1;
+
+	return 0;
+}
+
+/**
+ * rb_check_list - make sure a pointer to a list has the last bits zero
+ */
+static int rb_check_list(struct ring_buffer_per_cpu *cpu_buffer,
+			 struct list_head *list)
+{
+	if (RB_WARN_ON(cpu_buffer, rb_list_head(list->prev) != list->prev))
+		return 1;
+	if (RB_WARN_ON(cpu_buffer, rb_list_head(list->next) != list->next))
+		return 1;
+	return 0;
+}
+
 /**
  * check_pages - integrity check of buffer pages
  * @cpu_buffer: CPU buffer with pages to test
@@ -497,11 +905,16 @@ static int rb_check_pages(struct ring_buffer_per_cpu *cpu_buffer)
 	struct list_head *head = cpu_buffer->pages;
 	struct buffer_page *bpage, *tmp;
 
+	rb_head_page_deactivate(cpu_buffer);
+
 	if (RB_WARN_ON(cpu_buffer, head->next->prev != head))
 		return -1;
 	if (RB_WARN_ON(cpu_buffer, head->prev->next != head))
 		return -1;
 
+	if (rb_check_list(cpu_buffer, head))
+		return -1;
+
 	list_for_each_entry_safe(bpage, tmp, head, list) {
 		if (RB_WARN_ON(cpu_buffer,
 			       bpage->list.next->prev != &bpage->list))
@@ -509,8 +922,12 @@ static int rb_check_pages(struct ring_buffer_per_cpu *cpu_buffer)
 		if (RB_WARN_ON(cpu_buffer,
 			       bpage->list.prev->next != &bpage->list))
 			return -1;
+		if (rb_check_list(cpu_buffer, &bpage->list))
+			return -1;
 	}
 
+	rb_head_page_activate(cpu_buffer);
+
 	return 0;
 }
 
@@ -529,6 +946,9 @@ static int rb_allocate_pages(struct ring_buffer_per_cpu *cpu_buffer,
 				    GFP_KERNEL, cpu_to_node(cpu_buffer->cpu));
 		if (!bpage)
 			goto free_pages;
+
+		rb_check_bpage(cpu_buffer, bpage);
+
 		list_add(&bpage->list, &pages);
 
 		addr = __get_free_page(GFP_KERNEL);
@@ -587,6 +1007,8 @@ rb_allocate_cpu_buffer(struct ring_buffer *buffer, int cpu)
 	if (!bpage)
 		goto fail_free_buffer;
 
+	rb_check_bpage(cpu_buffer, bpage);
+
 	cpu_buffer->reader_page = bpage;
 	addr = __get_free_page(GFP_KERNEL);
 	if (!addr)
@@ -604,6 +1026,8 @@ rb_allocate_cpu_buffer(struct ring_buffer *buffer, int cpu)
 		= list_entry(cpu_buffer->pages, struct buffer_page, list);
 	cpu_buffer->tail_page = cpu_buffer->commit_page = cpu_buffer->head_page;
 
+	rb_head_page_activate(cpu_buffer);
+
 	return cpu_buffer;
 
  fail_free_reader:
@@ -621,6 +1045,8 @@ static void rb_free_cpu_buffer(struct ring_buffer_per_cpu *cpu_buffer)
 
 	free_buffer_page(cpu_buffer->reader_page);
 
+	rb_head_page_deactivate(cpu_buffer);
+
 	if (head) {
 		list_for_each_entry_safe(bpage, tmp, head, list) {
 			list_del_init(&bpage->list);
@@ -782,6 +1208,8 @@ rb_remove_pages(struct ring_buffer_per_cpu *cpu_buffer, unsigned nr_pages)
 	atomic_inc(&cpu_buffer->record_disabled);
 	synchronize_sched();
 
+	rb_head_page_deactivate(cpu_buffer);
+
 	for (i = 0; i < nr_pages; i++) {
 		if (RB_WARN_ON(cpu_buffer, list_empty(cpu_buffer->pages)))
 			return;
@@ -812,6 +1240,9 @@ rb_insert_pages(struct ring_buffer_per_cpu *cpu_buffer,
 	atomic_inc(&cpu_buffer->record_disabled);
 	synchronize_sched();
 
+	spin_lock_irq(&cpu_buffer->reader_lock);
+	rb_head_page_deactivate(cpu_buffer);
+
 	for (i = 0; i < nr_pages; i++) {
 		if (RB_WARN_ON(cpu_buffer, list_empty(pages)))
 			return;
@@ -821,6 +1252,7 @@ rb_insert_pages(struct ring_buffer_per_cpu *cpu_buffer,
 		list_add_tail(&bpage->list, cpu_buffer->pages);
 	}
 	rb_reset_cpu(cpu_buffer);
+	spin_unlock_irq(&cpu_buffer->reader_lock);
 
 	rb_check_pages(cpu_buffer);
 
@@ -971,21 +1403,14 @@ rb_reader_event(struct ring_buffer_per_cpu *cpu_buffer)
 }
 
 static inline struct ring_buffer_event *
-rb_head_event(struct ring_buffer_per_cpu *cpu_buffer)
-{
-	return __rb_page_index(cpu_buffer->head_page,
-			       cpu_buffer->head_page->read);
-}
-
-static inline struct ring_buffer_event *
 rb_iter_head_event(struct ring_buffer_iter *iter)
 {
 	return __rb_page_index(iter->head_page, iter->head);
 }
 
-static inline unsigned rb_page_write(struct buffer_page *bpage)
+static inline unsigned long rb_page_write(struct buffer_page *bpage)
 {
-	return local_read(&bpage->write);
+	return local_read(&bpage->write) & RB_WRITE_MASK;
 }
 
 static inline unsigned rb_page_commit(struct buffer_page *bpage)
@@ -993,6 +1418,11 @@ static inline unsigned rb_page_commit(struct buffer_page *bpage)
 	return local_read(&bpage->page->commit);
 }
 
+static inline unsigned long rb_page_entries(struct buffer_page *bpage)
+{
+	return local_read(&bpage->entries) & RB_WRITE_MASK;
+}
+
 /* Size is determined by what has been commited */
 static inline unsigned rb_page_size(struct buffer_page *bpage)
 {
@@ -1005,19 +1435,6 @@ rb_commit_index(struct ring_buffer_per_cpu *cpu_buffer)
 	return rb_page_commit(cpu_buffer->commit_page);
 }
 
-static inline unsigned rb_head_size(struct ring_buffer_per_cpu *cpu_buffer)
-{
-	return rb_page_commit(cpu_buffer->head_page);
-}
-
-static inline void rb_inc_page(struct ring_buffer_per_cpu *cpu_buffer,
-			       struct buffer_page **bpage)
-{
-	struct list_head *p = (*bpage)->list.next;
-
-	*bpage = list_entry(p, struct buffer_page, list);
-}
-
 static inline unsigned
 rb_event_index(struct ring_buffer_event *event)
 {
@@ -1056,6 +1473,9 @@ rb_set_commit_event(struct ring_buffer_per_cpu *cpu_buffer,
 			return;
 		cpu_buffer->commit_page->page->commit =
 			cpu_buffer->commit_page->write;
+		RB_WARN_ON(cpu_buffer,
+			   local_read(&cpu_buffer->commit_page->page->commit) &
+			   ~RB_WRITE_MASK);
 		rb_inc_page(cpu_buffer, &cpu_buffer->commit_page);
 		cpu_buffer->write_stamp =
 			cpu_buffer->commit_page->page->time_stamp;
@@ -1080,6 +1500,9 @@ rb_set_commit_to_write(struct ring_buffer_per_cpu *cpu_buffer)
 	while (cpu_buffer->commit_page != cpu_buffer->tail_page) {
 		cpu_buffer->commit_page->page->commit =
 			cpu_buffer->commit_page->write;
+		RB_WARN_ON(cpu_buffer,
+			   local_read(&cpu_buffer->commit_page->page->commit) &
+			   ~RB_WRITE_MASK);
 		rb_inc_page(cpu_buffer, &cpu_buffer->commit_page);
 		cpu_buffer->write_stamp =
 			cpu_buffer->commit_page->page->time_stamp;
@@ -1090,6 +1513,9 @@ rb_set_commit_to_write(struct ring_buffer_per_cpu *cpu_buffer)
 	       rb_page_write(cpu_buffer->commit_page)) {
 		cpu_buffer->commit_page->page->commit =
 			cpu_buffer->commit_page->write;
+		RB_WARN_ON(cpu_buffer,
+			   local_read(&cpu_buffer->commit_page->page->commit) &
+			   ~RB_WRITE_MASK);
 		barrier();
 	}
 
@@ -1122,7 +1548,7 @@ static void rb_inc_iter(struct ring_buffer_iter *iter)
 	 * to the head page instead of next.
 	 */
 	if (iter->head_page == cpu_buffer->reader_page)
-		iter->head_page = cpu_buffer->head_page;
+		iter->head_page = rb_set_head_page(cpu_buffer);
 	else
 		rb_inc_page(cpu_buffer, &iter->head_page);
 
@@ -1166,6 +1592,165 @@ rb_update_event(struct ring_buffer_event *event,
 	}
 }
 
+/*
+ * rb_handle_head_page - writer hit the head page
+ *
+ * Returns: +1 to retry page
+ *           0 to continue
+ *          -1 on error
+ */
+static int
+rb_handle_head_page(struct ring_buffer_per_cpu *cpu_buffer,
+		    struct buffer_page *tail_page,
+		    struct buffer_page *next_page)
+{
+	struct buffer_page *new_head;
+	int entries;
+	int type;
+	int ret;
+
+	entries = rb_page_entries(next_page);
+
+	/*
+	 * The hard part is here. We need to move the head
+	 * forward, and protect against both readers on
+	 * other CPUs and writers coming in via interrupts.
+	 */
+	type = rb_head_page_set_update(cpu_buffer, next_page, tail_page,
+				       RB_PAGE_HEAD);
+
+	/*
+	 * type can be one of four:
+	 *  NORMAL - an interrupt already moved it for us
+	 *  HEAD   - we are the first to get here.
+	 *  UPDATE - we are the interrupt interrupting
+	 *           a current move.
+	 *  MOVED  - a reader on another CPU moved the next
+	 *           pointer to its reader page. Give up
+	 *           and try again.
+	 */
+
+	switch (type) {
+	case RB_PAGE_HEAD:
+		/*
+		 * We changed the head to UPDATE, thus
+		 * it is our responsibility to update
+		 * the counters.
+		 */
+		local_add(entries, &cpu_buffer->overrun);
+
+		/*
+		 * It is safest to just subtract what we
+		 * know. An interrupt could have come in
+		 * and started adding more entries.
+		 */
+		local_sub(entries, &next_page->entries);
+
+		/* still more to do */
+		break;
+
+	case RB_PAGE_UPDATE:
+		/*
+		 * This is an interrupt that interrupt the
+		 * previous update. Still more to do.
+		 */
+		break;
+	case RB_PAGE_NORMAL:
+		/*
+		 * An interrupt came in before the update
+		 * and processed this for us.
+		 * Nothing left to do.
+		 */
+		return 1;
+	case RB_PAGE_MOVED:
+		/*
+		 * The reader is on another CPU and just did
+		 * a swap with our next_page.
+		 * Try again.
+		 */
+		return 1;
+	default:
+		RB_WARN_ON(cpu_buffer, 1); /* WTF??? */
+		return -1;
+	}
+
+	/*
+	 * Now that we are here, the old head pointer is
+	 * set to UPDATE. This will keep the reader from
+	 * swapping the head page with the reader page.
+	 * The reader (on another CPU) will spin till
+	 * we are finished.
+	 *
+	 * We just need to protect against interrupts
+	 * doing the job. We will set the next pointer
+	 * to HEAD. After that, we set the old pointer
+	 * to NORMAL, but only if it was HEAD before.
+	 * otherwise we are an interrupt, and only
+	 * want the outer most commit to reset it.
+	 */
+	new_head = next_page;
+	rb_inc_page(cpu_buffer, &new_head);
+
+	ret = rb_head_page_set_head(cpu_buffer, new_head, next_page,
+				    RB_PAGE_NORMAL);
+
+	/*
+	 * Valid returns are:
+	 *  HEAD   - an interrupt came in and already set it.
+	 *  NORMAL - One of two things:
+	 *            1) We really set it.
+	 *            2) A bunch of interrupts came in and moved
+	 *               the page forward again.
+	 */
+	switch (ret) {
+	case RB_PAGE_HEAD:
+	case RB_PAGE_NORMAL:
+		/* OK */
+		break;
+	default:
+		RB_WARN_ON(cpu_buffer, 1);
+		return -1;
+	}
+
+	/*
+	 * It is possible that an interrupt came in,
+	 * set the head up, then more interrupts came in
+	 * and moved it again. When we get back here,
+	 * the page would have been set to NORMAL but we
+	 * just set it back to HEAD.
+	 *
+	 * How do you detect this? Well, if that happened
+	 * the tail page would have moved.
+	 */
+	if (ret == RB_PAGE_NORMAL) {
+		/*
+		 * If the tail had moved passed next, then we need
+		 * to reset the pointer.
+		 */
+		if (cpu_buffer->tail_page != tail_page &&
+		    cpu_buffer->tail_page != next_page)
+			rb_head_page_set_normal(cpu_buffer, new_head,
+						next_page,
+						RB_PAGE_HEAD);
+	}
+
+	/*
+	 * If this was the outer most commit (the one that
+	 * changed the original pointer from HEAD to UPDATE),
+	 * then it is up to us to reset it to NORMAL.
+	 */
+	if (type == RB_PAGE_HEAD) {
+		ret = rb_head_page_set_normal(cpu_buffer, next_page,
+					      tail_page,
+					      RB_PAGE_UPDATE);
+		if (RB_WARN_ON(cpu_buffer,
+			       ret != RB_PAGE_UPDATE))
+			return -1;
+	}
+
+	return 0;
+}
+
 static unsigned rb_calculate_event_length(unsigned length)
 {
 	struct ring_buffer_event event; /* Used only for sizeof array */
@@ -1190,95 +1775,89 @@ rb_move_tail(struct ring_buffer_per_cpu *cpu_buffer,
 	     struct buffer_page *commit_page,
 	     struct buffer_page *tail_page, u64 *ts)
 {
-	struct buffer_page *next_page, *head_page, *reader_page;
 	struct ring_buffer *buffer = cpu_buffer->buffer;
 	struct ring_buffer_event *event;
-	bool lock_taken = false;
-	unsigned long flags;
+	struct buffer_page *next_page;
+	int ret;
 
 	next_page = tail_page;
 
-	local_irq_save(flags);
-	/*
-	 * Since the write to the buffer is still not
-	 * fully lockless, we must be careful with NMIs.
-	 * The locks in the writers are taken when a write
-	 * crosses to a new page. The locks protect against
-	 * races with the readers (this will soon be fixed
-	 * with a lockless solution).
-	 *
-	 * Because we can not protect against NMIs, and we
-	 * want to keep traces reentrant, we need to manage
-	 * what happens when we are in an NMI.
-	 *
-	 * NMIs can happen after we take the lock.
-	 * If we are in an NMI, only take the lock
-	 * if it is not already taken. Otherwise
-	 * simply fail.
-	 */
-	if (unlikely(in_nmi())) {
-		if (!__raw_spin_trylock(&cpu_buffer->lock)) {
-			cpu_buffer->nmi_dropped++;
-			goto out_reset;
-		}
-	} else
-		__raw_spin_lock(&cpu_buffer->lock);
-
-	lock_taken = true;
-
 	rb_inc_page(cpu_buffer, &next_page);
 
-	head_page = cpu_buffer->head_page;
-	reader_page = cpu_buffer->reader_page;
-
-	/* we grabbed the lock before incrementing */
-	if (RB_WARN_ON(cpu_buffer, next_page == reader_page))
-		goto out_reset;
-
 	/*
 	 * If for some reason, we had an interrupt storm that made
 	 * it all the way around the buffer, bail, and warn
 	 * about it.
 	 */
 	if (unlikely(next_page == commit_page)) {
-		cpu_buffer->commit_overrun++;
+		local_inc(&cpu_buffer->commit_overrun);
 		goto out_reset;
 	}
 
-	if (next_page == head_page) {
-		if (!(buffer->flags & RB_FL_OVERWRITE))
-			goto out_reset;
-
-		/* tail_page has not moved yet? */
-		if (tail_page == cpu_buffer->tail_page) {
-			/* count overflows */
-			cpu_buffer->overrun +=
-				local_read(&head_page->entries);
+	/*
+	 * This is where the fun begins!
+	 *
+	 * We are fighting against races between a reader that
+	 * could be on another CPU trying to swap its reader
+	 * page with the buffer head.
+	 *
+	 * We are also fighting against interrupts coming in and
+	 * moving the head or tail on us as well.
+	 *
+	 * If the next page is the head page then we have filled
+	 * the buffer, unless the commit page is still on the
+	 * reader page.
+	 */
+	if (rb_is_head_page(cpu_buffer, next_page, &tail_page->list)) {
 
-			rb_inc_page(cpu_buffer, &head_page);
-			cpu_buffer->head_page = head_page;
-			cpu_buffer->head_page->read = 0;
+		/*
+		 * If the commit is not on the reader page, then
+		 * move the header page.
+		 */
+		if (!rb_is_reader_page(cpu_buffer->commit_page)) {
+			/*
+			 * If we are not in overwrite mode,
+			 * this is easy, just stop here.
+			 */
+			if (!(buffer->flags & RB_FL_OVERWRITE))
+				goto out_reset;
+
+			ret = rb_handle_head_page(cpu_buffer,
+						  tail_page,
+						  next_page);
+			if (ret < 0)
+				goto out_reset;
+			if (ret)
+				goto out_again;
+		} else {
+			/*
+			 * We need to be careful here too. The
+			 * commit page could still be on the reader
+			 * page. We could have a small buffer, and
+			 * have filled up the buffer with events
+			 * from interrupts and such, and wrapped.
+			 */
+			if (unlikely(cpu_buffer->commit_page !=
+				     cpu_buffer->tail_page)) {
+				local_inc(&cpu_buffer->commit_overrun);
+				goto out_reset;
+			}
 		}
 	}
 
-	/*
-	 * If the tail page is still the same as what we think
-	 * it is, then it is up to us to update the tail
-	 * pointer.
-	 */
-	if (tail_page == cpu_buffer->tail_page) {
-		local_set(&next_page->write, 0);
-		local_set(&next_page->entries, 0);
-		local_set(&next_page->page->commit, 0);
-		cpu_buffer->tail_page = next_page;
-
-		/* reread the time stamp */
+	ret = rb_tail_page_update(cpu_buffer, tail_page, next_page);
+	if (ret) {
+		/*
+		 * Nested commits always have zero deltas, so
+		 * just reread the time stamp
+		 */
 		*ts = rb_time_stamp(buffer, cpu_buffer->cpu);
-		cpu_buffer->tail_page->page->time_stamp = *ts;
+		next_page->page->time_stamp = *ts;
 	}
 
 	/*
-	 * The actual tail page has moved forward.
+	 * Only the event that crossed the page boundary
+	 * must fill the old tail_page with padding.
 	 */
 	if (tail < BUF_PAGE_SIZE) {
 		/* Mark the rest of the page with padding */
@@ -1286,20 +1865,22 @@ rb_move_tail(struct ring_buffer_per_cpu *cpu_buffer,
 		rb_event_set_padding(event);
 	}
 
+ out_again:
+
 	/* Set the write back to the previous setting */
 	local_sub(length, &tail_page->write);
 
 	/*
 	 * If this was a commit entry that failed,
-	 * increment that too
+	 * then if any interrupts came in, they are now
+	 * the real commits. When we go back and try again
+	 * we will again test if we are a commit and will
+	 * fail if we do not account for any interrupts that
+	 * came in during the above.
 	 */
 	if (tail_page == cpu_buffer->commit_page &&
-	    tail == rb_commit_index(cpu_buffer)) {
+	    tail == rb_commit_index(cpu_buffer))
 		rb_set_commit_to_write(cpu_buffer);
-	}
-
-	__raw_spin_unlock(&cpu_buffer->lock);
-	local_irq_restore(flags);
 
 	/* fail and let the caller try again */
 	return ERR_PTR(-EAGAIN);
@@ -1308,9 +1889,6 @@ rb_move_tail(struct ring_buffer_per_cpu *cpu_buffer,
 	/* reset write */
 	local_sub(length, &tail_page->write);
 
-	if (likely(lock_taken))
-		__raw_spin_unlock(&cpu_buffer->lock);
-	local_irq_restore(flags);
 	return NULL;
 }
 
@@ -1327,6 +1905,9 @@ __rb_reserve_next(struct ring_buffer_per_cpu *cpu_buffer,
 	barrier();
 	tail_page = cpu_buffer->tail_page;
 	write = local_add_return(length, &tail_page->write);
+
+	/* set write to only the index of the write */
+	write &= RB_WRITE_MASK;
 	tail = write - length;
 
 	/* See if we shot pass the end of this buffer page */
@@ -1852,9 +2433,13 @@ EXPORT_SYMBOL_GPL(ring_buffer_write);
 static int rb_per_cpu_empty(struct ring_buffer_per_cpu *cpu_buffer)
 {
 	struct buffer_page *reader = cpu_buffer->reader_page;
-	struct buffer_page *head = cpu_buffer->head_page;
+	struct buffer_page *head = rb_set_head_page(cpu_buffer);
 	struct buffer_page *commit = cpu_buffer->commit_page;
 
+	/* In case of error, head will be NULL */
+	if (unlikely(!head))
+		return 1;
+
 	return reader->read == rb_page_commit(reader) &&
 		(commit == reader ||
 		 (commit == head &&
@@ -1945,7 +2530,7 @@ unsigned long ring_buffer_entries_cpu(struct ring_buffer *buffer, int cpu)
 		return 0;
 
 	cpu_buffer = buffer->buffers[cpu];
-	ret = (local_read(&cpu_buffer->entries) - cpu_buffer->overrun)
+	ret = (local_read(&cpu_buffer->entries) - local_read(&cpu_buffer->overrun))
 		- cpu_buffer->read;
 
 	return ret;
@@ -1966,33 +2551,13 @@ unsigned long ring_buffer_overrun_cpu(struct ring_buffer *buffer, int cpu)
 		return 0;
 
 	cpu_buffer = buffer->buffers[cpu];
-	ret = cpu_buffer->overrun;
+	ret = local_read(&cpu_buffer->overrun);
 
 	return ret;
 }
 EXPORT_SYMBOL_GPL(ring_buffer_overrun_cpu);
 
 /**
- * ring_buffer_nmi_dropped_cpu - get the number of nmis that were dropped
- * @buffer: The ring buffer
- * @cpu: The per CPU buffer to get the number of overruns from
- */
-unsigned long ring_buffer_nmi_dropped_cpu(struct ring_buffer *buffer, int cpu)
-{
-	struct ring_buffer_per_cpu *cpu_buffer;
-	unsigned long ret;
-
-	if (!cpumask_test_cpu(cpu, buffer->cpumask))
-		return 0;
-
-	cpu_buffer = buffer->buffers[cpu];
-	ret = cpu_buffer->nmi_dropped;
-
-	return ret;
-}
-EXPORT_SYMBOL_GPL(ring_buffer_nmi_dropped_cpu);
-
-/**
  * ring_buffer_commit_overrun_cpu - get the number of overruns caused by commits
  * @buffer: The ring buffer
  * @cpu: The per CPU buffer to get the number of overruns from
@@ -2007,7 +2572,7 @@ ring_buffer_commit_overrun_cpu(struct ring_buffer *buffer, int cpu)
 		return 0;
 
 	cpu_buffer = buffer->buffers[cpu];
-	ret = cpu_buffer->commit_overrun;
+	ret = local_read(&cpu_buffer->commit_overrun);
 
 	return ret;
 }
@@ -2030,7 +2595,7 @@ unsigned long ring_buffer_entries(struct ring_buffer *buffer)
 	for_each_buffer_cpu(buffer, cpu) {
 		cpu_buffer = buffer->buffers[cpu];
 		entries += (local_read(&cpu_buffer->entries) -
-			    cpu_buffer->overrun) - cpu_buffer->read;
+			    local_read(&cpu_buffer->overrun)) - cpu_buffer->read;
 	}
 
 	return entries;
@@ -2053,7 +2618,7 @@ unsigned long ring_buffer_overruns(struct ring_buffer *buffer)
 	/* if you care about this being correct, lock the buffer */
 	for_each_buffer_cpu(buffer, cpu) {
 		cpu_buffer = buffer->buffers[cpu];
-		overruns += cpu_buffer->overrun;
+		overruns += local_read(&cpu_buffer->overrun);
 	}
 
 	return overruns;
@@ -2066,8 +2631,10 @@ static void rb_iter_reset(struct ring_buffer_iter *iter)
 
 	/* Iterator usage is expected to have record disabled */
 	if (list_empty(&cpu_buffer->reader_page->list)) {
-		iter->head_page = cpu_buffer->head_page;
-		iter->head = cpu_buffer->head_page->read;
+		iter->head_page = rb_set_head_page(cpu_buffer);
+		if (unlikely(!iter->head_page))
+			return;
+		iter->head = iter->head_page->read;
 	} else {
 		iter->head_page = cpu_buffer->reader_page;
 		iter->head = cpu_buffer->reader_page->read;
@@ -2184,6 +2751,7 @@ rb_get_reader_page(struct ring_buffer_per_cpu *cpu_buffer)
 	struct buffer_page *reader = NULL;
 	unsigned long flags;
 	int nr_loops = 0;
+	int ret;
 
 	local_irq_save(flags);
 	__raw_spin_lock(&cpu_buffer->lock);
@@ -2217,11 +2785,17 @@ rb_get_reader_page(struct ring_buffer_per_cpu *cpu_buffer)
 		goto out;
 
 	/*
-	 * Splice the empty reader page into the list around the head.
 	 * Reset the reader page to size zero.
 	 */
+	local_set(&cpu_buffer->reader_page->write, 0);
+	local_set(&cpu_buffer->reader_page->entries, 0);
+	local_set(&cpu_buffer->reader_page->page->commit, 0);
 
-	reader = cpu_buffer->head_page;
+ spin:
+	/*
+	 * Splice the empty reader page into the list around the head.
+	 */
+	reader = rb_set_head_page(cpu_buffer);
 	cpu_buffer->reader_page->list.next = reader->list.next;
 	cpu_buffer->reader_page->list.prev = reader->list.prev;
 
@@ -2232,22 +2806,35 @@ rb_get_reader_page(struct ring_buffer_per_cpu *cpu_buffer)
 	 */
 	cpu_buffer->pages = reader->list.prev;
 
-	local_set(&cpu_buffer->reader_page->write, 0);
-	local_set(&cpu_buffer->reader_page->entries, 0);
-	local_set(&cpu_buffer->reader_page->page->commit, 0);
+	/* The reader page will be pointing to the new head */
+	rb_set_list_to_head(cpu_buffer, &cpu_buffer->reader_page->list);
 
-	/* Make the reader page now replace the head */
-	reader->list.prev->next = &cpu_buffer->reader_page->list;
-	reader->list.next->prev = &cpu_buffer->reader_page->list;
+	/*
+	 * Here's the tricky part.
+	 *
+	 * We need to move the pointer past the header page.
+	 * But we can only do that if a writer is not currently
+	 * moving it. The page before the header page has the
+	 * flag bit '1' set if it is pointing to the page we want.
+	 * but if the writer is in the process of moving it
+	 * than it will be '2' or already moved '0'.
+	 */
+
+	ret = rb_head_page_replace(reader, cpu_buffer->reader_page);
 
 	/*
-	 * If the tail is on the reader, then we must set the head
-	 * to the inserted page, otherwise we set it one before.
+	 * If we did not convert it, then we must try again.
 	 */
-	cpu_buffer->head_page = cpu_buffer->reader_page;
+	if (!ret)
+		goto spin;
 
-	if (cpu_buffer->commit_page != reader)
-		rb_inc_page(cpu_buffer, &cpu_buffer->head_page);
+	/*
+	 * Yeah! We succeeded in replacing the page.
+	 *
+	 * Now make the new head point back to the reader page.
+	 */
+	reader->list.next->prev = &cpu_buffer->reader_page->list;
+	rb_inc_page(cpu_buffer, &cpu_buffer->head_page);
 
 	/* Finally update the reader page to the new head */
 	cpu_buffer->reader_page = reader;
@@ -2675,6 +3262,8 @@ EXPORT_SYMBOL_GPL(ring_buffer_size);
 static void
 rb_reset_cpu(struct ring_buffer_per_cpu *cpu_buffer)
 {
+	rb_head_page_deactivate(cpu_buffer);
+
 	cpu_buffer->head_page
 		= list_entry(cpu_buffer->pages, struct buffer_page, list);
 	local_set(&cpu_buffer->head_page->write, 0);
@@ -2692,14 +3281,15 @@ rb_reset_cpu(struct ring_buffer_per_cpu *cpu_buffer)
 	local_set(&cpu_buffer->reader_page->page->commit, 0);
 	cpu_buffer->reader_page->read = 0;
 
-	cpu_buffer->nmi_dropped = 0;
-	cpu_buffer->commit_overrun = 0;
-	cpu_buffer->overrun = 0;
-	cpu_buffer->read = 0;
+	local_set(&cpu_buffer->commit_overrun, 0);
+	local_set(&cpu_buffer->overrun, 0);
 	local_set(&cpu_buffer->entries, 0);
+	cpu_buffer->read = 0;
 
 	cpu_buffer->write_stamp = 0;
 	cpu_buffer->read_stamp = 0;
+
+	rb_head_page_activate(cpu_buffer);
 }
 
 /**
@@ -2751,12 +3341,18 @@ EXPORT_SYMBOL_GPL(ring_buffer_reset);
 int ring_buffer_empty(struct ring_buffer *buffer)
 {
 	struct ring_buffer_per_cpu *cpu_buffer;
+	unsigned long flags;
 	int cpu;
+	int ret;
 
 	/* yes this is racy, but if you don't like the race, lock the buffer */
 	for_each_buffer_cpu(buffer, cpu) {
 		cpu_buffer = buffer->buffers[cpu];
-		if (!rb_per_cpu_empty(cpu_buffer))
+		spin_lock_irqsave(&cpu_buffer->reader_lock, flags);
+		ret = rb_per_cpu_empty(cpu_buffer);
+		spin_unlock_irqrestore(&cpu_buffer->reader_lock, flags);
+
+		if (!ret)
 			return 0;
 	}
 
@@ -2772,13 +3368,16 @@ EXPORT_SYMBOL_GPL(ring_buffer_empty);
 int ring_buffer_empty_cpu(struct ring_buffer *buffer, int cpu)
 {
 	struct ring_buffer_per_cpu *cpu_buffer;
+	unsigned long flags;
 	int ret;
 
 	if (!cpumask_test_cpu(cpu, buffer->cpumask))
 		return 1;
 
 	cpu_buffer = buffer->buffers[cpu];
+	spin_lock_irqsave(&cpu_buffer->reader_lock, flags);
 	ret = rb_per_cpu_empty(cpu_buffer);
+	spin_unlock_irqrestore(&cpu_buffer->reader_lock, flags);
 
 
 	return ret;
@@ -3026,6 +3625,8 @@ int ring_buffer_read_page(struct ring_buffer *buffer,
 	} else {
 		/* update the entry counter */
 		cpu_buffer->read += local_read(&reader->entries);
+		RB_WARN_ON(cpu_buffer,
+			   local_read(&reader->entries) & ~RB_WRITE_MASK);
 
 		/* swap the pages */
 		rb_init_page(bpage);
diff --git a/kernel/trace/trace.c b/kernel/trace/trace.c
index cae34c6..28fee77 100644
--- a/kernel/trace/trace.c
+++ b/kernel/trace/trace.c
@@ -3642,9 +3642,6 @@ tracing_stats_read(struct file *filp, char __user *ubuf,
 	cnt = ring_buffer_commit_overrun_cpu(tr->buffer, cpu);
 	trace_seq_printf(s, "commit overrun: %ld\n", cnt);
 
-	cnt = ring_buffer_nmi_dropped_cpu(tr->buffer, cpu);
-	trace_seq_printf(s, "nmi dropped: %ld\n", cnt);
-
 	count = simple_read_from_buffer(ubuf, count, ppos, s->buffer, s->len);
 
 	kfree(s);
-- 
1.6.3.1

-- 

^ permalink raw reply related	[flat|nested] 29+ messages in thread

* [PATCH 3/3] ring-buffer: add design document
  2009-06-10 19:53 [PATCH 0/3] [GIT PULL][for 2.6.32] lockless ring buffer Steven Rostedt
  2009-06-10 19:53 ` [PATCH 1/3] ring-buffer: make the buffer a true circular link list Steven Rostedt
  2009-06-10 19:53 ` [PATCH 2/3] ring-buffer: make lockless Steven Rostedt
@ 2009-06-10 19:53 ` Steven Rostedt
  2009-06-10 22:13   ` Mathieu Desnoyers
                     ` (4 more replies)
  2 siblings, 5 replies; 29+ messages in thread
From: Steven Rostedt @ 2009-06-10 19:53 UTC (permalink / raw)
  To: linux-kernel
  Cc: Ingo Molnar, Andrew Morton, Thomas Gleixner, Peter Zijlstra,
	Frederic Weisbecker, Theodore Tso, Arnaldo Carvalho de Melo,
	Mathieu Desnoyers, Lai Jiangshan, Martin J. Bligh,
	Christoph Hellwig, Li Zefan, Huang Ying, H. Peter Anvin,
	Hidetoshi Seto, Masami Hiramatsu

[-- Attachment #1: 0003-ring-buffer-add-design-document.patch --]
[-- Type: text/plain, Size: 32065 bytes --]

From: Steven Rostedt <srostedt@redhat.com>

This adds the design document for the ring buffer and also
explains how it is designed to have lockless writes.

Signed-off-by: Steven Rostedt <rostedt@goodmis.org>
---
 Documentation/trace/ring-buffer-design.txt |  949 ++++++++++++++++++++++++++++
 1 files changed, 949 insertions(+), 0 deletions(-)
 create mode 100644 Documentation/trace/ring-buffer-design.txt

diff --git a/Documentation/trace/ring-buffer-design.txt b/Documentation/trace/ring-buffer-design.txt
new file mode 100644
index 0000000..cca290b
--- /dev/null
+++ b/Documentation/trace/ring-buffer-design.txt
@@ -0,0 +1,949 @@
+		Lockless Ring Buffer Design
+		===========================
+
+Copyright 2009 Red Hat Inc.
+   Author:   Steven Rostedt <srostedt@redhat.com>
+  License:   The GNU Free Documentation License, Version 1.2
+               (dual licensed under the GPL v2)
+
+Written for: 2.6.31
+
+Terminology used in this Document
+---------------------------------
+
+tail - where new writes happen in the ring buffer.
+
+head - where new reads happen in the ring buffer.
+
+producer - the task that writes into the ring buffer (same as writer)
+
+writer - same as producer
+
+consumer - the task that reads from the buffer (same as reader)
+
+reader - same as consumer.
+
+reader_page - A page outside the ring buffer used solely (for the most part)
+    by the reader.
+
+head_page - a pointer to the page that the reader will use next
+
+tail_page - a pointer to the page that will be written to next
+
+commit_page - a pointer to the page with the last finished non nested write.
+
+cmpxchg - hardware assisted atomic transaction that performs the following:
+
+   A = B iff previous A == C
+
+   R = cmpxchg(A, C, B) is saying that we replace A with B if and only if
+      current A is equal to C, and we put the old (current) A into R
+
+   R gets the previous A regardless if A is updated with B or not.
+
+   To see if the update was successful a compare of R == C may be used.
+
+The Generic Ring Buffer
+-----------------------
+
+The ring buffer can be used in either an overwrite mode or in
+producer/consumer mode.
+
+Producer/consumer mode is where the producer were to fill up the
+buffer before the consumer could free up anything, the producer
+will stop writing to the buffer. This will lose most recent events.
+
+Overwrite mode is where the produce were to fill up the buffer
+before the consumer could free up anything, the producer will
+overwrite the older data. This will lose the oldest events.
+
+No two writers can write at the same time (on the same per cpu buffer),
+but a writer may preempt another writer, but it must finish writing
+before the previous writer may continue. This is very important to the
+algorithm. The writers act like a "stack".
+
+
+  writer1 start
+     <preempted> writer2 start
+         <preempted> writer3 start
+                     writer3 finishes
+                 writer2 finishes
+  writer1 finishes
+
+This is very much like a writer being preempted by an interrupt and
+the interrupt doing a write as well.
+
+Readers can happen at any time. But no two readers may run at the
+same time, nor can a reader preempt another reader. A reader can not preempt
+a writer, but it may read/consume from the buffer at the same time as
+a writer is writing, but the reader must be on another processor.
+
+A writer can preempt a reader, but a reader can not preempt a writer.
+But a reader can read the buffer at the same time (on another processor)
+as a writer.
+
+The ring buffer is made up of a list of pages held together by a link list.
+
+At initialization a reader page is allocated for the reader that is not
+part of the ring buffer.
+
+The head_page, tail_page and commit_page are all initialized to point
+to the same page.
+
+The reader page is initialized to have its next pointer pointing to
+the head page, and its previous pointer pointing to a page before
+the head page.
+
+The reader has its own page to use. At start up time, this page is
+allocated but is not attached to the list. When the reader wants
+to read from the buffer, if its page is empty (like it is on start up)
+it will swap its page with the head_page. The old reader page will
+become part of the ring buffer and the head_page will be removed.
+A new head page goes to the page after the old head page (but not
+the page that was swapped in).
+
+Once the new page is given to the reader, the reader could do what
+it wants with it, as long as a writer has left that page.
+
+A sample of how the reader page is swapped: Note this does not
+show the head page in the buffer, it is for demonstrating a swap
+only.
+
+  +------+
+  |reader|          RING BUFFER
+  |page  |
+  +------+
+                  +---+   +---+   +---+
+                  |   |-->|   |-->|   |
+                  |   |<--|   |<--|   |
+                  +---+   +---+   +---+
+                   ^ |             ^ |
+                   | +-------------+ |
+                   +-----------------+
+
+
+  +------+
+  |reader|          RING BUFFER
+  |page  |-------------------+
+  +------+                   v
+    |             +---+   +---+   +---+
+    |             |   |-->|   |-->|   |
+    |             |   |<--|   |<--|   |<-+
+    |             +---+   +---+   +---+  |
+    |              ^ |             ^ |   |
+    |              | +-------------+ |   |
+    |              +-----------------+   |
+    +------------------------------------+
+
+  +------+
+  |reader|          RING BUFFER
+  |page  |-------------------+
+  +------+ <---------------+ v
+    |  ^          +---+   +---+   +---+
+    |  |          |   |-->|   |-->|   |
+    |  |          |   |<--|   |<--|   |<-+
+    |  |          +---+   +---+   +---+  |
+    |  |             |             ^ |   |
+    |  |             +-------------+ |   |
+    |  +-----------------------------+   |
+    +------------------------------------+
+
+  +------+
+  |buffer|          RING BUFFER
+  |page  |-------------------+
+  +------+ <---------------+ v
+    |  ^          +---+   +---+   +---+
+    |  |          |   |   |   |-->|   |
+    |  |  New     |   |   |   |<--|   |<-+
+    |  | Reader   +---+   +---+   +---+  |
+    |  |  page ----^                 |   |
+    |  |                             |   |
+    |  +-----------------------------+   |
+    +------------------------------------+
+
+
+
+It is possible that the page swapped is the commit page and the tail page,
+if what is in the ring buffer is less than what is held in a buffer page.
+
+
+          reader page    commit page   tail page
+              |              |             |
+              v              |             |
+             +---+           |             |
+             |   |<----------+             |
+             |   |<------------------------+
+             |   |------+
+             +---+      |
+                        |
+                        v
+    +---+    +---+    +---+    +---+
+<---|   |--->|   |--->|   |--->|   |--->
+--->|   |<---|   |<---|   |<---|   |<---
+    +---+    +---+    +---+    +---+
+
+This case is still legal for this algorithm.
+When the writer leaves the page, it simply goes into the ring buffer
+since the reader page still points to the next location in the ring
+buffer.
+
+
+The main pointers:
+
+  reader page - The page used solely by the reader and is not part
+                of the ring buffer (may be swapped in)
+
+  head page - the next page in the ring buffer that will be swapped
+              with the reader page.
+
+  tail page - the page where the next write will take place.
+
+  commit page - the page that last finished a write.
+
+The commit page only is updated by the outer most writer in the
+writer stack. A writer that preempts another writer will not move the
+commit page.
+
+When data is written into the ring buffer, a position is reserved
+in the ring buffer and passed back to the writer. When the writer
+is finished writing data into that position, it commits the write.
+
+Another write (or a read) may take place at anytime during this
+transaction. If another write happens it must finish before continuing
+with the previous write.
+
+
+   Write reserve:
+
+       Buffer page
+      +---------+
+      |written  |
+      +---------+  <--- given back to writer (current commit)
+      |reserved |
+      +---------+ <--- tail pointer
+      | empty   |
+      +---------+
+
+   Write commit:
+
+       Buffer page
+      +---------+
+      |written  |
+      +---------+
+      |written  |
+      +---------+  <--- next positon for write (current commit)
+      | empty   |
+      +---------+
+
+
+ If a write happens after the first reserve:
+
+       Buffer page
+      +---------+
+      |written  |
+      +---------+  <-- current commit
+      |reserved |
+      +---------+  <--- given back to second writer
+      |reserved |
+      +---------+ <--- tail pointer
+
+  After second writer commits:
+
+
+       Buffer page
+      +---------+
+      |written  |
+      +---------+  <--(last full commit)
+      |reserved |
+      +---------+
+      |pending  |
+      |commit   |
+      +---------+ <--- tail pointer
+
+  When the first writer commits:
+
+       Buffer page
+      +---------+
+      |written  |
+      +---------+
+      |written  |
+      +---------+
+      |written  |
+      +---------+  <--(last full commit and tail pointer)
+
+
+The commit pointer points to the last write location that was
+committed without preempting another write. When a write that
+preempted another write is committed, it only becomes a pending commit
+and will not be a full commit till all writes have been committed.
+
+The commit page points to the page that has the last full commit.
+The tail page points to the page with the last write (before
+committing).
+
+The tail page is always equal to or after the commit page. It may
+be several pages ahead. If the tail page catches up to the commit
+page then no more writes may take place (regardless of the mode
+of the ring buffer: overwrite and produce/consumer).
+
+The order of pages are:
+
+ head page
+ commit page
+ tail page
+
+Possible scenario:
+                             tail page
+  head page         commit page  |
+      |                 |        |
+      v                 v        v
+    +---+    +---+    +---+    +---+
+<---|   |--->|   |--->|   |--->|   |--->
+--->|   |<---|   |<---|   |<---|   |<---
+    +---+    +---+    +---+    +---+
+
+There is a special case that the head page is after either the commit page
+and possibly the tail page. That is when the commit (and tail) page has been
+swapped with the reader page. This is because the head page is always
+part of the ring buffer, but the reader page is not. When ever there
+has been less than a full page that has been committed inside the ring buffer,
+and a reader swaps out a page, it will be swapping out the commit page.
+
+
+          reader page    commit page   tail page
+              |              |             |
+              v              |             |
+             +---+           |             |
+             |   |<----------+             |
+             |   |<------------------------+
+             |   |------+
+             +---+      |
+                        |
+                        v
+    +---+    +---+    +---+    +---+
+<---|   |--->|   |--->|   |--->|   |--->
+--->|   |<---|   |<---|   |<---|   |<---
+    +---+    +---+    +---+    +---+
+                        ^
+                        |
+                    head page
+
+
+In this case, the head page will not move when the tail and commit
+move back into the ring buffer.
+
+The reader can not swap a page into the ring buffer if the commit page
+is still on that page. If the read meets the last commit (real commit
+not pending or reserved), then there is nothing more to read.
+The buffer is considered empty until another full commit finishes.
+
+When the tail meets the head page, if the buffer is in overwrite mode,
+the head page will be pushed ahead one. If the buffer is in producer/consumer
+mode, the write will fail.
+
+Overwrite mode:
+
+            tail page
+               |
+               v
+    +---+    +---+    +---+    +---+
+<---|   |--->|   |--->|   |--->|   |--->
+--->|   |<---|   |<---|   |<---|   |<---
+    +---+    +---+    +---+    +---+
+                        ^
+                        |
+                    head page
+
+
+            tail page
+               |
+               v
+    +---+    +---+    +---+    +---+
+<---|   |--->|   |--->|   |--->|   |--->
+--->|   |<---|   |<---|   |<---|   |<---
+    +---+    +---+    +---+    +---+
+                                 ^
+                                 |
+                             head page
+
+
+                    tail page
+                        |
+                        v
+    +---+    +---+    +---+    +---+
+<---|   |--->|   |--->|   |--->|   |--->
+--->|   |<---|   |<---|   |<---|   |<---
+    +---+    +---+    +---+    +---+
+                                 ^
+                                 |
+                             head page
+
+Note, the reader page will still point to the previous head page.
+But when a swap takes place, it will use the most recent head page.
+
+
+Making the Ring Buffer Lockless:
+--------------------------------
+
+The main idea behind the lockless algorithm is to combine the moving
+of the head_page pointer with the swapping of pages with the reader.
+State flags are placed inside the pointer to the page. To do this,
+each page must be aligned in memory by 4 bytes. This will allow the 2
+least significant bits of the address to be used as flags. Since
+they will always be zero for the address. To get the address,
+simply mask out the flags.
+
+  MASK = ~3
+
+  address & MASK
+
+Two flags will be kept by these two bits:
+
+   HEADER - the page being pointed to is a head page
+
+   UPDATE - the page being pointed to is being updated by a writer
+          and was or is about to be a head page.
+
+
+          reader page
+              |
+              v
+             +---+
+             |   |------+
+             +---+      |
+                        |
+                        v
+    +---+    +---+    +---+    +---+
+<---|   |--->|   |-H->|   |--->|   |--->
+--->|   |<---|   |<---|   |<---|   |<---
+    +---+    +---+    +---+    +---+
+
+
+The above pointer "-H->" would have the HEADER flag set. That is
+the next page is the next page to be swapped out by the reader.
+This pointer means the next page is the head page.
+
+When the tail page meets the head pointer, it will use cmpxchg to
+change the pointer to the UPDATE state:
+
+
+            tail page
+               |
+               v
+    +---+    +---+    +---+    +---+
+<---|   |--->|   |-H->|   |--->|   |--->
+--->|   |<---|   |<---|   |<---|   |<---
+    +---+    +---+    +---+    +---+
+
+            tail page
+               |
+               v
+    +---+    +---+    +---+    +---+
+<---|   |--->|   |-U->|   |--->|   |--->
+--->|   |<---|   |<---|   |<---|   |<---
+    +---+    +---+    +---+    +---+
+
+"-U->" represents a pointer in the UPDATE state.
+
+Any access to the reader will need to take some sort of lock to serialize
+the readers. But the writers will never take a lock to write to the
+ring buffer. This means we only need to worry about a single reader,
+and writes only preempt in "stack" formation.
+
+When the reader tries to swap the page with the ring buffer, it
+will also use cmpxchg. If the flag bit in the pointer to the
+head page does not have the HEADER flag set, the compare will fail
+and the reader will need to look for the new head page and try again.
+Note, the flag UPDATE and HEADER are never set at the same time.
+
+The reader swaps the reader page as follows:
+
+  +------+
+  |reader|          RING BUFFER
+  |page  |
+  +------+
+                  +---+    +---+    +---+
+                  |   |--->|   |--->|   |
+                  |   |<---|   |<---|   |
+                  +---+    +---+    +---+
+                   ^ |               ^ |
+                   | +---------------+ |
+                   +-----H-------------+
+
+The reader sets the reader page next pointer as HEADER to the page after
+the head page.
+
+
+  +------+
+  |reader|          RING BUFFER
+  |page  |-------H-----------+
+  +------+                   v
+    |             +---+    +---+    +---+
+    |             |   |--->|   |--->|   |
+    |             |   |<---|   |<---|   |<-+
+    |             +---+    +---+    +---+  |
+    |              ^ |               ^ |   |
+    |              | +---------------+ |   |
+    |              +-----H-------------+   |
+    +--------------------------------------+
+
+It does a cmpxchg with the pointer to the previous head page to make it
+point to the reader page. Note that the new pointer does not have the HEADER
+flag set.  This action atomically moves the head page forward.
+
+  +------+
+  |reader|          RING BUFFER
+  |page  |-------H-----------+
+  +------+ <---------------+ v
+    |  ^          +---+   +---+   +---+
+    |  |          |   |-->|   |-->|   |
+    |  |          |   |<--|   |<--|   |<-+
+    |  |          +---+   +---+   +---+  |
+    |  |             |             ^ |   |
+    |  |             +-------------+ |   |
+    |  +-----------------------------+   |
+    +------------------------------------+
+
+After the new head page is set, the previous pointer of the head page is
+updated to the reader page.
+
+  +------+
+  |reader|          RING BUFFER
+  |page  |-------H-----------+
+  +------+                   v
+    |  ^          +---+   +---+   +---+
+    |  |          |   |-->|   |-->|   |
+    |  |          |   |<--|   |<--|   |<-+
+    |  |          +---+   +---+   +---+  |
+    |  |             |             ^ |   |
+    |  |             +-------------+ |   |
+    |  +-----------------------------+   |
+    +------------------------------------+
+
+  +------+
+  |buffer|          RING BUFFER
+  |page  |-------H-----------+  <--- New head page
+  +------+ <---------------+ v
+    |  ^          +---+   +---+   +---+
+    |  |          |   |   |   |-->|   |
+    |  |  New     |   |   |   |<--|   |<-+
+    |  | Reader   +---+   +---+   +---+  |
+    |  |  page ----^                 |   |
+    |  |                             |   |
+    |  +-----------------------------+   |
+    +------------------------------------+
+
+Another important point. The page that the reader page points back to
+by its previous pointer (the one that now points to the new head page)
+never points back to the reader page. That is because the reader page is
+not part of the ring buffer. Traversing the ring buffer via the next pointers
+will always stay in the ring buffer. Traversing the ring buffer via the
+prev pointers may not.
+
+Note, the way to determine a reader page is simply by examining the previous
+pointer of the page. If the next pointer of the previous page does not
+point back to the original page, then the original page is a reader page:
+
+                                  
+             +--------+
+             | reader |  next   +----+
+             |  page  |-------->|    |<====== (buffer page)
+             +--------+         +----+
+                 |                | ^
+                 |                v | next
+            prev |              +----+
+                 +------------->|    |
+                                +----+
+
+The way the head page moves forward:
+
+When the tail page meets the head page and the buffer is in overwrite mode
+and more writes take place, the head page must be moved forward before the
+writer may move the tail page. The way this is done is that the writer
+performs a cmpxchg to convert the pointer to the head page from the HEADER
+flag to have the UPDATE flag set. Once this is done, the reader will
+not be able to swap the head page from the buffer, nor will it be able to
+move the head page, until the writer is finished with the move.
+
+This eliminates any races that the reader can have on the writer. The reader
+must spin, and this is why the reader can not preempt the writer.
+
+            tail page
+               |
+               v
+    +---+    +---+    +---+    +---+
+<---|   |--->|   |-H->|   |--->|   |--->
+--->|   |<---|   |<---|   |<---|   |<---
+    +---+    +---+    +---+    +---+
+
+            tail page
+               |
+               v
+    +---+    +---+    +---+    +---+
+<---|   |--->|   |-U->|   |--->|   |--->
+--->|   |<---|   |<---|   |<---|   |<---
+    +---+    +---+    +---+    +---+
+
+The following page will be made into the new head page.
+
+           tail page
+               |
+               v
+    +---+    +---+    +---+    +---+
+<---|   |--->|   |-U->|   |-H->|   |--->
+--->|   |<---|   |<---|   |<---|   |<---
+    +---+    +---+    +---+    +---+
+
+After the new head page has been set, we can set the old head page
+pointer back to NORMAL.
+
+           tail page
+               |
+               v
+    +---+    +---+    +---+    +---+
+<---|   |--->|   |--->|   |-H->|   |--->
+--->|   |<---|   |<---|   |<---|   |<---
+    +---+    +---+    +---+    +---+
+
+After the head page has been moved, the tail page may now move forward.
+
+                    tail page
+                        |
+                        v
+    +---+    +---+    +---+    +---+
+<---|   |--->|   |--->|   |-H->|   |--->
+--->|   |<---|   |<---|   |<---|   |<---
+    +---+    +---+    +---+    +---+
+
+
+The above are the trivial updates. Now for the more complex scenarios.
+
+
+As stated before, if enough writes preempt the first write, the
+tail page may make it all the way around the buffer and meet the commit
+page. At this time, we must start dropping writes (usually with some kind
+of warning to the user). But what happens if the commit was still on the
+reader page? The commit page is not part of the ring buffer. The tail page
+must account for this.
+
+
+          reader page    commit page
+              |              |
+              v              |
+             +---+           |
+             |   |<----------+
+             |   |
+             |   |------+
+             +---+      |
+                        |
+                        v
+    +---+    +---+    +---+    +---+
+<---|   |--->|   |-H->|   |--->|   |--->
+--->|   |<---|   |<---|   |<---|   |<---
+    +---+    +---+    +---+    +---+
+               ^
+               |
+           tail page
+
+If the tail page were to simply push the head page forward, the commit when
+leaving the reader page would not be pointing to the correct page.
+
+The solution to this is to test if the commit page is on the reader page
+before pushing the head page. If it is, then it can be assumed that the
+tail page wrapped the buffer, and we must drop new writes.
+
+This is not a race condition, because the commit page can only be moved
+by the outter most writer (the writer that was preempted).
+This means that the commit will not move while a writer is moving the
+tail page. The reader can not swap the reader page if it is also being
+used as the commit page. The reader can simply check that the commit
+is off the reader page. Once the commit page leaves the reader page
+it will never go back on it unless a reader does another swap with the
+buffer page that is also the commit page.
+
+
+Nested writes
+-------------
+
+In the pushing forward of the tail page we must first push forward
+the head page if the head page is the next page. If the head page
+is not the next page, the tail page is simply updated with a cmpxchg.
+
+Only writers move the tail page. This must be done atomically to protect
+against nested writers.
+
+  temp_page = tail_page
+  next_page = temp_page->next
+  cmpxchg(tail_page, temp_page, next_page)
+
+The above will update the tail page if it is still pointing to the expected
+page. If this fails, a nested write pushed it forward, the the current write
+does not need to push it.
+
+
+           temp page
+               |
+               v
+            tail page
+               |
+               v
+    +---+    +---+    +---+    +---+
+<---|   |--->|   |--->|   |--->|   |--->
+--->|   |<---|   |<---|   |<---|   |<---
+    +---+    +---+    +---+    +---+
+
+Nested write comes in and moves the tail page forward:
+
+                    tail page (moved by nested writer)
+            temp page   |
+               |        |
+               v        v
+    +---+    +---+    +---+    +---+
+<---|   |--->|   |--->|   |--->|   |--->
+--->|   |<---|   |<---|   |<---|   |<---
+    +---+    +---+    +---+    +---+
+
+The above would fail the cmpxchg, but since the tail page has already
+been moved forward, the writer will just try again to reserve storage
+on the new tail page.
+
+But the moving of the head page is a bit more complex.
+
+            tail page
+               |
+               v
+    +---+    +---+    +---+    +---+
+<---|   |--->|   |-H->|   |--->|   |--->
+--->|   |<---|   |<---|   |<---|   |<---
+    +---+    +---+    +---+    +---+
+
+The write converts the head page pointer to UPDATE.
+
+            tail page
+               |
+               v
+    +---+    +---+    +---+    +---+
+<---|   |--->|   |-U->|   |--->|   |--->
+--->|   |<---|   |<---|   |<---|   |<---
+    +---+    +---+    +---+    +---+
+
+But if a nested writer preempts here. It will see that the next
+page is a head page, but it is also nested. It will detect that
+it is nested and will save that information. The detection is the
+fact that it sees the UPDATE flag instead of a HEADER or NORMAL
+pointer.
+
+The nested writer will set the new head page pointer.
+
+           tail page
+               |
+               v
+    +---+    +---+    +---+    +---+
+<---|   |--->|   |-U->|   |-H->|   |--->
+--->|   |<---|   |<---|   |<---|   |<---
+    +---+    +---+    +---+    +---+
+
+But it will not reset the update back to normal. Only the writer
+that converted a pointer from HEAD to UPDATE will convert it back
+to NORMAL.
+
+                    tail page
+                        |
+                        v
+    +---+    +---+    +---+    +---+
+<---|   |--->|   |-U->|   |-H->|   |--->
+--->|   |<---|   |<---|   |<---|   |<---
+    +---+    +---+    +---+    +---+
+
+After the nested writer finishes, the outer most writer will convert
+the UPDATE pointer to NORMAL.
+
+
+                    tail page
+                        |
+                        v
+    +---+    +---+    +---+    +---+
+<---|   |--->|   |--->|   |-H->|   |--->
+--->|   |<---|   |<---|   |<---|   |<---
+    +---+    +---+    +---+    +---+
+
+
+It can be even more complex if several nested writes came in and moved
+the tail page ahead several pages:
+
+
+(first writer)
+
+            tail page
+               |
+               v
+    +---+    +---+    +---+    +---+
+<---|   |--->|   |-H->|   |--->|   |--->
+--->|   |<---|   |<---|   |<---|   |<---
+    +---+    +---+    +---+    +---+
+
+The write converts the head page pointer to UPDATE.
+
+            tail page
+               |
+               v
+    +---+    +---+    +---+    +---+
+<---|   |--->|   |-U->|   |--->|   |--->
+--->|   |<---|   |<---|   |<---|   |<---
+    +---+    +---+    +---+    +---+
+
+Next writer comes in, and sees the update and sets up the new
+head page.
+
+(second writer)
+
+           tail page
+               |
+               v
+    +---+    +---+    +---+    +---+
+<---|   |--->|   |-U->|   |-H->|   |--->
+--->|   |<---|   |<---|   |<---|   |<---
+    +---+    +---+    +---+    +---+
+
+The nested writer moves the tail page forward. But does not set the old
+update page to NORMAL because it is not the outer most writer.
+
+                    tail page
+                        |
+                        v
+    +---+    +---+    +---+    +---+
+<---|   |--->|   |-U->|   |-H->|   |--->
+--->|   |<---|   |<---|   |<---|   |<---
+    +---+    +---+    +---+    +---+
+
+Another writer preempts and sees the page after the tail page is a head page.
+It changes it from HEAD to UPDATE.
+
+(third writer)
+
+                    tail page
+                        |
+                        v
+    +---+    +---+    +---+    +---+
+<---|   |--->|   |-U->|   |-U->|   |--->
+--->|   |<---|   |<---|   |<---|   |<---
+    +---+    +---+    +---+    +---+
+
+The writer will move the head page forward:
+
+
+(third writer)
+
+                    tail page
+                        |
+                        v
+    +---+    +---+    +---+    +---+
+<---|   |--->|   |-U->|   |-U->|   |-H->
+--->|   |<---|   |<---|   |<---|   |<---
+    +---+    +---+    +---+    +---+
+
+But now that the third writer did change the HEAD flag to UPDATE it
+will convert it to normal:
+
+
+(third writer)
+
+                    tail page
+                        |
+                        v
+    +---+    +---+    +---+    +---+
+<---|   |--->|   |-U->|   |--->|   |-H->
+--->|   |<---|   |<---|   |<---|   |<---
+    +---+    +---+    +---+    +---+
+
+
+Then it will move the tail page, and return back to the second writer.
+
+
+(second writer)
+
+                             tail page
+                                 |
+                                 v
+    +---+    +---+    +---+    +---+
+<---|   |--->|   |-U->|   |--->|   |-H->
+--->|   |<---|   |<---|   |<---|   |<---
+    +---+    +---+    +---+    +---+
+
+
+The second writer will fail to move the tail page because it was already
+moved, so it will try again and add its data to the new tail page.
+It will return to the first writer.
+
+
+(first writer)
+
+                             tail page
+                                 |
+                                 v
+    +---+    +---+    +---+    +---+
+<---|   |--->|   |-U->|   |--->|   |-H->
+--->|   |<---|   |<---|   |<---|   |<---
+    +---+    +---+    +---+    +---+
+
+The first writer can not know atomically test if the tail page moved
+while it updates the HEAD page. It will then update the head page to
+what it thinks is the new head page.
+
+
+(first writer)
+
+                             tail page
+                                 |
+                                 v
+    +---+    +---+    +---+    +---+
+<---|   |--->|   |-U->|   |-H->|   |-H->
+--->|   |<---|   |<---|   |<---|   |<---
+    +---+    +---+    +---+    +---+
+
+Since the cmpxchg returns the old value of the pointer the first writer
+will see it succeeded in updating the pointer from NORMAL to HEAD.
+But as we can see, this is not good enough. It must also check to see
+if the tail page is either where it use to be or on the next page:
+
+
+(first writer)
+
+               A        B    tail page
+               |        |        |
+               v        v        v
+    +---+    +---+    +---+    +---+
+<---|   |--->|   |-U->|   |-H->|   |-H->
+--->|   |<---|   |<---|   |<---|   |<---
+    +---+    +---+    +---+    +---+
+
+If tail page != A and tail page does not equal B, then it must reset the
+pointer back to NORMAL. The fact that it only needs to worry about
+nested writers, it only needs to check this after setting the HEAD page.
+
+
+(first writer)
+
+               A        B    tail page
+               |        |        |
+               v        v        v
+    +---+    +---+    +---+    +---+
+<---|   |--->|   |-U->|   |--->|   |-H->
+--->|   |<---|   |<---|   |<---|   |<---
+    +---+    +---+    +---+    +---+
+
+Now the writer can update the head page. This is also why the head page must
+remain in UPDATE and only reset by the outer most writer. This prevents
+the reader from seeing the incorrect head page.
+
+
+(first writer)
+
+               A        B    tail page
+               |        |        |
+               v        v        v
+    +---+    +---+    +---+    +---+
+<---|   |--->|   |--->|   |--->|   |-H->
+--->|   |<---|   |<---|   |<---|   |<---
+    +---+    +---+    +---+    +---+
+
-- 
1.6.3.1

-- 

^ permalink raw reply related	[flat|nested] 29+ messages in thread

* Re: [PATCH 3/3] ring-buffer: add design document
  2009-06-10 19:53 ` [PATCH 3/3] ring-buffer: add design document Steven Rostedt
@ 2009-06-10 22:13   ` Mathieu Desnoyers
  2009-06-11  1:55     ` Steven Rostedt
  2009-06-11  0:51   ` Huang Ying
                     ` (3 subsequent siblings)
  4 siblings, 1 reply; 29+ messages in thread
From: Mathieu Desnoyers @ 2009-06-10 22:13 UTC (permalink / raw)
  To: Steven Rostedt
  Cc: linux-kernel, Ingo Molnar, Andrew Morton, Thomas Gleixner,
	Peter Zijlstra, Frederic Weisbecker, Theodore Tso,
	Arnaldo Carvalho de Melo, Lai Jiangshan, Martin J. Bligh,
	Christoph Hellwig, Li Zefan, Huang Ying, H. Peter Anvin,
	Hidetoshi Seto, Masami Hiramatsu, ltt-dev, Robert Wisniewski,
	Paul E. McKenney

* Steven Rostedt (rostedt@goodmis.org) wrote:
> From: Steven Rostedt <srostedt@redhat.com>
> 
> This adds the design document for the ring buffer and also
> explains how it is designed to have lockless writes.
> 
> Signed-off-by: Steven Rostedt <rostedt@goodmis.org>
> ---
>  Documentation/trace/ring-buffer-design.txt |  949 ++++++++++++++++++++++++++++
>  1 files changed, 949 insertions(+), 0 deletions(-)
>  create mode 100644 Documentation/trace/ring-buffer-design.txt
> 
> diff --git a/Documentation/trace/ring-buffer-design.txt b/Documentation/trace/ring-buffer-design.txt
> new file mode 100644
> index 0000000..cca290b
> --- /dev/null
> +++ b/Documentation/trace/ring-buffer-design.txt
> @@ -0,0 +1,949 @@
> +		Lockless Ring Buffer Design
> +		===========================
> +
> +Copyright 2009 Red Hat Inc.
> +   Author:   Steven Rostedt <srostedt@redhat.com>
> +  License:   The GNU Free Documentation License, Version 1.2
> +               (dual licensed under the GPL v2)
> +
> +Written for: 2.6.31
> +
> +Terminology used in this Document
> +---------------------------------
> +
> +tail - where new writes happen in the ring buffer.
> +
> +head - where new reads happen in the ring buffer.
> +
> +producer - the task that writes into the ring buffer (same as writer)
> +
> +writer - same as producer
> +
> +consumer - the task that reads from the buffer (same as reader)
> +
> +reader - same as consumer.
> +
> +reader_page - A page outside the ring buffer used solely (for the most part)
> +    by the reader.
> +
> +head_page - a pointer to the page that the reader will use next
> +
> +tail_page - a pointer to the page that will be written to next
> +
> +commit_page - a pointer to the page with the last finished non nested write.
> +
> +cmpxchg - hardware assisted atomic transaction that performs the following:
> +
> +   A = B iff previous A == C
> +
> +   R = cmpxchg(A, C, B) is saying that we replace A with B if and only if
> +      current A is equal to C, and we put the old (current) A into R
> +
> +   R gets the previous A regardless if A is updated with B or not.
> +
> +   To see if the update was successful a compare of R == C may be used.
> +
> +The Generic Ring Buffer
> +-----------------------
> +
> +The ring buffer can be used in either an overwrite mode or in
> +producer/consumer mode.
> +
> +Producer/consumer mode is where the producer were to fill up the
> +buffer before the consumer could free up anything, the producer
> +will stop writing to the buffer. This will lose most recent events.
> +
> +Overwrite mode is where the produce were to fill up the buffer
> +before the consumer could free up anything, the producer will
> +overwrite the older data. This will lose the oldest events.
> +
> +No two writers can write at the same time (on the same per cpu buffer),
> +but a writer may preempt another writer, but it must finish writing

Hi Steven,

I would use "interrupt" instead of "preempt" here, given that preemption
implies scheduler activity which is specifically forbidden here.

> +before the previous writer may continue. This is very important to the
> +algorithm. The writers act like a "stack".
> +
> +
> +  writer1 start
> +     <preempted> writer2 start
> +         <preempted> writer3 start
> +                     writer3 finishes
> +                 writer2 finishes
> +  writer1 finishes
> +
> +This is very much like a writer being preempted by an interrupt and
> +the interrupt doing a write as well.
> +
> +Readers can happen at any time. But no two readers may run at the
> +same time, nor can a reader preempt another reader. A reader can not preempt
> +a writer, but it may read/consume from the buffer at the same time as
> +a writer is writing, but the reader must be on another processor.
> +
> +A writer can preempt a reader, but a reader can not preempt a writer.
> +But a reader can read the buffer at the same time (on another processor)
> +as a writer.
> +

This comment is inconsistent with the following code comment :

"* Reads can happen on any CPU."

Readers should be allowed to read from their own cpu's buffers too, and
support being interrupted by an incoming interrupt writer, but this
design document does not discuss this case. Is it at all supported ? If
not, then this algorithm would not work on uniprocessor.

> +The ring buffer is made up of a list of pages held together by a link list.
> +
> +At initialization a reader page is allocated for the reader that is not
> +part of the ring buffer.
> +
> +The head_page, tail_page and commit_page are all initialized to point
> +to the same page.
> +
> +The reader page is initialized to have its next pointer pointing to
> +the head page, and its previous pointer pointing to a page before
> +the head page.
> +
> +The reader has its own page to use. At start up time, this page is
> +allocated but is not attached to the list. When the reader wants
> +to read from the buffer, if its page is empty (like it is on start up)
> +it will swap its page with the head_page. The old reader page will
> +become part of the ring buffer and the head_page will be removed.
> +A new head page goes to the page after the old head page (but not
> +the page that was swapped in).
> +
> +Once the new page is given to the reader, the reader could do what
> +it wants with it, as long as a writer has left that page.
> +
> +A sample of how the reader page is swapped: Note this does not
> +show the head page in the buffer, it is for demonstrating a swap
> +only.
> +
> +  +------+
> +  |reader|          RING BUFFER
> +  |page  |
> +  +------+
> +                  +---+   +---+   +---+
> +                  |   |-->|   |-->|   |
> +                  |   |<--|   |<--|   |
> +                  +---+   +---+   +---+
> +                   ^ |             ^ |
> +                   | +-------------+ |
> +                   +-----------------+
> +
> +
> +  +------+
> +  |reader|          RING BUFFER
> +  |page  |-------------------+
> +  +------+                   v
> +    |             +---+   +---+   +---+
> +    |             |   |-->|   |-->|   |
> +    |             |   |<--|   |<--|   |<-+
> +    |             +---+   +---+   +---+  |
> +    |              ^ |             ^ |   |
> +    |              | +-------------+ |   |
> +    |              +-----------------+   |
> +    +------------------------------------+
> +
> +  +------+
> +  |reader|          RING BUFFER
> +  |page  |-------------------+
> +  +------+ <---------------+ v
> +    |  ^          +---+   +---+   +---+
> +    |  |          |   |-->|   |-->|   |
> +    |  |          |   |<--|   |<--|   |<-+
> +    |  |          +---+   +---+   +---+  |
> +    |  |             |             ^ |   |
> +    |  |             +-------------+ |   |
> +    |  +-----------------------------+   |
> +    +------------------------------------+
> +
> +  +------+
> +  |buffer|          RING BUFFER
> +  |page  |-------------------+
> +  +------+ <---------------+ v
> +    |  ^          +---+   +---+   +---+
> +    |  |          |   |   |   |-->|   |
> +    |  |  New     |   |   |   |<--|   |<-+
> +    |  | Reader   +---+   +---+   +---+  |
> +    |  |  page ----^                 |   |
> +    |  |                             |   |
> +    |  +-----------------------------+   |
> +    +------------------------------------+
> +

Nice ascii art ;)

Some important comments below,

> +
> +
> +It is possible that the page swapped is the commit page and the tail page,
> +if what is in the ring buffer is less than what is held in a buffer page.
> +
> +
> +          reader page    commit page   tail page
> +              |              |             |
> +              v              |             |
> +             +---+           |             |
> +             |   |<----------+             |
> +             |   |<------------------------+
> +             |   |------+
> +             +---+      |
> +                        |
> +                        v
> +    +---+    +---+    +---+    +---+
> +<---|   |--->|   |--->|   |--->|   |--->
> +--->|   |<---|   |<---|   |<---|   |<---
> +    +---+    +---+    +---+    +---+
> +
> +This case is still legal for this algorithm.
> +When the writer leaves the page, it simply goes into the ring buffer
> +since the reader page still points to the next location in the ring
> +buffer.
> +
> +
> +The main pointers:
> +
> +  reader page - The page used solely by the reader and is not part
> +                of the ring buffer (may be swapped in)
> +
> +  head page - the next page in the ring buffer that will be swapped
> +              with the reader page.
> +
> +  tail page - the page where the next write will take place.
> +
> +  commit page - the page that last finished a write.
> +
> +The commit page only is updated by the outer most writer in the
> +writer stack. A writer that preempts another writer will not move the
> +commit page.
> +
> +When data is written into the ring buffer, a position is reserved
> +in the ring buffer and passed back to the writer. When the writer
> +is finished writing data into that position, it commits the write.
> +
> +Another write (or a read) may take place at anytime during this
> +transaction. If another write happens it must finish before continuing
> +with the previous write.
> +
> +
> +   Write reserve:
> +
> +       Buffer page
> +      +---------+
> +      |written  |
> +      +---------+  <--- given back to writer (current commit)
> +      |reserved |
> +      +---------+ <--- tail pointer
> +      | empty   |
> +      +---------+
> +
> +   Write commit:
> +
> +       Buffer page
> +      +---------+
> +      |written  |
> +      +---------+
> +      |written  |
> +      +---------+  <--- next positon for write (current commit)
> +      | empty   |
> +      +---------+
> +
> +
> + If a write happens after the first reserve:
> +
> +       Buffer page
> +      +---------+
> +      |written  |
> +      +---------+  <-- current commit
> +      |reserved |
> +      +---------+  <--- given back to second writer
> +      |reserved |
> +      +---------+ <--- tail pointer
> +
> +  After second writer commits:
> +
> +
> +       Buffer page
> +      +---------+
> +      |written  |
> +      +---------+  <--(last full commit)
> +      |reserved |
> +      +---------+
> +      |pending  |
> +      |commit   |
> +      +---------+ <--- tail pointer
> +
> +  When the first writer commits:
> +
> +       Buffer page
> +      +---------+
> +      |written  |
> +      +---------+
> +      |written  |
> +      +---------+
> +      |written  |
> +      +---------+  <--(last full commit and tail pointer)
> +
> +
> +The commit pointer points to the last write location that was
> +committed without preempting another write. When a write that
> +preempted another write is committed, it only becomes a pending commit
> +and will not be a full commit till all writes have been committed.
> +
> +The commit page points to the page that has the last full commit.
> +The tail page points to the page with the last write (before
> +committing).
> +
> +The tail page is always equal to or after the commit page. It may
> +be several pages ahead. If the tail page catches up to the commit
> +page then no more writes may take place (regardless of the mode
> +of the ring buffer: overwrite and produce/consumer).
> +
> +The order of pages are:
> +
> + head page
> + commit page
> + tail page
> +
> +Possible scenario:
> +                             tail page
> +  head page         commit page  |
> +      |                 |        |
> +      v                 v        v
> +    +---+    +---+    +---+    +---+
> +<---|   |--->|   |--->|   |--->|   |--->
> +--->|   |<---|   |<---|   |<---|   |<---
> +    +---+    +---+    +---+    +---+
> +
> +There is a special case that the head page is after either the commit page
> +and possibly the tail page. That is when the commit (and tail) page has been
> +swapped with the reader page. This is because the head page is always
> +part of the ring buffer, but the reader page is not. When ever there
> +has been less than a full page that has been committed inside the ring buffer,
> +and a reader swaps out a page, it will be swapping out the commit page.
> +
> +
> +          reader page    commit page   tail page
> +              |              |             |
> +              v              |             |
> +             +---+           |             |
> +             |   |<----------+             |
> +             |   |<------------------------+
> +             |   |------+
> +             +---+      |
> +                        |
> +                        v
> +    +---+    +---+    +---+    +---+
> +<---|   |--->|   |--->|   |--->|   |--->
> +--->|   |<---|   |<---|   |<---|   |<---
> +    +---+    +---+    +---+    +---+
> +                        ^
> +                        |
> +                    head page
> +
> +
> +In this case, the head page will not move when the tail and commit
> +move back into the ring buffer.
> +
> +The reader can not swap a page into the ring buffer if the commit page
> +is still on that page. If the read meets the last commit (real commit
> +not pending or reserved), then there is nothing more to read.
> +The buffer is considered empty until another full commit finishes.
> +
> +When the tail meets the head page, if the buffer is in overwrite mode,
> +the head page will be pushed ahead one. If the buffer is in producer/consumer
> +mode, the write will fail.
> +
> +Overwrite mode:
> +
> +            tail page
> +               |
> +               v
> +    +---+    +---+    +---+    +---+
> +<---|   |--->|   |--->|   |--->|   |--->
> +--->|   |<---|   |<---|   |<---|   |<---
> +    +---+    +---+    +---+    +---+
> +                        ^
> +                        |
> +                    head page
> +
> +
> +            tail page
> +               |
> +               v
> +    +---+    +---+    +---+    +---+
> +<---|   |--->|   |--->|   |--->|   |--->
> +--->|   |<---|   |<---|   |<---|   |<---
> +    +---+    +---+    +---+    +---+
> +                                 ^
> +                                 |
> +                             head page
> +
> +
> +                    tail page
> +                        |
> +                        v
> +    +---+    +---+    +---+    +---+
> +<---|   |--->|   |--->|   |--->|   |--->
> +--->|   |<---|   |<---|   |<---|   |<---
> +    +---+    +---+    +---+    +---+
> +                                 ^
> +                                 |
> +                             head page
> +
> +Note, the reader page will still point to the previous head page.
> +But when a swap takes place, it will use the most recent head page.
> +
> +
> +Making the Ring Buffer Lockless:
> +--------------------------------
> +
> +The main idea behind the lockless algorithm is to combine the moving
> +of the head_page pointer with the swapping of pages with the reader.
> +State flags are placed inside the pointer to the page. To do this,
> +each page must be aligned in memory by 4 bytes. This will allow the 2
> +least significant bits of the address to be used as flags. Since
> +they will always be zero for the address. To get the address,
> +simply mask out the flags.
> +
> +  MASK = ~3
> +
> +  address & MASK
> +
> +Two flags will be kept by these two bits:
> +
> +   HEADER - the page being pointed to is a head page
> +
> +   UPDATE - the page being pointed to is being updated by a writer
> +          and was or is about to be a head page.
> +
> +
> +          reader page
> +              |
> +              v
> +             +---+
> +             |   |------+
> +             +---+      |
> +                        |
> +                        v
> +    +---+    +---+    +---+    +---+
> +<---|   |--->|   |-H->|   |--->|   |--->
> +--->|   |<---|   |<---|   |<---|   |<---
> +    +---+    +---+    +---+    +---+
> +
> +
> +The above pointer "-H->" would have the HEADER flag set. That is
> +the next page is the next page to be swapped out by the reader.
> +This pointer means the next page is the head page.
> +
> +When the tail page meets the head pointer, it will use cmpxchg to
> +change the pointer to the UPDATE state:
> +
> +
> +            tail page
> +               |
> +               v
> +    +---+    +---+    +---+    +---+
> +<---|   |--->|   |-H->|   |--->|   |--->
> +--->|   |<---|   |<---|   |<---|   |<---
> +    +---+    +---+    +---+    +---+
> +
> +            tail page
> +               |
> +               v
> +    +---+    +---+    +---+    +---+
> +<---|   |--->|   |-U->|   |--->|   |--->
> +--->|   |<---|   |<---|   |<---|   |<---
> +    +---+    +---+    +---+    +---+
> +
> +"-U->" represents a pointer in the UPDATE state.
> +
> +Any access to the reader will need to take some sort of lock to serialize
> +the readers. But the writers will never take a lock to write to the
> +ring buffer. This means we only need to worry about a single reader,
> +and writes only preempt in "stack" formation.
> +
> +When the reader tries to swap the page with the ring buffer, it
> +will also use cmpxchg. If the flag bit in the pointer to the
> +head page does not have the HEADER flag set, the compare will fail
> +and the reader will need to look for the new head page and try again.
> +Note, the flag UPDATE and HEADER are never set at the same time.
> +
> +The reader swaps the reader page as follows:
> +
> +  +------+
> +  |reader|          RING BUFFER
> +  |page  |
> +  +------+
> +                  +---+    +---+    +---+
> +                  |   |--->|   |--->|   |
> +                  |   |<---|   |<---|   |
> +                  +---+    +---+    +---+
> +                   ^ |               ^ |
> +                   | +---------------+ |
> +                   +-----H-------------+
> +
> +The reader sets the reader page next pointer as HEADER to the page after
> +the head page.
> +
> +
> +  +------+
> +  |reader|          RING BUFFER
> +  |page  |-------H-----------+
> +  +------+                   v
> +    |             +---+    +---+    +---+
> +    |             |   |--->|   |--->|   |
> +    |             |   |<---|   |<---|   |<-+
> +    |             +---+    +---+    +---+  |
> +    |              ^ |               ^ |   |
> +    |              | +---------------+ |   |
> +    |              +-----H-------------+   |
> +    +--------------------------------------+
> +
> +It does a cmpxchg with the pointer to the previous head page to make it
> +point to the reader page. Note that the new pointer does not have the HEADER
> +flag set.  This action atomically moves the head page forward.
> +
> +  +------+
> +  |reader|          RING BUFFER
> +  |page  |-------H-----------+
> +  +------+ <---------------+ v
> +    |  ^          +---+   +---+   +---+
> +    |  |          |   |-->|   |-->|   |
> +    |  |          |   |<--|   |<--|   |<-+
> +    |  |          +---+   +---+   +---+  |
> +    |  |             |             ^ |   |
> +    |  |             +-------------+ |   |
> +    |  +-----------------------------+   |
> +    +------------------------------------+
> +
> +After the new head page is set, the previous pointer of the head page is
> +updated to the reader page.
> +
> +  +------+
> +  |reader|          RING BUFFER
> +  |page  |-------H-----------+
> +  +------+                   v
> +    |  ^          +---+   +---+   +---+
> +    |  |          |   |-->|   |-->|   |
> +    |  |          |   |<--|   |<--|   |<-+
> +    |  |          +---+   +---+   +---+  |
> +    |  |             |             ^ |   |
> +    |  |             +-------------+ |   |
> +    |  +-----------------------------+   |
> +    +------------------------------------+
> +
> +  +------+
> +  |buffer|          RING BUFFER
> +  |page  |-------H-----------+  <--- New head page
> +  +------+ <---------------+ v
> +    |  ^          +---+   +---+   +---+
> +    |  |          |   |   |   |-->|   |
> +    |  |  New     |   |   |   |<--|   |<-+
> +    |  | Reader   +---+   +---+   +---+  |
> +    |  |  page ----^                 |   |
> +    |  |                             |   |
> +    |  +-----------------------------+   |
> +    +------------------------------------+
> +
> +Another important point. The page that the reader page points back to
> +by its previous pointer (the one that now points to the new head page)
> +never points back to the reader page. That is because the reader page is
> +not part of the ring buffer. Traversing the ring buffer via the next pointers
> +will always stay in the ring buffer. Traversing the ring buffer via the
> +prev pointers may not.
> +
> +Note, the way to determine a reader page is simply by examining the previous
> +pointer of the page. If the next pointer of the previous page does not
> +point back to the original page, then the original page is a reader page:
> +
> +                                  
> +             +--------+
> +             | reader |  next   +----+
> +             |  page  |-------->|    |<====== (buffer page)
> +             +--------+         +----+
> +                 |                | ^
> +                 |                v | next
> +            prev |              +----+
> +                 +------------->|    |
> +                                +----+
> +
> +The way the head page moves forward:
> +
> +When the tail page meets the head page and the buffer is in overwrite mode
> +and more writes take place, the head page must be moved forward before the
> +writer may move the tail page. The way this is done is that the writer
> +performs a cmpxchg to convert the pointer to the head page from the HEADER
> +flag to have the UPDATE flag set. Once this is done, the reader will
> +not be able to swap the head page from the buffer, nor will it be able to
> +move the head page, until the writer is finished with the move.
> +
> +This eliminates any races that the reader can have on the writer. The reader
> +must spin, and this is why the reader can not preempt the writer.
> +
> +            tail page
> +               |
> +               v
> +    +---+    +---+    +---+    +---+
> +<---|   |--->|   |-H->|   |--->|   |--->
> +--->|   |<---|   |<---|   |<---|   |<---
> +    +---+    +---+    +---+    +---+
> +
> +            tail page
> +               |
> +               v
> +    +---+    +---+    +---+    +---+
> +<---|   |--->|   |-U->|   |--->|   |--->
> +--->|   |<---|   |<---|   |<---|   |<---
> +    +---+    +---+    +---+    +---+
> +
> +The following page will be made into the new head page.
> +
> +           tail page
> +               |
> +               v
> +    +---+    +---+    +---+    +---+
> +<---|   |--->|   |-U->|   |-H->|   |--->
> +--->|   |<---|   |<---|   |<---|   |<---
> +    +---+    +---+    +---+    +---+
> +
> +After the new head page has been set, we can set the old head page
> +pointer back to NORMAL.
> +
> +           tail page
> +               |
> +               v
> +    +---+    +---+    +---+    +---+
> +<---|   |--->|   |--->|   |-H->|   |--->
> +--->|   |<---|   |<---|   |<---|   |<---
> +    +---+    +---+    +---+    +---+
> +
> +After the head page has been moved, the tail page may now move forward.
> +
> +                    tail page
> +                        |
> +                        v
> +    +---+    +---+    +---+    +---+
> +<---|   |--->|   |--->|   |-H->|   |--->
> +--->|   |<---|   |<---|   |<---|   |<---
> +    +---+    +---+    +---+    +---+
> +
> +
> +The above are the trivial updates. Now for the more complex scenarios.
> +
> +
> +As stated before, if enough writes preempt the first write, the
> +tail page may make it all the way around the buffer and meet the commit
> +page. At this time, we must start dropping writes (usually with some kind
> +of warning to the user). But what happens if the commit was still on the
> +reader page? The commit page is not part of the ring buffer. The tail page
> +must account for this.
> +
> +
> +          reader page    commit page
> +              |              |
> +              v              |
> +             +---+           |
> +             |   |<----------+
> +             |   |
> +             |   |------+
> +             +---+      |
> +                        |
> +                        v
> +    +---+    +---+    +---+    +---+
> +<---|   |--->|   |-H->|   |--->|   |--->
> +--->|   |<---|   |<---|   |<---|   |<---
> +    +---+    +---+    +---+    +---+
> +               ^
> +               |
> +           tail page
> +
> +If the tail page were to simply push the head page forward, the commit when
> +leaving the reader page would not be pointing to the correct page.
> +
> +The solution to this is to test if the commit page is on the reader page
> +before pushing the head page. If it is, then it can be assumed that the
> +tail page wrapped the buffer, and we must drop new writes.
> +
> +This is not a race condition, because the commit page can only be moved
> +by the outter most writer (the writer that was preempted).
> +This means that the commit will not move while a writer is moving the
> +tail page. The reader can not swap the reader page if it is also being
> +used as the commit page. The reader can simply check that the commit
> +is off the reader page. Once the commit page leaves the reader page
> +it will never go back on it unless a reader does another swap with the
> +buffer page that is also the commit page.
> +
> +
> +Nested writes
> +-------------
> +
> +In the pushing forward of the tail page we must first push forward
> +the head page if the head page is the next page. If the head page
> +is not the next page, the tail page is simply updated with a cmpxchg.
> +
> +Only writers move the tail page. This must be done atomically to protect
> +against nested writers.
> +
> +  temp_page = tail_page
> +  next_page = temp_page->next
> +  cmpxchg(tail_page, temp_page, next_page)
> +

OK, I'll bite :

What happens if :

- a writer is at the end of a page, 
- needs to push the tail_page pointer
- reads tail_page
  - interrupted.
  - nested writers come, successfully updates the tail_page, write
    enough data to fill the whole buffer
  - concurrently (on another CPU), a reader is consuming all the data
  - This brings the tail_page pointer back to its original value
  - iret
- here, the writer will successfully perform the tail_page cmpxchg,
  because the value match. However, the page currently being written to
  could be only partially reserved; the writer will not re-check if the
  page is really full.

That's actually one of my main concerns with an approach where two
separate "pointers" are used to keep track of reserved space within a
buffer.

The same concern applies to moving the head page when concurrent writers
are nesting.

More generally, I'm also concerned about the lack of memory barriers
around some non-cmpxchg tail/head page set operations in your code, and
the lack of proper rcu_dereference-style primitive for list iteration.

For those I've added to CC, I'm referring to the patch at :

http://patchwork.kernel.org/patch/29395/

The great news to me is that no one can say LTTng's lockless buffering
algorithm is complex compared to this. ;)

Mathieu

> +The above will update the tail page if it is still pointing to the expected
> +page. If this fails, a nested write pushed it forward, the the current write
> +does not need to push it.
> +
> +
> +           temp page
> +               |
> +               v
> +            tail page
> +               |
> +               v
> +    +---+    +---+    +---+    +---+
> +<---|   |--->|   |--->|   |--->|   |--->
> +--->|   |<---|   |<---|   |<---|   |<---
> +    +---+    +---+    +---+    +---+
> +
> +Nested write comes in and moves the tail page forward:
> +
> +                    tail page (moved by nested writer)
> +            temp page   |
> +               |        |
> +               v        v
> +    +---+    +---+    +---+    +---+
> +<---|   |--->|   |--->|   |--->|   |--->
> +--->|   |<---|   |<---|   |<---|   |<---
> +    +---+    +---+    +---+    +---+
> +
> +The above would fail the cmpxchg, but since the tail page has already
> +been moved forward, the writer will just try again to reserve storage
> +on the new tail page.
> +
> +But the moving of the head page is a bit more complex.
> +
> +            tail page
> +               |
> +               v
> +    +---+    +---+    +---+    +---+
> +<---|   |--->|   |-H->|   |--->|   |--->
> +--->|   |<---|   |<---|   |<---|   |<---
> +    +---+    +---+    +---+    +---+
> +
> +The write converts the head page pointer to UPDATE.
> +
> +            tail page
> +               |
> +               v
> +    +---+    +---+    +---+    +---+
> +<---|   |--->|   |-U->|   |--->|   |--->
> +--->|   |<---|   |<---|   |<---|   |<---
> +    +---+    +---+    +---+    +---+
> +
> +But if a nested writer preempts here. It will see that the next
> +page is a head page, but it is also nested. It will detect that
> +it is nested and will save that information. The detection is the
> +fact that it sees the UPDATE flag instead of a HEADER or NORMAL
> +pointer.
> +
> +The nested writer will set the new head page pointer.
> +
> +           tail page
> +               |
> +               v
> +    +---+    +---+    +---+    +---+
> +<---|   |--->|   |-U->|   |-H->|   |--->
> +--->|   |<---|   |<---|   |<---|   |<---
> +    +---+    +---+    +---+    +---+
> +
> +But it will not reset the update back to normal. Only the writer
> +that converted a pointer from HEAD to UPDATE will convert it back
> +to NORMAL.
> +
> +                    tail page
> +                        |
> +                        v
> +    +---+    +---+    +---+    +---+
> +<---|   |--->|   |-U->|   |-H->|   |--->
> +--->|   |<---|   |<---|   |<---|   |<---
> +    +---+    +---+    +---+    +---+
> +
> +After the nested writer finishes, the outer most writer will convert
> +the UPDATE pointer to NORMAL.
> +
> +
> +                    tail page
> +                        |
> +                        v
> +    +---+    +---+    +---+    +---+
> +<---|   |--->|   |--->|   |-H->|   |--->
> +--->|   |<---|   |<---|   |<---|   |<---
> +    +---+    +---+    +---+    +---+
> +
> +
> +It can be even more complex if several nested writes came in and moved
> +the tail page ahead several pages:
> +
> +
> +(first writer)
> +
> +            tail page
> +               |
> +               v
> +    +---+    +---+    +---+    +---+
> +<---|   |--->|   |-H->|   |--->|   |--->
> +--->|   |<---|   |<---|   |<---|   |<---
> +    +---+    +---+    +---+    +---+
> +
> +The write converts the head page pointer to UPDATE.
> +
> +            tail page
> +               |
> +               v
> +    +---+    +---+    +---+    +---+
> +<---|   |--->|   |-U->|   |--->|   |--->
> +--->|   |<---|   |<---|   |<---|   |<---
> +    +---+    +---+    +---+    +---+
> +
> +Next writer comes in, and sees the update and sets up the new
> +head page.
> +
> +(second writer)
> +
> +           tail page
> +               |
> +               v
> +    +---+    +---+    +---+    +---+
> +<---|   |--->|   |-U->|   |-H->|   |--->
> +--->|   |<---|   |<---|   |<---|   |<---
> +    +---+    +---+    +---+    +---+
> +
> +The nested writer moves the tail page forward. But does not set the old
> +update page to NORMAL because it is not the outer most writer.
> +
> +                    tail page
> +                        |
> +                        v
> +    +---+    +---+    +---+    +---+
> +<---|   |--->|   |-U->|   |-H->|   |--->
> +--->|   |<---|   |<---|   |<---|   |<---
> +    +---+    +---+    +---+    +---+
> +
> +Another writer preempts and sees the page after the tail page is a head page.
> +It changes it from HEAD to UPDATE.
> +
> +(third writer)
> +
> +                    tail page
> +                        |
> +                        v
> +    +---+    +---+    +---+    +---+
> +<---|   |--->|   |-U->|   |-U->|   |--->
> +--->|   |<---|   |<---|   |<---|   |<---
> +    +---+    +---+    +---+    +---+
> +
> +The writer will move the head page forward:
> +
> +
> +(third writer)
> +
> +                    tail page
> +                        |
> +                        v
> +    +---+    +---+    +---+    +---+
> +<---|   |--->|   |-U->|   |-U->|   |-H->
> +--->|   |<---|   |<---|   |<---|   |<---
> +    +---+    +---+    +---+    +---+
> +
> +But now that the third writer did change the HEAD flag to UPDATE it
> +will convert it to normal:
> +
> +
> +(third writer)
> +
> +                    tail page
> +                        |
> +                        v
> +    +---+    +---+    +---+    +---+
> +<---|   |--->|   |-U->|   |--->|   |-H->
> +--->|   |<---|   |<---|   |<---|   |<---
> +    +---+    +---+    +---+    +---+
> +
> +
> +Then it will move the tail page, and return back to the second writer.
> +
> +
> +(second writer)
> +
> +                             tail page
> +                                 |
> +                                 v
> +    +---+    +---+    +---+    +---+
> +<---|   |--->|   |-U->|   |--->|   |-H->
> +--->|   |<---|   |<---|   |<---|   |<---
> +    +---+    +---+    +---+    +---+
> +
> +
> +The second writer will fail to move the tail page because it was already
> +moved, so it will try again and add its data to the new tail page.
> +It will return to the first writer.
> +
> +
> +(first writer)
> +
> +                             tail page
> +                                 |
> +                                 v
> +    +---+    +---+    +---+    +---+
> +<---|   |--->|   |-U->|   |--->|   |-H->
> +--->|   |<---|   |<---|   |<---|   |<---
> +    +---+    +---+    +---+    +---+
> +
> +The first writer can not know atomically test if the tail page moved
> +while it updates the HEAD page. It will then update the head page to
> +what it thinks is the new head page.
> +
> +
> +(first writer)
> +
> +                             tail page
> +                                 |
> +                                 v
> +    +---+    +---+    +---+    +---+
> +<---|   |--->|   |-U->|   |-H->|   |-H->
> +--->|   |<---|   |<---|   |<---|   |<---
> +    +---+    +---+    +---+    +---+
> +
> +Since the cmpxchg returns the old value of the pointer the first writer
> +will see it succeeded in updating the pointer from NORMAL to HEAD.
> +But as we can see, this is not good enough. It must also check to see
> +if the tail page is either where it use to be or on the next page:
> +
> +
> +(first writer)
> +
> +               A        B    tail page
> +               |        |        |
> +               v        v        v
> +    +---+    +---+    +---+    +---+
> +<---|   |--->|   |-U->|   |-H->|   |-H->
> +--->|   |<---|   |<---|   |<---|   |<---
> +    +---+    +---+    +---+    +---+
> +
> +If tail page != A and tail page does not equal B, then it must reset the
> +pointer back to NORMAL. The fact that it only needs to worry about
> +nested writers, it only needs to check this after setting the HEAD page.
> +
> +
> +(first writer)
> +
> +               A        B    tail page
> +               |        |        |
> +               v        v        v
> +    +---+    +---+    +---+    +---+
> +<---|   |--->|   |-U->|   |--->|   |-H->
> +--->|   |<---|   |<---|   |<---|   |<---
> +    +---+    +---+    +---+    +---+
> +
> +Now the writer can update the head page. This is also why the head page must
> +remain in UPDATE and only reset by the outer most writer. This prevents
> +the reader from seeing the incorrect head page.
> +
> +
> +(first writer)
> +
> +               A        B    tail page
> +               |        |        |
> +               v        v        v
> +    +---+    +---+    +---+    +---+
> +<---|   |--->|   |--->|   |--->|   |-H->
> +--->|   |<---|   |<---|   |<---|   |<---
> +    +---+    +---+    +---+    +---+
> +
> -- 
> 1.6.3.1
> 
> -- 
> 

-- 
Mathieu Desnoyers
OpenPGP key fingerprint: 8CD5 52C3 8E3C 4140 715F  BA06 3F25 A8FE 3BAE 9A68

^ permalink raw reply	[flat|nested] 29+ messages in thread

* Re: [PATCH 3/3] ring-buffer: add design document
  2009-06-10 19:53 ` [PATCH 3/3] ring-buffer: add design document Steven Rostedt
  2009-06-10 22:13   ` Mathieu Desnoyers
@ 2009-06-11  0:51   ` Huang Ying
  2009-06-11  0:54     ` H. Peter Anvin
  2009-06-11  1:58     ` Steven Rostedt
  2009-06-11  3:15   ` Hidetoshi Seto
                     ` (2 subsequent siblings)
  4 siblings, 2 replies; 29+ messages in thread
From: Huang Ying @ 2009-06-11  0:51 UTC (permalink / raw)
  To: Steven Rostedt
  Cc: linux-kernel, Ingo Molnar, Andrew Morton, Thomas Gleixner,
	Peter Zijlstra, Frederic Weisbecker, Theodore Tso,
	Arnaldo Carvalho de Melo, Mathieu Desnoyers, Lai Jiangshan,
	Martin J. Bligh, Christoph Hellwig, Li Zefan, H. Peter Anvin,
	Hidetoshi Seto, Masami Hiramatsu

On Thu, 2009-06-11 at 03:53 +0800, Steven Rostedt wrote:
> +
> +cmpxchg - hardware assisted atomic transaction that performs the following:
> +
> +   A = B iff previous A == C
> +
> +   R = cmpxchg(A, C, B) is saying that we replace A with B if and only if
> +      current A is equal to C, and we put the old (current) A into R
> +
> +   R gets the previous A regardless if A is updated with B or not.
> +
> +   To see if the update was successful a compare of R == C may be used.

As far as I know, some architectures have no hardware assisted (NMI
safe) cmpxchg. Is it OK to use cmpxchg in architecture-independent code?

Best Regards,
Huang Ying



^ permalink raw reply	[flat|nested] 29+ messages in thread

* Re: [PATCH 3/3] ring-buffer: add design document
  2009-06-11  0:51   ` Huang Ying
@ 2009-06-11  0:54     ` H. Peter Anvin
  2009-06-11  1:58     ` Steven Rostedt
  1 sibling, 0 replies; 29+ messages in thread
From: H. Peter Anvin @ 2009-06-11  0:54 UTC (permalink / raw)
  To: Huang Ying
  Cc: Steven Rostedt, linux-kernel, Ingo Molnar, Andrew Morton,
	Thomas Gleixner, Peter Zijlstra, Frederic Weisbecker,
	Theodore Tso, Arnaldo Carvalho de Melo, Mathieu Desnoyers,
	Lai Jiangshan, Martin J. Bligh, Christoph Hellwig, Li Zefan,
	Hidetoshi Seto, Masami Hiramatsu

Huang Ying wrote:
> 
> As far as I know, some architectures have no hardware assisted (NMI
> safe) cmpxchg. Is it OK to use cmpxchg in architecture-independent code?
> 

Including the i386.

	-hpa

^ permalink raw reply	[flat|nested] 29+ messages in thread

* Re: [PATCH 1/3] ring-buffer: make the buffer a true circular link list
  2009-06-10 19:53 ` [PATCH 1/3] ring-buffer: make the buffer a true circular link list Steven Rostedt
@ 2009-06-11  1:12   ` Lai Jiangshan
  2009-06-11  2:00     ` Steven Rostedt
  0 siblings, 1 reply; 29+ messages in thread
From: Lai Jiangshan @ 2009-06-11  1:12 UTC (permalink / raw)
  To: Steven Rostedt
  Cc: linux-kernel, Ingo Molnar, Andrew Morton, Thomas Gleixner,
	Peter Zijlstra, Frederic Weisbecker, Theodore Tso,
	Arnaldo Carvalho de Melo, Mathieu Desnoyers, Martin J. Bligh,
	Christoph Hellwig, Li Zefan, Huang Ying, H. Peter Anvin,
	Hidetoshi Seto, Masami Hiramatsu, Steven Rostedt

Steven Rostedt wrote:
> From: Steven Rostedt <srostedt@redhat.com>
> 
> This patch changes the ring buffer data pages from using a link list
> head pointer, to making each buffer page point to another buffer page
> and never back to a "head".
> 
> This makes the handling of the ring buffer less complex, since the
> traversing of the ring buffer pages no longer needs to account for the
> head pointer.
> 
> This change also is needed to make the ring buffer lockless.
> 
> [ Impact: simplify the ring buffer to help make it lockless ]
> 
> Signed-off-by: Steven Rostedt <srostedt@redhat.com>
> ---
>  kernel/trace/ring_buffer.c |   54 ++++++++++++++++++++++++++++++-------------
>  1 files changed, 37 insertions(+), 17 deletions(-)
> 
> diff --git a/kernel/trace/ring_buffer.c b/kernel/trace/ring_buffer.c
> index 2e642b2..d1edd63 100644
> --- a/kernel/trace/ring_buffer.c
> +++ b/kernel/trace/ring_buffer.c
> @@ -404,7 +404,7 @@ struct ring_buffer_per_cpu {
>  	spinlock_t			reader_lock; /* serialize readers */
>  	raw_spinlock_t			lock;
>  	struct lock_class_key		lock_key;
> -	struct list_head		pages;
> +	struct list_head		*pages;
>  	struct buffer_page		*head_page;	/* read from head */
>  	struct buffer_page		*tail_page;	/* write to tail */
>  	struct buffer_page		*commit_page;	/* committed pages */
> @@ -494,7 +494,7 @@ EXPORT_SYMBOL_GPL(ring_buffer_normalize_time_stamp);
>   */
>  static int rb_check_pages(struct ring_buffer_per_cpu *cpu_buffer)
>  {
> -	struct list_head *head = &cpu_buffer->pages;
> +	struct list_head *head = cpu_buffer->pages;
>  	struct buffer_page *bpage, *tmp;
>  
>  	if (RB_WARN_ON(cpu_buffer, head->next->prev != head))
> @@ -517,12 +517,13 @@ static int rb_check_pages(struct ring_buffer_per_cpu *cpu_buffer)
>  static int rb_allocate_pages(struct ring_buffer_per_cpu *cpu_buffer,
>  			     unsigned nr_pages)
>  {
> -	struct list_head *head = &cpu_buffer->pages;
>  	struct buffer_page *bpage, *tmp;
>  	unsigned long addr;
>  	LIST_HEAD(pages);
>  	unsigned i;
>  
> +	WARN_ON(!nr_pages);
> +
>  	for (i = 0; i < nr_pages; i++) {
>  		bpage = kzalloc_node(ALIGN(sizeof(*bpage), cache_line_size()),
>  				    GFP_KERNEL, cpu_to_node(cpu_buffer->cpu));
> @@ -537,7 +538,18 @@ static int rb_allocate_pages(struct ring_buffer_per_cpu *cpu_buffer,
>  		rb_init_page(bpage->page);
>  	}
>  
> -	list_splice(&pages, head);
> +	/*
> +	 * The ring buffer page list is a circular list that does not
> +	 * start and end with a list head. All page list items point to
> +	 * other pages. Remove one of the pages, init its list head,
> +	 * and use list splice to move the rest of the pages to it.
> +	 */
> +	bpage = list_entry(pages.next, struct buffer_page, list);
> +	list_del_init(&bpage->list);
> +	cpu_buffer->pages = &bpage->list;
> +
> +	list_splice(&pages, cpu_buffer->pages);
> +

Is it proper?

	cpu_buffer->pages = pages.next;
	list_del(&pages);

>  
>  	rb_check_pages(cpu_buffer);
>  
> @@ -569,7 +581,6 @@ rb_allocate_cpu_buffer(struct ring_buffer *buffer, int cpu)
>  	spin_lock_init(&cpu_buffer->reader_lock);
>  	lockdep_set_class(&cpu_buffer->reader_lock, buffer->reader_lock_key);
>  	cpu_buffer->lock = (raw_spinlock_t)__RAW_SPIN_LOCK_UNLOCKED;
> -	INIT_LIST_HEAD(&cpu_buffer->pages);
>  
>  	bpage = kzalloc_node(ALIGN(sizeof(*bpage), cache_line_size()),
>  			    GFP_KERNEL, cpu_to_node(cpu));
> @@ -590,7 +601,7 @@ rb_allocate_cpu_buffer(struct ring_buffer *buffer, int cpu)
>  		goto fail_free_reader;
>  
>  	cpu_buffer->head_page
> -		= list_entry(cpu_buffer->pages.next, struct buffer_page, list);
> +		= list_entry(cpu_buffer->pages, struct buffer_page, list);
>  	cpu_buffer->tail_page = cpu_buffer->commit_page = cpu_buffer->head_page;
>  
>  	return cpu_buffer;
> @@ -605,15 +616,20 @@ rb_allocate_cpu_buffer(struct ring_buffer *buffer, int cpu)
>  
>  static void rb_free_cpu_buffer(struct ring_buffer_per_cpu *cpu_buffer)
>  {
> -	struct list_head *head = &cpu_buffer->pages;
> +	struct list_head *head = cpu_buffer->pages;
>  	struct buffer_page *bpage, *tmp;
>  
>  	free_buffer_page(cpu_buffer->reader_page);
>  
> -	list_for_each_entry_safe(bpage, tmp, head, list) {
> -		list_del_init(&bpage->list);
> +	if (head) {
> +		list_for_each_entry_safe(bpage, tmp, head, list) {
> +			list_del_init(&bpage->list);
> +			free_buffer_page(bpage);
> +		}
> +		bpage = list_entry(head, struct buffer_page, list);
>  		free_buffer_page(bpage);
>  	}
> +
>  	kfree(cpu_buffer);
>  }
>  
> @@ -767,14 +783,14 @@ rb_remove_pages(struct ring_buffer_per_cpu *cpu_buffer, unsigned nr_pages)
>  	synchronize_sched();
>  
>  	for (i = 0; i < nr_pages; i++) {
> -		if (RB_WARN_ON(cpu_buffer, list_empty(&cpu_buffer->pages)))
> +		if (RB_WARN_ON(cpu_buffer, list_empty(cpu_buffer->pages)))
>  			return;
> -		p = cpu_buffer->pages.next;
> +		p = cpu_buffer->pages->next;
>  		bpage = list_entry(p, struct buffer_page, list);
>  		list_del_init(&bpage->list);
>  		free_buffer_page(bpage);
>  	}
> -	if (RB_WARN_ON(cpu_buffer, list_empty(&cpu_buffer->pages)))
> +	if (RB_WARN_ON(cpu_buffer, list_empty(cpu_buffer->pages)))
>  		return;
>  
>  	rb_reset_cpu(cpu_buffer);
> @@ -802,7 +818,7 @@ rb_insert_pages(struct ring_buffer_per_cpu *cpu_buffer,
>  		p = pages->next;
>  		bpage = list_entry(p, struct buffer_page, list);
>  		list_del_init(&bpage->list);
> -		list_add_tail(&bpage->list, &cpu_buffer->pages);
> +		list_add_tail(&bpage->list, cpu_buffer->pages);
>  	}
>  	rb_reset_cpu(cpu_buffer);
>  
> @@ -999,9 +1015,6 @@ static inline void rb_inc_page(struct ring_buffer_per_cpu *cpu_buffer,
>  {
>  	struct list_head *p = (*bpage)->list.next;
>  
> -	if (p == &cpu_buffer->pages)
> -		p = p->next;
> -
>  	*bpage = list_entry(p, struct buffer_page, list);
>  }
>  
> @@ -2212,6 +2225,13 @@ rb_get_reader_page(struct ring_buffer_per_cpu *cpu_buffer)
>  	cpu_buffer->reader_page->list.next = reader->list.next;
>  	cpu_buffer->reader_page->list.prev = reader->list.prev;
>  
> +	/*
> +	 * cpu_buffer->pages just needs to point to the buffer, it
> +	 *  has no specific buffer page to point to. Lets move it out
> +	 *  of our way so we don't accidently swap it.
> +	 */
> +	cpu_buffer->pages = reader->list.prev;
> +
>  	local_set(&cpu_buffer->reader_page->write, 0);
>  	local_set(&cpu_buffer->reader_page->entries, 0);
>  	local_set(&cpu_buffer->reader_page->page->commit, 0);
> @@ -2656,7 +2676,7 @@ static void
>  rb_reset_cpu(struct ring_buffer_per_cpu *cpu_buffer)
>  {
>  	cpu_buffer->head_page
> -		= list_entry(cpu_buffer->pages.next, struct buffer_page, list);
> +		= list_entry(cpu_buffer->pages, struct buffer_page, list);
>  	local_set(&cpu_buffer->head_page->write, 0);
>  	local_set(&cpu_buffer->head_page->entries, 0);
>  	local_set(&cpu_buffer->head_page->page->commit, 0);



^ permalink raw reply	[flat|nested] 29+ messages in thread

* Re: [PATCH 3/3] ring-buffer: add design document
  2009-06-10 22:13   ` Mathieu Desnoyers
@ 2009-06-11  1:55     ` Steven Rostedt
  2009-06-11  3:51       ` Mathieu Desnoyers
  0 siblings, 1 reply; 29+ messages in thread
From: Steven Rostedt @ 2009-06-11  1:55 UTC (permalink / raw)
  To: Mathieu Desnoyers
  Cc: linux-kernel, Ingo Molnar, Andrew Morton, Thomas Gleixner,
	Peter Zijlstra, Frederic Weisbecker, Theodore Tso,
	Arnaldo Carvalho de Melo, Lai Jiangshan, Martin J. Bligh,
	Christoph Hellwig, Li Zefan, Huang Ying, H. Peter Anvin,
	Hidetoshi Seto, Masami Hiramatsu, ltt-dev, Robert Wisniewski,
	Paul E. McKenney


On Wed, 10 Jun 2009, Mathieu Desnoyers wrote:
> * Steven Rostedt (rostedt@goodmis.org) wrote:
> > +The Generic Ring Buffer
> > +-----------------------
> > +
> > +The ring buffer can be used in either an overwrite mode or in
> > +producer/consumer mode.
> > +
> > +Producer/consumer mode is where the producer were to fill up the
> > +buffer before the consumer could free up anything, the producer
> > +will stop writing to the buffer. This will lose most recent events.
> > +
> > +Overwrite mode is where the produce were to fill up the buffer
> > +before the consumer could free up anything, the producer will
> > +overwrite the older data. This will lose the oldest events.
> > +
> > +No two writers can write at the same time (on the same per cpu buffer),
> > +but a writer may preempt another writer, but it must finish writing
> 
> Hi Steven,
> 
> I would use "interrupt" instead of "preempt" here, given that preemption
> implies scheduler activity which is specifically forbidden here.

Good point, I'll update it.

> 
> > +before the previous writer may continue. This is very important to the
> > +algorithm. The writers act like a "stack".
> > +
> > +
> > +  writer1 start
> > +     <preempted> writer2 start
> > +         <preempted> writer3 start
> > +                     writer3 finishes
> > +                 writer2 finishes
> > +  writer1 finishes
> > +
> > +This is very much like a writer being preempted by an interrupt and
> > +the interrupt doing a write as well.
> > +
> > +Readers can happen at any time. But no two readers may run at the
> > +same time, nor can a reader preempt another reader. A reader can not preempt
> > +a writer, but it may read/consume from the buffer at the same time as
> > +a writer is writing, but the reader must be on another processor.
> > +
> > +A writer can preempt a reader, but a reader can not preempt a writer.
> > +But a reader can read the buffer at the same time (on another processor)
> > +as a writer.
> > +
> 
> This comment is inconsistent with the following code comment :
> 
> "* Reads can happen on any CPU."
> 
> Readers should be allowed to read from their own cpu's buffers too, and
> support being interrupted by an incoming interrupt writer, but this
> design document does not discuss this case. Is it at all supported ? If
> not, then this algorithm would not work on uniprocessor.

Yes it is supported. That's what I mean by "A writer can preempt a 
reader". I'll change it to "A writer can interrupt a reader". Would that 
sound better?

But a reader can not interrupt a writer. I hope you don't plan on doing 
reads of the ring buffer from an interrupt.


> 
> > +The ring buffer is made up of a list of pages held together by a link list.
> > +
> > +At initialization a reader page is allocated for the reader that is not
> > +part of the ring buffer.
> > +
> > +The head_page, tail_page and commit_page are all initialized to point
> > +to the same page.
> > +
> > +The reader page is initialized to have its next pointer pointing to
> > +the head page, and its previous pointer pointing to a page before
> > +the head page.
> > +
> > +The reader has its own page to use. At start up time, this page is
> > +allocated but is not attached to the list. When the reader wants
> > +to read from the buffer, if its page is empty (like it is on start up)
> > +it will swap its page with the head_page. The old reader page will
> > +become part of the ring buffer and the head_page will be removed.
> > +A new head page goes to the page after the old head page (but not
> > +the page that was swapped in).
> > +
> > +Once the new page is given to the reader, the reader could do what
> > +it wants with it, as long as a writer has left that page.
> > +
> > +A sample of how the reader page is swapped: Note this does not
> > +show the head page in the buffer, it is for demonstrating a swap
> > +only.
> > +
> > +  +------+
> > +  |reader|          RING BUFFER
> > +  |page  |
> > +  +------+
> > +                  +---+   +---+   +---+
> > +                  |   |-->|   |-->|   |
> > +                  |   |<--|   |<--|   |
> > +                  +---+   +---+   +---+
> > +                   ^ |             ^ |
> > +                   | +-------------+ |
> > +                   +-----------------+
> > +
> > +
> > +  +------+
> > +  |reader|          RING BUFFER
> > +  |page  |-------------------+
> > +  +------+                   v
> > +    |             +---+   +---+   +---+
> > +    |             |   |-->|   |-->|   |
> > +    |             |   |<--|   |<--|   |<-+
> > +    |             +---+   +---+   +---+  |
> > +    |              ^ |             ^ |   |
> > +    |              | +-------------+ |   |
> > +    |              +-----------------+   |
> > +    +------------------------------------+
> > +
> > +  +------+
> > +  |reader|          RING BUFFER
> > +  |page  |-------------------+
> > +  +------+ <---------------+ v
> > +    |  ^          +---+   +---+   +---+
> > +    |  |          |   |-->|   |-->|   |
> > +    |  |          |   |<--|   |<--|   |<-+
> > +    |  |          +---+   +---+   +---+  |
> > +    |  |             |             ^ |   |
> > +    |  |             +-------------+ |   |
> > +    |  +-----------------------------+   |
> > +    +------------------------------------+
> > +
> > +  +------+
> > +  |buffer|          RING BUFFER
> > +  |page  |-------------------+
> > +  +------+ <---------------+ v
> > +    |  ^          +---+   +---+   +---+
> > +    |  |          |   |   |   |-->|   |
> > +    |  |  New     |   |   |   |<--|   |<-+
> > +    |  | Reader   +---+   +---+   +---+  |
> > +    |  |  page ----^                 |   |
> > +    |  |                             |   |
> > +    |  +-----------------------------+   |
> > +    +------------------------------------+
> > +
> 
> Nice ascii art ;)
> 
> Some important comments below,

I draw best with plus's and minus's ;-)

> 
> > +
> > +
> > +It is possible that the page swapped is the commit page and the tail page,
> > +if what is in the ring buffer is less than what is held in a buffer page.
> > +
> > +
> > +          reader page    commit page   tail page
> > +              |              |             |
> > +              v              |             |
> > +             +---+           |             |
> > +             |   |<----------+             |
> > +             |   |<------------------------+
> > +             |   |------+
> > +             +---+      |
> > +                        |
> > +                        v
> > +    +---+    +---+    +---+    +---+
> > +<---|   |--->|   |--->|   |--->|   |--->
> > +--->|   |<---|   |<---|   |<---|   |<---
> > +    +---+    +---+    +---+    +---+
> > +
> > +This case is still legal for this algorithm.
> > +When the writer leaves the page, it simply goes into the ring buffer
> > +since the reader page still points to the next location in the ring
> > +buffer.
> > +
> > +
> > +The main pointers:
> > +
> > +  reader page - The page used solely by the reader and is not part
> > +                of the ring buffer (may be swapped in)
> > +
> > +  head page - the next page in the ring buffer that will be swapped
> > +              with the reader page.
> > +
> > +  tail page - the page where the next write will take place.
> > +
> > +  commit page - the page that last finished a write.
> > +
> > +The commit page only is updated by the outer most writer in the
> > +writer stack. A writer that preempts another writer will not move the
> > +commit page.
> > +
> > +When data is written into the ring buffer, a position is reserved
> > +in the ring buffer and passed back to the writer. When the writer
> > +is finished writing data into that position, it commits the write.
> > +
> > +Another write (or a read) may take place at anytime during this
> > +transaction. If another write happens it must finish before continuing
> > +with the previous write.
> > +
> > +
> > +   Write reserve:
> > +
> > +       Buffer page
> > +      +---------+
> > +      |written  |
> > +      +---------+  <--- given back to writer (current commit)
> > +      |reserved |
> > +      +---------+ <--- tail pointer
> > +      | empty   |
> > +      +---------+
> > +
> > +   Write commit:
> > +
> > +       Buffer page
> > +      +---------+
> > +      |written  |
> > +      +---------+
> > +      |written  |
> > +      +---------+  <--- next positon for write (current commit)
> > +      | empty   |
> > +      +---------+
> > +
> > +
> > + If a write happens after the first reserve:
> > +
> > +       Buffer page
> > +      +---------+
> > +      |written  |
> > +      +---------+  <-- current commit
> > +      |reserved |
> > +      +---------+  <--- given back to second writer
> > +      |reserved |
> > +      +---------+ <--- tail pointer
> > +
> > +  After second writer commits:
> > +
> > +
> > +       Buffer page
> > +      +---------+
> > +      |written  |
> > +      +---------+  <--(last full commit)
> > +      |reserved |
> > +      +---------+
> > +      |pending  |
> > +      |commit   |
> > +      +---------+ <--- tail pointer
> > +
> > +  When the first writer commits:
> > +
> > +       Buffer page
> > +      +---------+
> > +      |written  |
> > +      +---------+
> > +      |written  |
> > +      +---------+
> > +      |written  |
> > +      +---------+  <--(last full commit and tail pointer)
> > +
> > +
> > +The commit pointer points to the last write location that was
> > +committed without preempting another write. When a write that
> > +preempted another write is committed, it only becomes a pending commit
> > +and will not be a full commit till all writes have been committed.
> > +
> > +The commit page points to the page that has the last full commit.
> > +The tail page points to the page with the last write (before
> > +committing).
> > +
> > +The tail page is always equal to or after the commit page. It may
> > +be several pages ahead. If the tail page catches up to the commit
> > +page then no more writes may take place (regardless of the mode
> > +of the ring buffer: overwrite and produce/consumer).
> > +
> > +The order of pages are:
> > +
> > + head page
> > + commit page
> > + tail page
> > +
> > +Possible scenario:
> > +                             tail page
> > +  head page         commit page  |
> > +      |                 |        |
> > +      v                 v        v
> > +    +---+    +---+    +---+    +---+
> > +<---|   |--->|   |--->|   |--->|   |--->
> > +--->|   |<---|   |<---|   |<---|   |<---
> > +    +---+    +---+    +---+    +---+
> > +
> > +There is a special case that the head page is after either the commit page
> > +and possibly the tail page. That is when the commit (and tail) page has been
> > +swapped with the reader page. This is because the head page is always
> > +part of the ring buffer, but the reader page is not. When ever there
> > +has been less than a full page that has been committed inside the ring buffer,
> > +and a reader swaps out a page, it will be swapping out the commit page.
> > +
> > +
> > +          reader page    commit page   tail page
> > +              |              |             |
> > +              v              |             |
> > +             +---+           |             |
> > +             |   |<----------+             |
> > +             |   |<------------------------+
> > +             |   |------+
> > +             +---+      |
> > +                        |
> > +                        v
> > +    +---+    +---+    +---+    +---+
> > +<---|   |--->|   |--->|   |--->|   |--->
> > +--->|   |<---|   |<---|   |<---|   |<---
> > +    +---+    +---+    +---+    +---+
> > +                        ^
> > +                        |
> > +                    head page
> > +
> > +
> > +In this case, the head page will not move when the tail and commit
> > +move back into the ring buffer.
> > +
> > +The reader can not swap a page into the ring buffer if the commit page
> > +is still on that page. If the read meets the last commit (real commit
> > +not pending or reserved), then there is nothing more to read.
> > +The buffer is considered empty until another full commit finishes.
> > +
> > +When the tail meets the head page, if the buffer is in overwrite mode,
> > +the head page will be pushed ahead one. If the buffer is in producer/consumer
> > +mode, the write will fail.
> > +
> > +Overwrite mode:
> > +
> > +            tail page
> > +               |
> > +               v
> > +    +---+    +---+    +---+    +---+
> > +<---|   |--->|   |--->|   |--->|   |--->
> > +--->|   |<---|   |<---|   |<---|   |<---
> > +    +---+    +---+    +---+    +---+
> > +                        ^
> > +                        |
> > +                    head page
> > +
> > +
> > +            tail page
> > +               |
> > +               v
> > +    +---+    +---+    +---+    +---+
> > +<---|   |--->|   |--->|   |--->|   |--->
> > +--->|   |<---|   |<---|   |<---|   |<---
> > +    +---+    +---+    +---+    +---+
> > +                                 ^
> > +                                 |
> > +                             head page
> > +
> > +
> > +                    tail page
> > +                        |
> > +                        v
> > +    +---+    +---+    +---+    +---+
> > +<---|   |--->|   |--->|   |--->|   |--->
> > +--->|   |<---|   |<---|   |<---|   |<---
> > +    +---+    +---+    +---+    +---+
> > +                                 ^
> > +                                 |
> > +                             head page
> > +
> > +Note, the reader page will still point to the previous head page.
> > +But when a swap takes place, it will use the most recent head page.
> > +
> > +
> > +Making the Ring Buffer Lockless:
> > +--------------------------------
> > +
> > +The main idea behind the lockless algorithm is to combine the moving
> > +of the head_page pointer with the swapping of pages with the reader.
> > +State flags are placed inside the pointer to the page. To do this,
> > +each page must be aligned in memory by 4 bytes. This will allow the 2
> > +least significant bits of the address to be used as flags. Since
> > +they will always be zero for the address. To get the address,
> > +simply mask out the flags.
> > +
> > +  MASK = ~3
> > +
> > +  address & MASK
> > +
> > +Two flags will be kept by these two bits:
> > +
> > +   HEADER - the page being pointed to is a head page
> > +
> > +   UPDATE - the page being pointed to is being updated by a writer
> > +          and was or is about to be a head page.
> > +
> > +
> > +          reader page
> > +              |
> > +              v
> > +             +---+
> > +             |   |------+
> > +             +---+      |
> > +                        |
> > +                        v
> > +    +---+    +---+    +---+    +---+
> > +<---|   |--->|   |-H->|   |--->|   |--->
> > +--->|   |<---|   |<---|   |<---|   |<---
> > +    +---+    +---+    +---+    +---+
> > +
> > +
> > +The above pointer "-H->" would have the HEADER flag set. That is
> > +the next page is the next page to be swapped out by the reader.
> > +This pointer means the next page is the head page.
> > +
> > +When the tail page meets the head pointer, it will use cmpxchg to
> > +change the pointer to the UPDATE state:
> > +
> > +
> > +            tail page
> > +               |
> > +               v
> > +    +---+    +---+    +---+    +---+
> > +<---|   |--->|   |-H->|   |--->|   |--->
> > +--->|   |<---|   |<---|   |<---|   |<---
> > +    +---+    +---+    +---+    +---+
> > +
> > +            tail page
> > +               |
> > +               v
> > +    +---+    +---+    +---+    +---+
> > +<---|   |--->|   |-U->|   |--->|   |--->
> > +--->|   |<---|   |<---|   |<---|   |<---
> > +    +---+    +---+    +---+    +---+
> > +
> > +"-U->" represents a pointer in the UPDATE state.
> > +
> > +Any access to the reader will need to take some sort of lock to serialize
> > +the readers. But the writers will never take a lock to write to the
> > +ring buffer. This means we only need to worry about a single reader,
> > +and writes only preempt in "stack" formation.
> > +
> > +When the reader tries to swap the page with the ring buffer, it
> > +will also use cmpxchg. If the flag bit in the pointer to the
> > +head page does not have the HEADER flag set, the compare will fail
> > +and the reader will need to look for the new head page and try again.
> > +Note, the flag UPDATE and HEADER are never set at the same time.
> > +
> > +The reader swaps the reader page as follows:
> > +
> > +  +------+
> > +  |reader|          RING BUFFER
> > +  |page  |
> > +  +------+
> > +                  +---+    +---+    +---+
> > +                  |   |--->|   |--->|   |
> > +                  |   |<---|   |<---|   |
> > +                  +---+    +---+    +---+
> > +                   ^ |               ^ |
> > +                   | +---------------+ |
> > +                   +-----H-------------+
> > +
> > +The reader sets the reader page next pointer as HEADER to the page after
> > +the head page.
> > +
> > +
> > +  +------+
> > +  |reader|          RING BUFFER
> > +  |page  |-------H-----------+
> > +  +------+                   v
> > +    |             +---+    +---+    +---+
> > +    |             |   |--->|   |--->|   |
> > +    |             |   |<---|   |<---|   |<-+
> > +    |             +---+    +---+    +---+  |
> > +    |              ^ |               ^ |   |
> > +    |              | +---------------+ |   |
> > +    |              +-----H-------------+   |
> > +    +--------------------------------------+
> > +
> > +It does a cmpxchg with the pointer to the previous head page to make it
> > +point to the reader page. Note that the new pointer does not have the HEADER
> > +flag set.  This action atomically moves the head page forward.
> > +
> > +  +------+
> > +  |reader|          RING BUFFER
> > +  |page  |-------H-----------+
> > +  +------+ <---------------+ v
> > +    |  ^          +---+   +---+   +---+
> > +    |  |          |   |-->|   |-->|   |
> > +    |  |          |   |<--|   |<--|   |<-+
> > +    |  |          +---+   +---+   +---+  |
> > +    |  |             |             ^ |   |
> > +    |  |             +-------------+ |   |
> > +    |  +-----------------------------+   |
> > +    +------------------------------------+
> > +
> > +After the new head page is set, the previous pointer of the head page is
> > +updated to the reader page.
> > +
> > +  +------+
> > +  |reader|          RING BUFFER
> > +  |page  |-------H-----------+
> > +  +------+                   v
> > +    |  ^          +---+   +---+   +---+
> > +    |  |          |   |-->|   |-->|   |
> > +    |  |          |   |<--|   |<--|   |<-+
> > +    |  |          +---+   +---+   +---+  |
> > +    |  |             |             ^ |   |
> > +    |  |             +-------------+ |   |
> > +    |  +-----------------------------+   |
> > +    +------------------------------------+
> > +
> > +  +------+
> > +  |buffer|          RING BUFFER
> > +  |page  |-------H-----------+  <--- New head page
> > +  +------+ <---------------+ v
> > +    |  ^          +---+   +---+   +---+
> > +    |  |          |   |   |   |-->|   |
> > +    |  |  New     |   |   |   |<--|   |<-+
> > +    |  | Reader   +---+   +---+   +---+  |
> > +    |  |  page ----^                 |   |
> > +    |  |                             |   |
> > +    |  +-----------------------------+   |
> > +    +------------------------------------+
> > +
> > +Another important point. The page that the reader page points back to
> > +by its previous pointer (the one that now points to the new head page)
> > +never points back to the reader page. That is because the reader page is
> > +not part of the ring buffer. Traversing the ring buffer via the next pointers
> > +will always stay in the ring buffer. Traversing the ring buffer via the
> > +prev pointers may not.
> > +
> > +Note, the way to determine a reader page is simply by examining the previous
> > +pointer of the page. If the next pointer of the previous page does not
> > +point back to the original page, then the original page is a reader page:
> > +
> > +                                  
> > +             +--------+
> > +             | reader |  next   +----+
> > +             |  page  |-------->|    |<====== (buffer page)
> > +             +--------+         +----+
> > +                 |                | ^
> > +                 |                v | next
> > +            prev |              +----+
> > +                 +------------->|    |
> > +                                +----+
> > +
> > +The way the head page moves forward:
> > +
> > +When the tail page meets the head page and the buffer is in overwrite mode
> > +and more writes take place, the head page must be moved forward before the
> > +writer may move the tail page. The way this is done is that the writer
> > +performs a cmpxchg to convert the pointer to the head page from the HEADER
> > +flag to have the UPDATE flag set. Once this is done, the reader will
> > +not be able to swap the head page from the buffer, nor will it be able to
> > +move the head page, until the writer is finished with the move.
> > +
> > +This eliminates any races that the reader can have on the writer. The reader
> > +must spin, and this is why the reader can not preempt the writer.
> > +
> > +            tail page
> > +               |
> > +               v
> > +    +---+    +---+    +---+    +---+
> > +<---|   |--->|   |-H->|   |--->|   |--->
> > +--->|   |<---|   |<---|   |<---|   |<---
> > +    +---+    +---+    +---+    +---+
> > +
> > +            tail page
> > +               |
> > +               v
> > +    +---+    +---+    +---+    +---+
> > +<---|   |--->|   |-U->|   |--->|   |--->
> > +--->|   |<---|   |<---|   |<---|   |<---
> > +    +---+    +---+    +---+    +---+
> > +
> > +The following page will be made into the new head page.
> > +
> > +           tail page
> > +               |
> > +               v
> > +    +---+    +---+    +---+    +---+
> > +<---|   |--->|   |-U->|   |-H->|   |--->
> > +--->|   |<---|   |<---|   |<---|   |<---
> > +    +---+    +---+    +---+    +---+
> > +
> > +After the new head page has been set, we can set the old head page
> > +pointer back to NORMAL.
> > +
> > +           tail page
> > +               |
> > +               v
> > +    +---+    +---+    +---+    +---+
> > +<---|   |--->|   |--->|   |-H->|   |--->
> > +--->|   |<---|   |<---|   |<---|   |<---
> > +    +---+    +---+    +---+    +---+
> > +
> > +After the head page has been moved, the tail page may now move forward.
> > +
> > +                    tail page
> > +                        |
> > +                        v
> > +    +---+    +---+    +---+    +---+
> > +<---|   |--->|   |--->|   |-H->|   |--->
> > +--->|   |<---|   |<---|   |<---|   |<---
> > +    +---+    +---+    +---+    +---+
> > +
> > +
> > +The above are the trivial updates. Now for the more complex scenarios.
> > +
> > +
> > +As stated before, if enough writes preempt the first write, the
> > +tail page may make it all the way around the buffer and meet the commit
> > +page. At this time, we must start dropping writes (usually with some kind
> > +of warning to the user). But what happens if the commit was still on the
> > +reader page? The commit page is not part of the ring buffer. The tail page
> > +must account for this.
> > +
> > +
> > +          reader page    commit page
> > +              |              |
> > +              v              |
> > +             +---+           |
> > +             |   |<----------+
> > +             |   |
> > +             |   |------+
> > +             +---+      |
> > +                        |
> > +                        v
> > +    +---+    +---+    +---+    +---+
> > +<---|   |--->|   |-H->|   |--->|   |--->
> > +--->|   |<---|   |<---|   |<---|   |<---
> > +    +---+    +---+    +---+    +---+
> > +               ^
> > +               |
> > +           tail page
> > +
> > +If the tail page were to simply push the head page forward, the commit when
> > +leaving the reader page would not be pointing to the correct page.
> > +
> > +The solution to this is to test if the commit page is on the reader page
> > +before pushing the head page. If it is, then it can be assumed that the
> > +tail page wrapped the buffer, and we must drop new writes.
> > +
> > +This is not a race condition, because the commit page can only be moved
> > +by the outter most writer (the writer that was preempted).
> > +This means that the commit will not move while a writer is moving the
> > +tail page. The reader can not swap the reader page if it is also being
> > +used as the commit page. The reader can simply check that the commit
> > +is off the reader page. Once the commit page leaves the reader page
> > +it will never go back on it unless a reader does another swap with the
> > +buffer page that is also the commit page.
> > +
> > +
> > +Nested writes
> > +-------------
> > +
> > +In the pushing forward of the tail page we must first push forward
> > +the head page if the head page is the next page. If the head page
> > +is not the next page, the tail page is simply updated with a cmpxchg.
> > +
> > +Only writers move the tail page. This must be done atomically to protect
> > +against nested writers.
> > +
> > +  temp_page = tail_page
> > +  next_page = temp_page->next
> > +  cmpxchg(tail_page, temp_page, next_page)
> > +
> 
> OK, I'll bite :
> 
> What happens if :
> 
> - a writer is at the end of a page, 
> - needs to push the tail_page pointer
> - reads tail_page
>   - interrupted.
>   - nested writers come, successfully updates the tail_page, write
>     enough data to fill the whole buffer
>   - concurrently (on another CPU), a reader is consuming all the data
>   - This brings the tail_page pointer back to its original value
>   - iret
> - here, the writer will successfully perform the tail_page cmpxchg,
>   because the value match. However, the page currently being written to
>   could be only partially reserved; the writer will not re-check if the
>   page is really full.
> 
> That's actually one of my main concerns with an approach where two
> separate "pointers" are used to keep track of reserved space within a
> buffer.

Actually, the two pointers is exactly what prevents the above scenario.

We have a commit page pointer and a commit index pointer. The commit page
points to the page that holds the last true commit. A read can never go 
pass the commit. That is, it can not read reserved but uncommited data.

Another key point is that if the tail page meets the commit page, it will 
not move it and drop the data. If your buffer is not big enough to hold 
all data in a interrupt, then your buffer is too small. We count these in 
the "commit_overrun" counter as well as return NULL on the reserve so the 
tracer will know that it had its data dropped.


> 
> The same concern applies to moving the head page when concurrent writers
> are nesting.
> 
> More generally, I'm also concerned about the lack of memory barriers
> around some non-cmpxchg tail/head page set operations in your code, and
> the lack of proper rcu_dereference-style primitive for list iteration.

The cmpxchg is a memory barrier. Writes only contend with other writes on 
the same CPU. When we update the pointer from HEAD to UPDATE a reader will
not pass that point. The update is done via cmpxchg and thus is a memory 
barrier. Now if cmpxchg is not a memory barrier, then I need to add 
smp_mb() by all of them.

> 
> For those I've added to CC, I'm referring to the patch at :
> 
> http://patchwork.kernel.org/patch/29395/
> 
> The great news to me is that no one can say LTTng's lockless buffering
> algorithm is complex compared to this. ;)

But can you read without worries about writers? The nice thing about this 
approach, which a lot of ftrace depends on, is that I don't need call 
backs or copies to check if what I read from the buffer was not stomped 
on by a writer. There is a zero copy overhead for readers (when the buffer 
is more than a page filled) and when a reader has its data, it belongs to 
that reader.

-- Steve


^ permalink raw reply	[flat|nested] 29+ messages in thread

* Re: [PATCH 3/3] ring-buffer: add design document
  2009-06-11  0:51   ` Huang Ying
  2009-06-11  0:54     ` H. Peter Anvin
@ 2009-06-11  1:58     ` Steven Rostedt
  2009-06-11  2:33       ` Huang Ying
  1 sibling, 1 reply; 29+ messages in thread
From: Steven Rostedt @ 2009-06-11  1:58 UTC (permalink / raw)
  To: Huang Ying
  Cc: linux-kernel, Ingo Molnar, Andrew Morton, Thomas Gleixner,
	Peter Zijlstra, Frederic Weisbecker, Theodore Tso,
	Arnaldo Carvalho de Melo, Mathieu Desnoyers, Lai Jiangshan,
	Martin J. Bligh, Christoph Hellwig, Li Zefan, H. Peter Anvin,
	Hidetoshi Seto, Masami Hiramatsu


On Thu, 11 Jun 2009, Huang Ying wrote:

> On Thu, 2009-06-11 at 03:53 +0800, Steven Rostedt wrote:
> > +
> > +cmpxchg - hardware assisted atomic transaction that performs the following:
> > +
> > +   A = B iff previous A == C
> > +
> > +   R = cmpxchg(A, C, B) is saying that we replace A with B if and only if
> > +      current A is equal to C, and we put the old (current) A into R
> > +
> > +   R gets the previous A regardless if A is updated with B or not.
> > +
> > +   To see if the update was successful a compare of R == C may be used.
> 
> As far as I know, some architectures have no hardware assisted (NMI
> safe) cmpxchg. Is it OK to use cmpxchg in architecture-independent code?

I can fall back to the lock solution for those archs without cmpxchg. It 
is NMI safe, because we do spin_trylock() in NMI context. If we fail to 
acquire the lock in NMI context, we simply drop the packet.

Are these archs without cmpxchg and NMIs, a concern for you?

-- Steve


^ permalink raw reply	[flat|nested] 29+ messages in thread

* Re: [PATCH 1/3] ring-buffer: make the buffer a true circular link list
  2009-06-11  1:12   ` Lai Jiangshan
@ 2009-06-11  2:00     ` Steven Rostedt
  2009-06-11  3:25       ` Lai Jiangshan
  0 siblings, 1 reply; 29+ messages in thread
From: Steven Rostedt @ 2009-06-11  2:00 UTC (permalink / raw)
  To: Lai Jiangshan
  Cc: linux-kernel, Ingo Molnar, Andrew Morton, Thomas Gleixner,
	Peter Zijlstra, Frederic Weisbecker, Theodore Tso,
	Arnaldo Carvalho de Melo, Mathieu Desnoyers, Martin J. Bligh,
	Christoph Hellwig, Li Zefan, Huang Ying, H. Peter Anvin,
	Hidetoshi Seto, Masami Hiramatsu, Steven Rostedt


On Thu, 11 Jun 2009, Lai Jiangshan wrote:

> > -	list_splice(&pages, head);
> > +	/*
> > +	 * The ring buffer page list is a circular list that does not
> > +	 * start and end with a list head. All page list items point to
> > +	 * other pages. Remove one of the pages, init its list head,
> > +	 * and use list splice to move the rest of the pages to it.
> > +	 */
> > +	bpage = list_entry(pages.next, struct buffer_page, list);
> > +	list_del_init(&bpage->list);
> > +	cpu_buffer->pages = &bpage->list;
> > +
> > +	list_splice(&pages, cpu_buffer->pages);
> > +
> 
> Is it proper?
> 
> 	cpu_buffer->pages = pages.next;
> 	list_del(&pages);
> 

Not sure what you are asking here?

-- Steve

> >  
> >  	rb_check_pages(cpu_buffer);
> >  

^ permalink raw reply	[flat|nested] 29+ messages in thread

* Re: [PATCH 3/3] ring-buffer: add design document
  2009-06-11  1:58     ` Steven Rostedt
@ 2009-06-11  2:33       ` Huang Ying
  2009-06-11  2:38         ` Mathieu Desnoyers
  0 siblings, 1 reply; 29+ messages in thread
From: Huang Ying @ 2009-06-11  2:33 UTC (permalink / raw)
  To: Steven Rostedt
  Cc: linux-kernel, Ingo Molnar, Andrew Morton, Thomas Gleixner,
	Peter Zijlstra, Frederic Weisbecker, Theodore Tso,
	Arnaldo Carvalho de Melo, Mathieu Desnoyers, Lai Jiangshan,
	Martin J. Bligh, Christoph Hellwig, Li Zefan, H. Peter Anvin,
	Hidetoshi Seto, Masami Hiramatsu

On Thu, 2009-06-11 at 09:58 +0800, Steven Rostedt wrote:
> On Thu, 11 Jun 2009, Huang Ying wrote:
> 
> > On Thu, 2009-06-11 at 03:53 +0800, Steven Rostedt wrote:
> > > +
> > > +cmpxchg - hardware assisted atomic transaction that performs the following:
> > > +
> > > +   A = B iff previous A == C
> > > +
> > > +   R = cmpxchg(A, C, B) is saying that we replace A with B if and only if
> > > +      current A is equal to C, and we put the old (current) A into R
> > > +
> > > +   R gets the previous A regardless if A is updated with B or not.
> > > +
> > > +   To see if the update was successful a compare of R == C may be used.
> > 
> > As far as I know, some architectures have no hardware assisted (NMI
> > safe) cmpxchg. Is it OK to use cmpxchg in architecture-independent code?
> 
> I can fall back to the lock solution for those archs without cmpxchg. It 
> is NMI safe, because we do spin_trylock() in NMI context. If we fail to 
> acquire the lock in NMI context, we simply drop the packet.

Yes. For users do not care about packet drop, it is acceptable. But
please select the implementation at run-time instead of build time.
Because on some architecture such as ARM, whether CPU has cmpxchg
support is determined at run-time.

> Are these archs without cmpxchg and NMIs, a concern for you?

ARM has no cmpxchg until ARM v6, but it has NMI like mechanism named
FIQ.

Best Regards,
Huang Ying



^ permalink raw reply	[flat|nested] 29+ messages in thread

* Re: [PATCH 3/3] ring-buffer: add design document
  2009-06-11  2:33       ` Huang Ying
@ 2009-06-11  2:38         ` Mathieu Desnoyers
  2009-06-12  3:13           ` Huang Ying
  0 siblings, 1 reply; 29+ messages in thread
From: Mathieu Desnoyers @ 2009-06-11  2:38 UTC (permalink / raw)
  To: Huang Ying
  Cc: Steven Rostedt, linux-kernel, Ingo Molnar, Andrew Morton,
	Thomas Gleixner, Peter Zijlstra, Frederic Weisbecker,
	Theodore Tso, Arnaldo Carvalho de Melo, Lai Jiangshan,
	Martin J. Bligh, Christoph Hellwig, Li Zefan, H. Peter Anvin,
	Hidetoshi Seto, Masami Hiramatsu

* Huang Ying (ying.huang@intel.com) wrote:
> On Thu, 2009-06-11 at 09:58 +0800, Steven Rostedt wrote:
> > On Thu, 11 Jun 2009, Huang Ying wrote:
> > 
> > > On Thu, 2009-06-11 at 03:53 +0800, Steven Rostedt wrote:
> > > > +
> > > > +cmpxchg - hardware assisted atomic transaction that performs the following:
> > > > +
> > > > +   A = B iff previous A == C
> > > > +
> > > > +   R = cmpxchg(A, C, B) is saying that we replace A with B if and only if
> > > > +      current A is equal to C, and we put the old (current) A into R
> > > > +
> > > > +   R gets the previous A regardless if A is updated with B or not.
> > > > +
> > > > +   To see if the update was successful a compare of R == C may be used.
> > > 
> > > As far as I know, some architectures have no hardware assisted (NMI
> > > safe) cmpxchg. Is it OK to use cmpxchg in architecture-independent code?
> > 
> > I can fall back to the lock solution for those archs without cmpxchg. It 
> > is NMI safe, because we do spin_trylock() in NMI context. If we fail to 
> > acquire the lock in NMI context, we simply drop the packet.
> 
> Yes. For users do not care about packet drop, it is acceptable. But
> please select the implementation at run-time instead of build time.
> Because on some architecture such as ARM, whether CPU has cmpxchg
> support is determined at run-time.
> 
> > Are these archs without cmpxchg and NMIs, a concern for you?
> 
> ARM has no cmpxchg until ARM v6, but it has NMI like mechanism named
> FIQ.
> 

One could probably adapt the cmpxchg for earlier ARM so it disables
FIQs. Note that the current limitation is that there is only a
fiq disable, not a fiq save/restore.

Mathieu

> Best Regards,
> Huang Ying
> 
> 

-- 
Mathieu Desnoyers
OpenPGP key fingerprint: 8CD5 52C3 8E3C 4140 715F  BA06 3F25 A8FE 3BAE 9A68

^ permalink raw reply	[flat|nested] 29+ messages in thread

* Re: [PATCH 3/3] ring-buffer: add design document
  2009-06-10 19:53 ` [PATCH 3/3] ring-buffer: add design document Steven Rostedt
  2009-06-10 22:13   ` Mathieu Desnoyers
  2009-06-11  0:51   ` Huang Ying
@ 2009-06-11  3:15   ` Hidetoshi Seto
  2009-06-11  3:25     ` Steven Rostedt
  2009-06-13  1:54   ` Frederic Weisbecker
  2009-06-15  0:56   ` Frederic Weisbecker
  4 siblings, 1 reply; 29+ messages in thread
From: Hidetoshi Seto @ 2009-06-11  3:15 UTC (permalink / raw)
  To: Steven Rostedt
  Cc: linux-kernel, Ingo Molnar, Andrew Morton, Thomas Gleixner,
	Peter Zijlstra, Frederic Weisbecker, Theodore Tso,
	Arnaldo Carvalho de Melo, Mathieu Desnoyers, Lai Jiangshan,
	Martin J. Bligh, Christoph Hellwig, Li Zefan, Huang Ying,
	H. Peter Anvin, Masami Hiramatsu

Steven Rostedt wrote:
> From: Steven Rostedt <srostedt@redhat.com>
> 
> This adds the design document for the ring buffer and also
> explains how it is designed to have lockless writes.
> 
> Signed-off-by: Steven Rostedt <rostedt@goodmis.org>
> ---
>  Documentation/trace/ring-buffer-design.txt |  949 ++++++++++++++++++++++++++++
>  1 files changed, 949 insertions(+), 0 deletions(-)
>  create mode 100644 Documentation/trace/ring-buffer-design.txt
> 
> diff --git a/Documentation/trace/ring-buffer-design.txt b/Documentation/trace/ring-buffer-design.txt
> new file mode 100644
> index 0000000..cca290b
> --- /dev/null
> +++ b/Documentation/trace/ring-buffer-design.txt
> @@ -0,0 +1,949 @@
> +		Lockless Ring Buffer Design
> +		===========================
> +
> +Copyright 2009 Red Hat Inc.
> +   Author:   Steven Rostedt <srostedt@redhat.com>
> +  License:   The GNU Free Documentation License, Version 1.2
> +               (dual licensed under the GPL v2)
> +
> +Written for: 2.6.31
> +
> +Terminology used in this Document
> +---------------------------------
> +
> +tail - where new writes happen in the ring buffer.
> +
> +head - where new reads happen in the ring buffer.
> +
> +producer - the task that writes into the ring buffer (same as writer)
> +
> +writer - same as producer
> +
> +consumer - the task that reads from the buffer (same as reader)
> +
> +reader - same as consumer.
> +
> +reader_page - A page outside the ring buffer used solely (for the most part)
> +    by the reader.
> +
> +head_page - a pointer to the page that the reader will use next
> +
> +tail_page - a pointer to the page that will be written to next
> +
> +commit_page - a pointer to the page with the last finished non nested write.
> +
> +cmpxchg - hardware assisted atomic transaction that performs the following:
> +
> +   A = B iff previous A == C
> +
> +   R = cmpxchg(A, C, B) is saying that we replace A with B if and only if
> +      current A is equal to C, and we put the old (current) A into R
> +
> +   R gets the previous A regardless if A is updated with B or not.
> +
> +   To see if the update was successful a compare of R == C may be used.
> +
> +The Generic Ring Buffer
> +-----------------------
> +
> +The ring buffer can be used in either an overwrite mode or in
> +producer/consumer mode.
> +
> +Producer/consumer mode is where the producer were to fill up the
> +buffer before the consumer could free up anything, the producer
> +will stop writing to the buffer. This will lose most recent events.
> +
> +Overwrite mode is where the produce were to fill up the buffer
> +before the consumer could free up anything, the producer will
> +overwrite the older data. This will lose the oldest events.
> +
> +No two writers can write at the same time (on the same per cpu buffer),
> +but a writer may preempt another writer, but it must finish writing
> +before the previous writer may continue. This is very important to the
> +algorithm. The writers act like a "stack".
> +
> +
> +  writer1 start
> +     <preempted> writer2 start
> +         <preempted> writer3 start
> +                     writer3 finishes
> +                 writer2 finishes
> +  writer1 finishes
> +
> +This is very much like a writer being preempted by an interrupt and
> +the interrupt doing a write as well.
> +
> +Readers can happen at any time. But no two readers may run at the
> +same time, nor can a reader preempt another reader. A reader can not preempt
> +a writer, but it may read/consume from the buffer at the same time as
> +a writer is writing, but the reader must be on another processor.
> +
> +A writer can preempt a reader, but a reader can not preempt a writer.
> +But a reader can read the buffer at the same time (on another processor)
> +as a writer.
> +
> +The ring buffer is made up of a list of pages held together by a link list.
> +
> +At initialization a reader page is allocated for the reader that is not
> +part of the ring buffer.
> +
> +The head_page, tail_page and commit_page are all initialized to point
> +to the same page.
> +
> +The reader page is initialized to have its next pointer pointing to
> +the head page, and its previous pointer pointing to a page before
> +the head page.
> +
> +The reader has its own page to use. At start up time, this page is
> +allocated but is not attached to the list. When the reader wants
> +to read from the buffer, if its page is empty (like it is on start up)
> +it will swap its page with the head_page. The old reader page will
> +become part of the ring buffer and the head_page will be removed.
> +A new head page goes to the page after the old head page (but not
> +the page that was swapped in).
> +
> +Once the new page is given to the reader, the reader could do what
> +it wants with it, as long as a writer has left that page.
> +
> +A sample of how the reader page is swapped: Note this does not
> +show the head page in the buffer, it is for demonstrating a swap
> +only.
> +
> +  +------+
> +  |reader|          RING BUFFER
> +  |page  |
> +  +------+
> +                  +---+   +---+   +---+
> +                  |   |-->|   |-->|   |
> +                  |   |<--|   |<--|   |
> +                  +---+   +---+   +---+
> +                   ^ |             ^ |
> +                   | +-------------+ |
> +                   +-----------------+
> +
> +
> +  +------+
> +  |reader|          RING BUFFER
> +  |page  |-------------------+
> +  +------+                   v
> +    |             +---+   +---+   +---+
> +    |             |   |-->|   |-->|   |
> +    |             |   |<--|   |<--|   |<-+
> +    |             +---+   +---+   +---+  |
> +    |              ^ |             ^ |   |
> +    |              | +-------------+ |   |
> +    |              +-----------------+   |
> +    +------------------------------------+
> +
> +  +------+
> +  |reader|          RING BUFFER
> +  |page  |-------------------+
> +  +------+ <---------------+ v
> +    |  ^          +---+   +---+   +---+
> +    |  |          |   |-->|   |-->|   |
> +    |  |          |   |<--|   |<--|   |<-+
> +    |  |          +---+   +---+   +---+  |
> +    |  |             |             ^ |   |
> +    |  |             +-------------+ |   |
> +    |  +-----------------------------+   |
> +    +------------------------------------+

It seems the middle of three pages have 2 prev arrows... ?


> +
> +  +------+
> +  |buffer|          RING BUFFER
> +  |page  |-------------------+
> +  +------+ <---------------+ v
> +    |  ^          +---+   +---+   +---+
> +    |  |          |   |   |   |-->|   |
> +    |  |  New     |   |   |   |<--|   |<-+
> +    |  | Reader   +---+   +---+   +---+  |
> +    |  |  page ----^                 |   |
> +    |  |                             |   |
> +    |  +-----------------------------+   |
> +    +------------------------------------+
> +
> +
> +
> +It is possible that the page swapped is the commit page and the tail page,
> +if what is in the ring buffer is less than what is held in a buffer page.
> +
> +
> +          reader page    commit page   tail page
> +              |              |             |
> +              v              |             |
> +             +---+           |             |
> +             |   |<----------+             |
> +             |   |<------------------------+
> +             |   |------+
> +             +---+      |
> +                        |
> +                        v
> +    +---+    +---+    +---+    +---+
> +<---|   |--->|   |--->|   |--->|   |--->
> +--->|   |<---|   |<---|   |<---|   |<---
> +    +---+    +---+    +---+    +---+
> +
> +This case is still legal for this algorithm.
> +When the writer leaves the page, it simply goes into the ring buffer
> +since the reader page still points to the next location in the ring
> +buffer.
> +
> +
> +The main pointers:
> +
> +  reader page - The page used solely by the reader and is not part
> +                of the ring buffer (may be swapped in)
> +
> +  head page - the next page in the ring buffer that will be swapped
> +              with the reader page.
> +
> +  tail page - the page where the next write will take place.
> +
> +  commit page - the page that last finished a write.
> +
> +The commit page only is updated by the outer most writer in the
> +writer stack. A writer that preempts another writer will not move the
> +commit page.
> +
> +When data is written into the ring buffer, a position is reserved
> +in the ring buffer and passed back to the writer. When the writer
> +is finished writing data into that position, it commits the write.
> +
> +Another write (or a read) may take place at anytime during this
> +transaction. If another write happens it must finish before continuing
> +with the previous write.
> +
> +
> +   Write reserve:
> +
> +       Buffer page
> +      +---------+
> +      |written  |
> +      +---------+  <--- given back to writer (current commit)
> +      |reserved |
> +      +---------+ <--- tail pointer
> +      | empty   |
> +      +---------+
> +
> +   Write commit:
> +
> +       Buffer page
> +      +---------+
> +      |written  |
> +      +---------+
> +      |written  |
> +      +---------+  <--- next positon for write (current commit)
> +      | empty   |
> +      +---------+
> +
> +
> + If a write happens after the first reserve:
> +
> +       Buffer page
> +      +---------+
> +      |written  |
> +      +---------+  <-- current commit
> +      |reserved |
> +      +---------+  <--- given back to second writer
> +      |reserved |
> +      +---------+ <--- tail pointer
> +
> +  After second writer commits:
> +
> +
> +       Buffer page
> +      +---------+
> +      |written  |
> +      +---------+  <--(last full commit)
> +      |reserved |
> +      +---------+
> +      |pending  |
> +      |commit   |
> +      +---------+ <--- tail pointer
> +
> +  When the first writer commits:
> +
> +       Buffer page
> +      +---------+
> +      |written  |
> +      +---------+
> +      |written  |
> +      +---------+
> +      |written  |
> +      +---------+  <--(last full commit and tail pointer)
> +
> +
> +The commit pointer points to the last write location that was
> +committed without preempting another write. When a write that
> +preempted another write is committed, it only becomes a pending commit
> +and will not be a full commit till all writes have been committed.
> +
> +The commit page points to the page that has the last full commit.
> +The tail page points to the page with the last write (before
> +committing).
> +
> +The tail page is always equal to or after the commit page. It may
> +be several pages ahead. If the tail page catches up to the commit
> +page then no more writes may take place (regardless of the mode
> +of the ring buffer: overwrite and produce/consumer).
> +
> +The order of pages are:
> +
> + head page
> + commit page
> + tail page
> +
> +Possible scenario:
> +                             tail page
> +  head page         commit page  |
> +      |                 |        |
> +      v                 v        v
> +    +---+    +---+    +---+    +---+
> +<---|   |--->|   |--->|   |--->|   |--->
> +--->|   |<---|   |<---|   |<---|   |<---
> +    +---+    +---+    +---+    +---+
> +
> +There is a special case that the head page is after either the commit page
> +and possibly the tail page. That is when the commit (and tail) page has been
> +swapped with the reader page. This is because the head page is always
> +part of the ring buffer, but the reader page is not. When ever there
> +has been less than a full page that has been committed inside the ring buffer,
> +and a reader swaps out a page, it will be swapping out the commit page.
> +
> +
> +          reader page    commit page   tail page
> +              |              |             |
> +              v              |             |
> +             +---+           |             |
> +             |   |<----------+             |
> +             |   |<------------------------+
> +             |   |------+
> +             +---+      |
> +                        |
> +                        v
> +    +---+    +---+    +---+    +---+
> +<---|   |--->|   |--->|   |--->|   |--->
> +--->|   |<---|   |<---|   |<---|   |<---
> +    +---+    +---+    +---+    +---+
> +                        ^
> +                        |
> +                    head page
> +
> +
> +In this case, the head page will not move when the tail and commit
> +move back into the ring buffer.
> +
> +The reader can not swap a page into the ring buffer if the commit page
> +is still on that page. If the read meets the last commit (real commit
> +not pending or reserved), then there is nothing more to read.
> +The buffer is considered empty until another full commit finishes.
> +
> +When the tail meets the head page, if the buffer is in overwrite mode,
> +the head page will be pushed ahead one. If the buffer is in producer/consumer
> +mode, the write will fail.
> +
> +Overwrite mode:
> +
> +            tail page
> +               |
> +               v
> +    +---+    +---+    +---+    +---+
> +<---|   |--->|   |--->|   |--->|   |--->
> +--->|   |<---|   |<---|   |<---|   |<---
> +    +---+    +---+    +---+    +---+
> +                        ^
> +                        |
> +                    head page
> +
> +
> +            tail page
> +               |
> +               v
> +    +---+    +---+    +---+    +---+
> +<---|   |--->|   |--->|   |--->|   |--->
> +--->|   |<---|   |<---|   |<---|   |<---
> +    +---+    +---+    +---+    +---+
> +                                 ^
> +                                 |
> +                             head page
> +
> +
> +                    tail page
> +                        |
> +                        v
> +    +---+    +---+    +---+    +---+
> +<---|   |--->|   |--->|   |--->|   |--->
> +--->|   |<---|   |<---|   |<---|   |<---
> +    +---+    +---+    +---+    +---+
> +                                 ^
> +                                 |
> +                             head page
> +
> +Note, the reader page will still point to the previous head page.
> +But when a swap takes place, it will use the most recent head page.
> +
> +
> +Making the Ring Buffer Lockless:
> +--------------------------------
> +
> +The main idea behind the lockless algorithm is to combine the moving
> +of the head_page pointer with the swapping of pages with the reader.
> +State flags are placed inside the pointer to the page. To do this,
> +each page must be aligned in memory by 4 bytes. This will allow the 2
> +least significant bits of the address to be used as flags. Since
> +they will always be zero for the address. To get the address,
> +simply mask out the flags.
> +
> +  MASK = ~3
> +
> +  address & MASK
> +
> +Two flags will be kept by these two bits:
> +
> +   HEADER - the page being pointed to is a head page
> +
> +   UPDATE - the page being pointed to is being updated by a writer
> +          and was or is about to be a head page.
> +
> +
> +          reader page
> +              |
> +              v
> +             +---+
> +             |   |------+
> +             +---+      |
> +                        |
> +                        v
> +    +---+    +---+    +---+    +---+
> +<---|   |--->|   |-H->|   |--->|   |--->
> +--->|   |<---|   |<---|   |<---|   |<---
> +    +---+    +---+    +---+    +---+
> +
> +
> +The above pointer "-H->" would have the HEADER flag set. That is
> +the next page is the next page to be swapped out by the reader.
> +This pointer means the next page is the head page.
> +
> +When the tail page meets the head pointer, it will use cmpxchg to
> +change the pointer to the UPDATE state:
> +
> +
> +            tail page
> +               |
> +               v
> +    +---+    +---+    +---+    +---+
> +<---|   |--->|   |-H->|   |--->|   |--->
> +--->|   |<---|   |<---|   |<---|   |<---
> +    +---+    +---+    +---+    +---+
> +
> +            tail page
> +               |
> +               v
> +    +---+    +---+    +---+    +---+
> +<---|   |--->|   |-U->|   |--->|   |--->
> +--->|   |<---|   |<---|   |<---|   |<---
> +    +---+    +---+    +---+    +---+
> +
> +"-U->" represents a pointer in the UPDATE state.
> +
> +Any access to the reader will need to take some sort of lock to serialize
> +the readers. But the writers will never take a lock to write to the
> +ring buffer. This means we only need to worry about a single reader,
> +and writes only preempt in "stack" formation.
> +
> +When the reader tries to swap the page with the ring buffer, it
> +will also use cmpxchg. If the flag bit in the pointer to the
> +head page does not have the HEADER flag set, the compare will fail
> +and the reader will need to look for the new head page and try again.
> +Note, the flag UPDATE and HEADER are never set at the same time.
> +
> +The reader swaps the reader page as follows:
> +
> +  +------+
> +  |reader|          RING BUFFER
> +  |page  |
> +  +------+
> +                  +---+    +---+    +---+
> +                  |   |--->|   |--->|   |
> +                  |   |<---|   |<---|   |
> +                  +---+    +---+    +---+
> +                   ^ |               ^ |
> +                   | +---------------+ |
> +                   +-----H-------------+
> +
> +The reader sets the reader page next pointer as HEADER to the page after
> +the head page.
> +
> +
> +  +------+
> +  |reader|          RING BUFFER
> +  |page  |-------H-----------+
> +  +------+                   v
> +    |             +---+    +---+    +---+
> +    |             |   |--->|   |--->|   |
> +    |             |   |<---|   |<---|   |<-+
> +    |             +---+    +---+    +---+  |
> +    |              ^ |               ^ |   |
> +    |              | +---------------+ |   |
> +    |              +-----H-------------+   |
> +    +--------------------------------------+
> +
> +It does a cmpxchg with the pointer to the previous head page to make it
> +point to the reader page. Note that the new pointer does not have the HEADER
> +flag set.  This action atomically moves the head page forward.
> +
> +  +------+
> +  |reader|          RING BUFFER
> +  |page  |-------H-----------+
> +  +------+ <---------------+ v
> +    |  ^          +---+   +---+   +---+
> +    |  |          |   |-->|   |-->|   |
> +    |  |          |   |<--|   |<--|   |<-+
> +    |  |          +---+   +---+   +---+  |
> +    |  |             |             ^ |   |
> +    |  |             +-------------+ |   |
> +    |  +-----------------------------+   |
> +    +------------------------------------+
> +

Ditto.

Thanks,
H.Seto


> +After the new head page is set, the previous pointer of the head page is
> +updated to the reader page.
> +
> +  +------+
> +  |reader|          RING BUFFER
> +  |page  |-------H-----------+
> +  +------+                   v
> +    |  ^          +---+   +---+   +---+
> +    |  |          |   |-->|   |-->|   |
> +    |  |          |   |<--|   |<--|   |<-+
> +    |  |          +---+   +---+   +---+  |
> +    |  |             |             ^ |   |
> +    |  |             +-------------+ |   |
> +    |  +-----------------------------+   |
> +    +------------------------------------+
> +
> +  +------+
> +  |buffer|          RING BUFFER
> +  |page  |-------H-----------+  <--- New head page
> +  +------+ <---------------+ v
> +    |  ^          +---+   +---+   +---+
> +    |  |          |   |   |   |-->|   |
> +    |  |  New     |   |   |   |<--|   |<-+
> +    |  | Reader   +---+   +---+   +---+  |
> +    |  |  page ----^                 |   |
> +    |  |                             |   |
> +    |  +-----------------------------+   |
> +    +------------------------------------+
> +
> +Another important point. The page that the reader page points back to
> +by its previous pointer (the one that now points to the new head page)
> +never points back to the reader page. That is because the reader page is
> +not part of the ring buffer. Traversing the ring buffer via the next pointers
> +will always stay in the ring buffer. Traversing the ring buffer via the
> +prev pointers may not.
> +
> +Note, the way to determine a reader page is simply by examining the previous
> +pointer of the page. If the next pointer of the previous page does not
> +point back to the original page, then the original page is a reader page:
> +
> +                                  
> +             +--------+
> +             | reader |  next   +----+
> +             |  page  |-------->|    |<====== (buffer page)
> +             +--------+         +----+
> +                 |                | ^
> +                 |                v | next
> +            prev |              +----+
> +                 +------------->|    |
> +                                +----+
> +
> +The way the head page moves forward:
> +
> +When the tail page meets the head page and the buffer is in overwrite mode
> +and more writes take place, the head page must be moved forward before the
> +writer may move the tail page. The way this is done is that the writer
> +performs a cmpxchg to convert the pointer to the head page from the HEADER
> +flag to have the UPDATE flag set. Once this is done, the reader will
> +not be able to swap the head page from the buffer, nor will it be able to
> +move the head page, until the writer is finished with the move.
> +
> +This eliminates any races that the reader can have on the writer. The reader
> +must spin, and this is why the reader can not preempt the writer.
> +
> +            tail page
> +               |
> +               v
> +    +---+    +---+    +---+    +---+
> +<---|   |--->|   |-H->|   |--->|   |--->
> +--->|   |<---|   |<---|   |<---|   |<---
> +    +---+    +---+    +---+    +---+
> +
> +            tail page
> +               |
> +               v
> +    +---+    +---+    +---+    +---+
> +<---|   |--->|   |-U->|   |--->|   |--->
> +--->|   |<---|   |<---|   |<---|   |<---
> +    +---+    +---+    +---+    +---+
> +
> +The following page will be made into the new head page.
> +
> +           tail page
> +               |
> +               v
> +    +---+    +---+    +---+    +---+
> +<---|   |--->|   |-U->|   |-H->|   |--->
> +--->|   |<---|   |<---|   |<---|   |<---
> +    +---+    +---+    +---+    +---+
> +
> +After the new head page has been set, we can set the old head page
> +pointer back to NORMAL.
> +
> +           tail page
> +               |
> +               v
> +    +---+    +---+    +---+    +---+
> +<---|   |--->|   |--->|   |-H->|   |--->
> +--->|   |<---|   |<---|   |<---|   |<---
> +    +---+    +---+    +---+    +---+
> +
> +After the head page has been moved, the tail page may now move forward.
> +
> +                    tail page
> +                        |
> +                        v
> +    +---+    +---+    +---+    +---+
> +<---|   |--->|   |--->|   |-H->|   |--->
> +--->|   |<---|   |<---|   |<---|   |<---
> +    +---+    +---+    +---+    +---+
> +
> +
> +The above are the trivial updates. Now for the more complex scenarios.
> +
> +
> +As stated before, if enough writes preempt the first write, the
> +tail page may make it all the way around the buffer and meet the commit
> +page. At this time, we must start dropping writes (usually with some kind
> +of warning to the user). But what happens if the commit was still on the
> +reader page? The commit page is not part of the ring buffer. The tail page
> +must account for this.
> +
> +
> +          reader page    commit page
> +              |              |
> +              v              |
> +             +---+           |
> +             |   |<----------+
> +             |   |
> +             |   |------+
> +             +---+      |
> +                        |
> +                        v
> +    +---+    +---+    +---+    +---+
> +<---|   |--->|   |-H->|   |--->|   |--->
> +--->|   |<---|   |<---|   |<---|   |<---
> +    +---+    +---+    +---+    +---+
> +               ^
> +               |
> +           tail page
> +
> +If the tail page were to simply push the head page forward, the commit when
> +leaving the reader page would not be pointing to the correct page.
> +
> +The solution to this is to test if the commit page is on the reader page
> +before pushing the head page. If it is, then it can be assumed that the
> +tail page wrapped the buffer, and we must drop new writes.
> +
> +This is not a race condition, because the commit page can only be moved
> +by the outter most writer (the writer that was preempted).
> +This means that the commit will not move while a writer is moving the
> +tail page. The reader can not swap the reader page if it is also being
> +used as the commit page. The reader can simply check that the commit
> +is off the reader page. Once the commit page leaves the reader page
> +it will never go back on it unless a reader does another swap with the
> +buffer page that is also the commit page.
> +
> +
> +Nested writes
> +-------------
> +
> +In the pushing forward of the tail page we must first push forward
> +the head page if the head page is the next page. If the head page
> +is not the next page, the tail page is simply updated with a cmpxchg.
> +
> +Only writers move the tail page. This must be done atomically to protect
> +against nested writers.
> +
> +  temp_page = tail_page
> +  next_page = temp_page->next
> +  cmpxchg(tail_page, temp_page, next_page)
> +
> +The above will update the tail page if it is still pointing to the expected
> +page. If this fails, a nested write pushed it forward, the the current write
> +does not need to push it.
> +
> +
> +           temp page
> +               |
> +               v
> +            tail page
> +               |
> +               v
> +    +---+    +---+    +---+    +---+
> +<---|   |--->|   |--->|   |--->|   |--->
> +--->|   |<---|   |<---|   |<---|   |<---
> +    +---+    +---+    +---+    +---+
> +
> +Nested write comes in and moves the tail page forward:
> +
> +                    tail page (moved by nested writer)
> +            temp page   |
> +               |        |
> +               v        v
> +    +---+    +---+    +---+    +---+
> +<---|   |--->|   |--->|   |--->|   |--->
> +--->|   |<---|   |<---|   |<---|   |<---
> +    +---+    +---+    +---+    +---+
> +
> +The above would fail the cmpxchg, but since the tail page has already
> +been moved forward, the writer will just try again to reserve storage
> +on the new tail page.
> +
> +But the moving of the head page is a bit more complex.
> +
> +            tail page
> +               |
> +               v
> +    +---+    +---+    +---+    +---+
> +<---|   |--->|   |-H->|   |--->|   |--->
> +--->|   |<---|   |<---|   |<---|   |<---
> +    +---+    +---+    +---+    +---+
> +
> +The write converts the head page pointer to UPDATE.
> +
> +            tail page
> +               |
> +               v
> +    +---+    +---+    +---+    +---+
> +<---|   |--->|   |-U->|   |--->|   |--->
> +--->|   |<---|   |<---|   |<---|   |<---
> +    +---+    +---+    +---+    +---+
> +
> +But if a nested writer preempts here. It will see that the next
> +page is a head page, but it is also nested. It will detect that
> +it is nested and will save that information. The detection is the
> +fact that it sees the UPDATE flag instead of a HEADER or NORMAL
> +pointer.
> +
> +The nested writer will set the new head page pointer.
> +
> +           tail page
> +               |
> +               v
> +    +---+    +---+    +---+    +---+
> +<---|   |--->|   |-U->|   |-H->|   |--->
> +--->|   |<---|   |<---|   |<---|   |<---
> +    +---+    +---+    +---+    +---+
> +
> +But it will not reset the update back to normal. Only the writer
> +that converted a pointer from HEAD to UPDATE will convert it back
> +to NORMAL.
> +
> +                    tail page
> +                        |
> +                        v
> +    +---+    +---+    +---+    +---+
> +<---|   |--->|   |-U->|   |-H->|   |--->
> +--->|   |<---|   |<---|   |<---|   |<---
> +    +---+    +---+    +---+    +---+
> +
> +After the nested writer finishes, the outer most writer will convert
> +the UPDATE pointer to NORMAL.
> +
> +
> +                    tail page
> +                        |
> +                        v
> +    +---+    +---+    +---+    +---+
> +<---|   |--->|   |--->|   |-H->|   |--->
> +--->|   |<---|   |<---|   |<---|   |<---
> +    +---+    +---+    +---+    +---+
> +
> +
> +It can be even more complex if several nested writes came in and moved
> +the tail page ahead several pages:
> +
> +
> +(first writer)
> +
> +            tail page
> +               |
> +               v
> +    +---+    +---+    +---+    +---+
> +<---|   |--->|   |-H->|   |--->|   |--->
> +--->|   |<---|   |<---|   |<---|   |<---
> +    +---+    +---+    +---+    +---+
> +
> +The write converts the head page pointer to UPDATE.
> +
> +            tail page
> +               |
> +               v
> +    +---+    +---+    +---+    +---+
> +<---|   |--->|   |-U->|   |--->|   |--->
> +--->|   |<---|   |<---|   |<---|   |<---
> +    +---+    +---+    +---+    +---+
> +
> +Next writer comes in, and sees the update and sets up the new
> +head page.
> +
> +(second writer)
> +
> +           tail page
> +               |
> +               v
> +    +---+    +---+    +---+    +---+
> +<---|   |--->|   |-U->|   |-H->|   |--->
> +--->|   |<---|   |<---|   |<---|   |<---
> +    +---+    +---+    +---+    +---+
> +
> +The nested writer moves the tail page forward. But does not set the old
> +update page to NORMAL because it is not the outer most writer.
> +
> +                    tail page
> +                        |
> +                        v
> +    +---+    +---+    +---+    +---+
> +<---|   |--->|   |-U->|   |-H->|   |--->
> +--->|   |<---|   |<---|   |<---|   |<---
> +    +---+    +---+    +---+    +---+
> +
> +Another writer preempts and sees the page after the tail page is a head page.
> +It changes it from HEAD to UPDATE.
> +
> +(third writer)
> +
> +                    tail page
> +                        |
> +                        v
> +    +---+    +---+    +---+    +---+
> +<---|   |--->|   |-U->|   |-U->|   |--->
> +--->|   |<---|   |<---|   |<---|   |<---
> +    +---+    +---+    +---+    +---+
> +
> +The writer will move the head page forward:
> +
> +
> +(third writer)
> +
> +                    tail page
> +                        |
> +                        v
> +    +---+    +---+    +---+    +---+
> +<---|   |--->|   |-U->|   |-U->|   |-H->
> +--->|   |<---|   |<---|   |<---|   |<---
> +    +---+    +---+    +---+    +---+
> +
> +But now that the third writer did change the HEAD flag to UPDATE it
> +will convert it to normal:
> +
> +
> +(third writer)
> +
> +                    tail page
> +                        |
> +                        v
> +    +---+    +---+    +---+    +---+
> +<---|   |--->|   |-U->|   |--->|   |-H->
> +--->|   |<---|   |<---|   |<---|   |<---
> +    +---+    +---+    +---+    +---+
> +
> +
> +Then it will move the tail page, and return back to the second writer.
> +
> +
> +(second writer)
> +
> +                             tail page
> +                                 |
> +                                 v
> +    +---+    +---+    +---+    +---+
> +<---|   |--->|   |-U->|   |--->|   |-H->
> +--->|   |<---|   |<---|   |<---|   |<---
> +    +---+    +---+    +---+    +---+
> +
> +
> +The second writer will fail to move the tail page because it was already
> +moved, so it will try again and add its data to the new tail page.
> +It will return to the first writer.
> +
> +
> +(first writer)
> +
> +                             tail page
> +                                 |
> +                                 v
> +    +---+    +---+    +---+    +---+
> +<---|   |--->|   |-U->|   |--->|   |-H->
> +--->|   |<---|   |<---|   |<---|   |<---
> +    +---+    +---+    +---+    +---+
> +
> +The first writer can not know atomically test if the tail page moved
> +while it updates the HEAD page. It will then update the head page to
> +what it thinks is the new head page.
> +
> +
> +(first writer)
> +
> +                             tail page
> +                                 |
> +                                 v
> +    +---+    +---+    +---+    +---+
> +<---|   |--->|   |-U->|   |-H->|   |-H->
> +--->|   |<---|   |<---|   |<---|   |<---
> +    +---+    +---+    +---+    +---+
> +
> +Since the cmpxchg returns the old value of the pointer the first writer
> +will see it succeeded in updating the pointer from NORMAL to HEAD.
> +But as we can see, this is not good enough. It must also check to see
> +if the tail page is either where it use to be or on the next page:
> +
> +
> +(first writer)
> +
> +               A        B    tail page
> +               |        |        |
> +               v        v        v
> +    +---+    +---+    +---+    +---+
> +<---|   |--->|   |-U->|   |-H->|   |-H->
> +--->|   |<---|   |<---|   |<---|   |<---
> +    +---+    +---+    +---+    +---+
> +
> +If tail page != A and tail page does not equal B, then it must reset the
> +pointer back to NORMAL. The fact that it only needs to worry about
> +nested writers, it only needs to check this after setting the HEAD page.
> +
> +
> +(first writer)
> +
> +               A        B    tail page
> +               |        |        |
> +               v        v        v
> +    +---+    +---+    +---+    +---+
> +<---|   |--->|   |-U->|   |--->|   |-H->
> +--->|   |<---|   |<---|   |<---|   |<---
> +    +---+    +---+    +---+    +---+
> +
> +Now the writer can update the head page. This is also why the head page must
> +remain in UPDATE and only reset by the outer most writer. This prevents
> +the reader from seeing the incorrect head page.
> +
> +
> +(first writer)
> +
> +               A        B    tail page
> +               |        |        |
> +               v        v        v
> +    +---+    +---+    +---+    +---+
> +<---|   |--->|   |--->|   |--->|   |-H->
> +--->|   |<---|   |<---|   |<---|   |<---
> +    +---+    +---+    +---+    +---+
> +


^ permalink raw reply	[flat|nested] 29+ messages in thread

* Re: [PATCH 3/3] ring-buffer: add design document
  2009-06-11  3:15   ` Hidetoshi Seto
@ 2009-06-11  3:25     ` Steven Rostedt
  0 siblings, 0 replies; 29+ messages in thread
From: Steven Rostedt @ 2009-06-11  3:25 UTC (permalink / raw)
  To: Hidetoshi Seto
  Cc: linux-kernel, Ingo Molnar, Andrew Morton, Thomas Gleixner,
	Peter Zijlstra, Frederic Weisbecker, Theodore Tso,
	Arnaldo Carvalho de Melo, Mathieu Desnoyers, Lai Jiangshan,
	Martin J. Bligh, Christoph Hellwig, Li Zefan, Huang Ying,
	H. Peter Anvin, Masami Hiramatsu


On Thu, 11 Jun 2009, Hidetoshi Seto wrote:
> Steven Rostedt wrote:
> > +
> > +  +------+
> > +  |reader|          RING BUFFER
> > +  |page  |-------------------+
> > +  +------+ <---------------+ v
> > +    |  ^          +---+   +---+   +---+
> > +    |  |          |   |-->|   |-->|   |
> > +    |  |          |   |<--|   |<--|   |<-+
> > +    |  |          +---+   +---+   +---+  |
> > +    |  |             |             ^ |   |
> > +    |  |             +-------------+ |   |
> > +    |  +-----------------------------+   |
> > +    +------------------------------------+
> 
> It seems the middle of three pages have 2 prev arrows... ?

Yes that is a mistake. Thanks, I'll fix it.
> > +
> > +It does a cmpxchg with the pointer to the previous head page to make it
> > +point to the reader page. Note that the new pointer does not have the HEADER
> > +flag set.  This action atomically moves the head page forward.
> > +
> > +  +------+
> > +  |reader|          RING BUFFER
> > +  |page  |-------H-----------+
> > +  +------+ <---------------+ v
> > +    |  ^          +---+   +---+   +---+
> > +    |  |          |   |-->|   |-->|   |
> > +    |  |          |   |<--|   |<--|   |<-+
> > +    |  |          +---+   +---+   +---+  |
> > +    |  |             |             ^ |   |
> > +    |  |             +-------------+ |   |
> > +    |  +-----------------------------+   |
> > +    +------------------------------------+
> > +
> 
> Ditto.

Ditto too ;-)

Thanks,

-- Steve


^ permalink raw reply	[flat|nested] 29+ messages in thread

* Re: [PATCH 1/3] ring-buffer: make the buffer a true circular link list
  2009-06-11  2:00     ` Steven Rostedt
@ 2009-06-11  3:25       ` Lai Jiangshan
  2009-06-11  3:35         ` Steven Rostedt
  0 siblings, 1 reply; 29+ messages in thread
From: Lai Jiangshan @ 2009-06-11  3:25 UTC (permalink / raw)
  To: Steven Rostedt
  Cc: linux-kernel, Ingo Molnar, Andrew Morton, Thomas Gleixner,
	Peter Zijlstra, Frederic Weisbecker, Theodore Tso,
	Arnaldo Carvalho de Melo, Mathieu Desnoyers, Martin J. Bligh,
	Christoph Hellwig, Li Zefan, Huang Ying, H. Peter Anvin,
	Hidetoshi Seto, Masami Hiramatsu, Steven Rostedt

Steven Rostedt wrote:
> On Thu, 11 Jun 2009, Lai Jiangshan wrote:
> 
>>> -	list_splice(&pages, head);
>>> +	/*
>>> +	 * The ring buffer page list is a circular list that does not
>>> +	 * start and end with a list head. All page list items point to
>>> +	 * other pages. Remove one of the pages, init its list head,
>>> +	 * and use list splice to move the rest of the pages to it.
>>> +	 */
>>> +	bpage = list_entry(pages.next, struct buffer_page, list);
>>> +	list_del_init(&bpage->list);
>>> +	cpu_buffer->pages = &bpage->list;
>>> +
>>> +	list_splice(&pages, cpu_buffer->pages);
>>> +
>> Is it proper?
>>
>> 	cpu_buffer->pages = pages.next;
>> 	list_del(&pages);
>>
> 
> Not sure what you are asking here?
> 


I'm not sure whether these 4 lines:
	bpage = list_entry(pages.next, struct buffer_page, list);
	list_del_init(&bpage->list);
	cpu_buffer->pages = &bpage->list;

	list_splice(&pages, cpu_buffer->pages);
equal to these 2 lines:
 	cpu_buffer->pages = pages.next;
 	list_del(&pages);

If there are equivalent, I think the second one
are simpler. It may be not a really necessarily cleanup.

What I asked is: if there are equivalent, could you use these two line:
 	cpu_buffer->pages = pages.next;
 	list_del(&pages);

Lai.


^ permalink raw reply	[flat|nested] 29+ messages in thread

* Re: [PATCH 1/3] ring-buffer: make the buffer a true circular link list
  2009-06-11  3:25       ` Lai Jiangshan
@ 2009-06-11  3:35         ` Steven Rostedt
  0 siblings, 0 replies; 29+ messages in thread
From: Steven Rostedt @ 2009-06-11  3:35 UTC (permalink / raw)
  To: Lai Jiangshan
  Cc: linux-kernel, Ingo Molnar, Andrew Morton, Thomas Gleixner,
	Peter Zijlstra, Frederic Weisbecker, Theodore Tso,
	Arnaldo Carvalho de Melo, Mathieu Desnoyers, Martin J. Bligh,
	Christoph Hellwig, Li Zefan, Huang Ying, H. Peter Anvin,
	Hidetoshi Seto, Masami Hiramatsu, Steven Rostedt


On Thu, 11 Jun 2009, Lai Jiangshan wrote:
> 
> I'm not sure whether these 4 lines:
> 	bpage = list_entry(pages.next, struct buffer_page, list);
> 	list_del_init(&bpage->list);
> 	cpu_buffer->pages = &bpage->list;
> 
> 	list_splice(&pages, cpu_buffer->pages);

> equal to these 2 lines:
>  	cpu_buffer->pages = pages.next;
>  	list_del(&pages);
> 
> If there are equivalent, I think the second one
> are simpler. It may be not a really necessarily cleanup.
> 
> What I asked is: if there are equivalent, could you use these two line:
>  	cpu_buffer->pages = pages.next;
>  	list_del(&pages);

OK, now I understand.

Hmm, that may be so. I'll have to look deeper at that.

Thanks,

-- Steve


^ permalink raw reply	[flat|nested] 29+ messages in thread

* Re: [PATCH 3/3] ring-buffer: add design document
  2009-06-11  1:55     ` Steven Rostedt
@ 2009-06-11  3:51       ` Mathieu Desnoyers
  2009-06-11  3:59         ` Mathieu Desnoyers
  0 siblings, 1 reply; 29+ messages in thread
From: Mathieu Desnoyers @ 2009-06-11  3:51 UTC (permalink / raw)
  To: Steven Rostedt
  Cc: linux-kernel, Ingo Molnar, Andrew Morton, Thomas Gleixner,
	Peter Zijlstra, Frederic Weisbecker, Theodore Tso,
	Arnaldo Carvalho de Melo, Lai Jiangshan, Martin J. Bligh,
	Christoph Hellwig, Li Zefan, Huang Ying, H. Peter Anvin,
	Hidetoshi Seto, Masami Hiramatsu, ltt-dev, Robert Wisniewski,
	Paul E. McKenney

* Steven Rostedt (rostedt@goodmis.org) wrote:
> 
> On Wed, 10 Jun 2009, Mathieu Desnoyers wrote:
> > * Steven Rostedt (rostedt@goodmis.org) wrote:
> > > +The Generic Ring Buffer
> > > +-----------------------
> > > +
> > > +The ring buffer can be used in either an overwrite mode or in
> > > +producer/consumer mode.
> > > +
> > > +Producer/consumer mode is where the producer were to fill up the
> > > +buffer before the consumer could free up anything, the producer
> > > +will stop writing to the buffer. This will lose most recent events.
> > > +
> > > +Overwrite mode is where the produce were to fill up the buffer
> > > +before the consumer could free up anything, the producer will
> > > +overwrite the older data. This will lose the oldest events.
> > > +
> > > +No two writers can write at the same time (on the same per cpu buffer),
> > > +but a writer may preempt another writer, but it must finish writing
> > 
> > Hi Steven,
> > 
> > I would use "interrupt" instead of "preempt" here, given that preemption
> > implies scheduler activity which is specifically forbidden here.
> 
> Good point, I'll update it.
> 

Please also look thorough the code... at some places you seem to imply
that the reader "must" be on a remote CPU, when you actually mean
"could" be on a remote or local cpu.

> > 
> > > +before the previous writer may continue. This is very important to the
> > > +algorithm. The writers act like a "stack".
> > > +
> > > +
> > > +  writer1 start
> > > +     <preempted> writer2 start
> > > +         <preempted> writer3 start
> > > +                     writer3 finishes
> > > +                 writer2 finishes
> > > +  writer1 finishes
> > > +
> > > +This is very much like a writer being preempted by an interrupt and
> > > +the interrupt doing a write as well.
> > > +
> > > +Readers can happen at any time. But no two readers may run at the
> > > +same time, nor can a reader preempt another reader. A reader can not preempt
> > > +a writer, but it may read/consume from the buffer at the same time as
> > > +a writer is writing, but the reader must be on another processor.
> > > +
> > > +A writer can preempt a reader, but a reader can not preempt a writer.
> > > +But a reader can read the buffer at the same time (on another processor)
> > > +as a writer.
> > > +
> > 
> > This comment is inconsistent with the following code comment :
> > 
> > "* Reads can happen on any CPU."
> > 
> > Readers should be allowed to read from their own cpu's buffers too, and
> > support being interrupted by an incoming interrupt writer, but this
> > design document does not discuss this case. Is it at all supported ? If
> > not, then this algorithm would not work on uniprocessor.
> 
> Yes it is supported. That's what I mean by "A writer can preempt a 
> reader". I'll change it to "A writer can interrupt a reader". Would that 
> sound better?
> 
> But a reader can not interrupt a writer. I hope you don't plan on doing 
> reads of the ring buffer from an interrupt.
> 

Yep.

> 
> > 
> > > +The ring buffer is made up of a list of pages held together by a link list.
> > > +
> > > +At initialization a reader page is allocated for the reader that is not
> > > +part of the ring buffer.
> > > +
> > > +The head_page, tail_page and commit_page are all initialized to point
> > > +to the same page.
> > > +
> > > +The reader page is initialized to have its next pointer pointing to
> > > +the head page, and its previous pointer pointing to a page before
> > > +the head page.
> > > +
> > > +The reader has its own page to use. At start up time, this page is
> > > +allocated but is not attached to the list. When the reader wants
> > > +to read from the buffer, if its page is empty (like it is on start up)
> > > +it will swap its page with the head_page. The old reader page will
> > > +become part of the ring buffer and the head_page will be removed.
> > > +A new head page goes to the page after the old head page (but not
> > > +the page that was swapped in).
> > > +
> > > +Once the new page is given to the reader, the reader could do what
> > > +it wants with it, as long as a writer has left that page.
> > > +
> > > +A sample of how the reader page is swapped: Note this does not
> > > +show the head page in the buffer, it is for demonstrating a swap
> > > +only.
> > > +
> > > +  +------+
> > > +  |reader|          RING BUFFER
> > > +  |page  |
> > > +  +------+
> > > +                  +---+   +---+   +---+
> > > +                  |   |-->|   |-->|   |
> > > +                  |   |<--|   |<--|   |
> > > +                  +---+   +---+   +---+
> > > +                   ^ |             ^ |
> > > +                   | +-------------+ |
> > > +                   +-----------------+
> > > +
> > > +
> > > +  +------+
> > > +  |reader|          RING BUFFER
> > > +  |page  |-------------------+
> > > +  +------+                   v
> > > +    |             +---+   +---+   +---+
> > > +    |             |   |-->|   |-->|   |
> > > +    |             |   |<--|   |<--|   |<-+
> > > +    |             +---+   +---+   +---+  |
> > > +    |              ^ |             ^ |   |
> > > +    |              | +-------------+ |   |
> > > +    |              +-----------------+   |
> > > +    +------------------------------------+
> > > +
> > > +  +------+
> > > +  |reader|          RING BUFFER
> > > +  |page  |-------------------+
> > > +  +------+ <---------------+ v
> > > +    |  ^          +---+   +---+   +---+
> > > +    |  |          |   |-->|   |-->|   |
> > > +    |  |          |   |<--|   |<--|   |<-+
> > > +    |  |          +---+   +---+   +---+  |
> > > +    |  |             |             ^ |   |
> > > +    |  |             +-------------+ |   |
> > > +    |  +-----------------------------+   |
> > > +    +------------------------------------+
> > > +
> > > +  +------+
> > > +  |buffer|          RING BUFFER
> > > +  |page  |-------------------+
> > > +  +------+ <---------------+ v
> > > +    |  ^          +---+   +---+   +---+
> > > +    |  |          |   |   |   |-->|   |
> > > +    |  |  New     |   |   |   |<--|   |<-+
> > > +    |  | Reader   +---+   +---+   +---+  |
> > > +    |  |  page ----^                 |   |
> > > +    |  |                             |   |
> > > +    |  +-----------------------------+   |
> > > +    +------------------------------------+
> > > +
> > 
> > Nice ascii art ;)
> > 
> > Some important comments below,
> 
> I draw best with plus's and minus's ;-)
> 
> > 
> > > +
> > > +
> > > +It is possible that the page swapped is the commit page and the tail page,
> > > +if what is in the ring buffer is less than what is held in a buffer page.
> > > +
> > > +
> > > +          reader page    commit page   tail page
> > > +              |              |             |
> > > +              v              |             |
> > > +             +---+           |             |
> > > +             |   |<----------+             |
> > > +             |   |<------------------------+
> > > +             |   |------+
> > > +             +---+      |
> > > +                        |
> > > +                        v
> > > +    +---+    +---+    +---+    +---+
> > > +<---|   |--->|   |--->|   |--->|   |--->
> > > +--->|   |<---|   |<---|   |<---|   |<---
> > > +    +---+    +---+    +---+    +---+
> > > +
> > > +This case is still legal for this algorithm.
> > > +When the writer leaves the page, it simply goes into the ring buffer
> > > +since the reader page still points to the next location in the ring
> > > +buffer.
> > > +
> > > +
> > > +The main pointers:
> > > +
> > > +  reader page - The page used solely by the reader and is not part
> > > +                of the ring buffer (may be swapped in)
> > > +
> > > +  head page - the next page in the ring buffer that will be swapped
> > > +              with the reader page.
> > > +
> > > +  tail page - the page where the next write will take place.
> > > +
> > > +  commit page - the page that last finished a write.
> > > +
> > > +The commit page only is updated by the outer most writer in the
> > > +writer stack. A writer that preempts another writer will not move the
> > > +commit page.
> > > +
> > > +When data is written into the ring buffer, a position is reserved
> > > +in the ring buffer and passed back to the writer. When the writer
> > > +is finished writing data into that position, it commits the write.
> > > +
> > > +Another write (or a read) may take place at anytime during this
> > > +transaction. If another write happens it must finish before continuing
> > > +with the previous write.
> > > +
> > > +
> > > +   Write reserve:
> > > +
> > > +       Buffer page
> > > +      +---------+
> > > +      |written  |
> > > +      +---------+  <--- given back to writer (current commit)
> > > +      |reserved |
> > > +      +---------+ <--- tail pointer
> > > +      | empty   |
> > > +      +---------+
> > > +
> > > +   Write commit:
> > > +
> > > +       Buffer page
> > > +      +---------+
> > > +      |written  |
> > > +      +---------+
> > > +      |written  |
> > > +      +---------+  <--- next positon for write (current commit)
> > > +      | empty   |
> > > +      +---------+
> > > +
> > > +
> > > + If a write happens after the first reserve:
> > > +
> > > +       Buffer page
> > > +      +---------+
> > > +      |written  |
> > > +      +---------+  <-- current commit
> > > +      |reserved |
> > > +      +---------+  <--- given back to second writer
> > > +      |reserved |
> > > +      +---------+ <--- tail pointer
> > > +
> > > +  After second writer commits:
> > > +
> > > +
> > > +       Buffer page
> > > +      +---------+
> > > +      |written  |
> > > +      +---------+  <--(last full commit)
> > > +      |reserved |
> > > +      +---------+
> > > +      |pending  |
> > > +      |commit   |
> > > +      +---------+ <--- tail pointer
> > > +
> > > +  When the first writer commits:
> > > +
> > > +       Buffer page
> > > +      +---------+
> > > +      |written  |
> > > +      +---------+
> > > +      |written  |
> > > +      +---------+
> > > +      |written  |
> > > +      +---------+  <--(last full commit and tail pointer)
> > > +
> > > +
> > > +The commit pointer points to the last write location that was
> > > +committed without preempting another write. When a write that
> > > +preempted another write is committed, it only becomes a pending commit
> > > +and will not be a full commit till all writes have been committed.
> > > +
> > > +The commit page points to the page that has the last full commit.
> > > +The tail page points to the page with the last write (before
> > > +committing).
> > > +
> > > +The tail page is always equal to or after the commit page. It may
> > > +be several pages ahead. If the tail page catches up to the commit
> > > +page then no more writes may take place (regardless of the mode
> > > +of the ring buffer: overwrite and produce/consumer).
> > > +
> > > +The order of pages are:
> > > +
> > > + head page
> > > + commit page
> > > + tail page
> > > +
> > > +Possible scenario:
> > > +                             tail page
> > > +  head page         commit page  |
> > > +      |                 |        |
> > > +      v                 v        v
> > > +    +---+    +---+    +---+    +---+
> > > +<---|   |--->|   |--->|   |--->|   |--->
> > > +--->|   |<---|   |<---|   |<---|   |<---
> > > +    +---+    +---+    +---+    +---+
> > > +
> > > +There is a special case that the head page is after either the commit page
> > > +and possibly the tail page. That is when the commit (and tail) page has been
> > > +swapped with the reader page. This is because the head page is always
> > > +part of the ring buffer, but the reader page is not. When ever there
> > > +has been less than a full page that has been committed inside the ring buffer,
> > > +and a reader swaps out a page, it will be swapping out the commit page.
> > > +
> > > +
> > > +          reader page    commit page   tail page
> > > +              |              |             |
> > > +              v              |             |
> > > +             +---+           |             |
> > > +             |   |<----------+             |
> > > +             |   |<------------------------+
> > > +             |   |------+
> > > +             +---+      |
> > > +                        |
> > > +                        v
> > > +    +---+    +---+    +---+    +---+
> > > +<---|   |--->|   |--->|   |--->|   |--->
> > > +--->|   |<---|   |<---|   |<---|   |<---
> > > +    +---+    +---+    +---+    +---+
> > > +                        ^
> > > +                        |
> > > +                    head page
> > > +
> > > +
> > > +In this case, the head page will not move when the tail and commit
> > > +move back into the ring buffer.
> > > +
> > > +The reader can not swap a page into the ring buffer if the commit page
> > > +is still on that page. If the read meets the last commit (real commit
> > > +not pending or reserved), then there is nothing more to read.
> > > +The buffer is considered empty until another full commit finishes.
> > > +
> > > +When the tail meets the head page, if the buffer is in overwrite mode,
> > > +the head page will be pushed ahead one. If the buffer is in producer/consumer
> > > +mode, the write will fail.
> > > +
> > > +Overwrite mode:
> > > +
> > > +            tail page
> > > +               |
> > > +               v
> > > +    +---+    +---+    +---+    +---+
> > > +<---|   |--->|   |--->|   |--->|   |--->
> > > +--->|   |<---|   |<---|   |<---|   |<---
> > > +    +---+    +---+    +---+    +---+
> > > +                        ^
> > > +                        |
> > > +                    head page
> > > +
> > > +
> > > +            tail page
> > > +               |
> > > +               v
> > > +    +---+    +---+    +---+    +---+
> > > +<---|   |--->|   |--->|   |--->|   |--->
> > > +--->|   |<---|   |<---|   |<---|   |<---
> > > +    +---+    +---+    +---+    +---+
> > > +                                 ^
> > > +                                 |
> > > +                             head page
> > > +
> > > +
> > > +                    tail page
> > > +                        |
> > > +                        v
> > > +    +---+    +---+    +---+    +---+
> > > +<---|   |--->|   |--->|   |--->|   |--->
> > > +--->|   |<---|   |<---|   |<---|   |<---
> > > +    +---+    +---+    +---+    +---+
> > > +                                 ^
> > > +                                 |
> > > +                             head page
> > > +
> > > +Note, the reader page will still point to the previous head page.
> > > +But when a swap takes place, it will use the most recent head page.
> > > +
> > > +
> > > +Making the Ring Buffer Lockless:
> > > +--------------------------------
> > > +
> > > +The main idea behind the lockless algorithm is to combine the moving
> > > +of the head_page pointer with the swapping of pages with the reader.
> > > +State flags are placed inside the pointer to the page. To do this,
> > > +each page must be aligned in memory by 4 bytes. This will allow the 2
> > > +least significant bits of the address to be used as flags. Since
> > > +they will always be zero for the address. To get the address,
> > > +simply mask out the flags.
> > > +
> > > +  MASK = ~3
> > > +
> > > +  address & MASK
> > > +
> > > +Two flags will be kept by these two bits:
> > > +
> > > +   HEADER - the page being pointed to is a head page
> > > +
> > > +   UPDATE - the page being pointed to is being updated by a writer
> > > +          and was or is about to be a head page.
> > > +
> > > +
> > > +          reader page
> > > +              |
> > > +              v
> > > +             +---+
> > > +             |   |------+
> > > +             +---+      |
> > > +                        |
> > > +                        v
> > > +    +---+    +---+    +---+    +---+
> > > +<---|   |--->|   |-H->|   |--->|   |--->
> > > +--->|   |<---|   |<---|   |<---|   |<---
> > > +    +---+    +---+    +---+    +---+
> > > +
> > > +
> > > +The above pointer "-H->" would have the HEADER flag set. That is
> > > +the next page is the next page to be swapped out by the reader.
> > > +This pointer means the next page is the head page.
> > > +
> > > +When the tail page meets the head pointer, it will use cmpxchg to
> > > +change the pointer to the UPDATE state:
> > > +
> > > +
> > > +            tail page
> > > +               |
> > > +               v
> > > +    +---+    +---+    +---+    +---+
> > > +<---|   |--->|   |-H->|   |--->|   |--->
> > > +--->|   |<---|   |<---|   |<---|   |<---
> > > +    +---+    +---+    +---+    +---+
> > > +
> > > +            tail page
> > > +               |
> > > +               v
> > > +    +---+    +---+    +---+    +---+
> > > +<---|   |--->|   |-U->|   |--->|   |--->
> > > +--->|   |<---|   |<---|   |<---|   |<---
> > > +    +---+    +---+    +---+    +---+
> > > +
> > > +"-U->" represents a pointer in the UPDATE state.
> > > +
> > > +Any access to the reader will need to take some sort of lock to serialize
> > > +the readers. But the writers will never take a lock to write to the
> > > +ring buffer. This means we only need to worry about a single reader,
> > > +and writes only preempt in "stack" formation.
> > > +
> > > +When the reader tries to swap the page with the ring buffer, it
> > > +will also use cmpxchg. If the flag bit in the pointer to the
> > > +head page does not have the HEADER flag set, the compare will fail
> > > +and the reader will need to look for the new head page and try again.
> > > +Note, the flag UPDATE and HEADER are never set at the same time.
> > > +
> > > +The reader swaps the reader page as follows:
> > > +
> > > +  +------+
> > > +  |reader|          RING BUFFER
> > > +  |page  |
> > > +  +------+
> > > +                  +---+    +---+    +---+
> > > +                  |   |--->|   |--->|   |
> > > +                  |   |<---|   |<---|   |
> > > +                  +---+    +---+    +---+
> > > +                   ^ |               ^ |
> > > +                   | +---------------+ |
> > > +                   +-----H-------------+
> > > +
> > > +The reader sets the reader page next pointer as HEADER to the page after
> > > +the head page.
> > > +
> > > +
> > > +  +------+
> > > +  |reader|          RING BUFFER
> > > +  |page  |-------H-----------+
> > > +  +------+                   v
> > > +    |             +---+    +---+    +---+
> > > +    |             |   |--->|   |--->|   |
> > > +    |             |   |<---|   |<---|   |<-+
> > > +    |             +---+    +---+    +---+  |
> > > +    |              ^ |               ^ |   |
> > > +    |              | +---------------+ |   |
> > > +    |              +-----H-------------+   |
> > > +    +--------------------------------------+
> > > +
> > > +It does a cmpxchg with the pointer to the previous head page to make it
> > > +point to the reader page. Note that the new pointer does not have the HEADER
> > > +flag set.  This action atomically moves the head page forward.
> > > +
> > > +  +------+
> > > +  |reader|          RING BUFFER
> > > +  |page  |-------H-----------+
> > > +  +------+ <---------------+ v
> > > +    |  ^          +---+   +---+   +---+
> > > +    |  |          |   |-->|   |-->|   |
> > > +    |  |          |   |<--|   |<--|   |<-+
> > > +    |  |          +---+   +---+   +---+  |
> > > +    |  |             |             ^ |   |
> > > +    |  |             +-------------+ |   |
> > > +    |  +-----------------------------+   |
> > > +    +------------------------------------+
> > > +
> > > +After the new head page is set, the previous pointer of the head page is
> > > +updated to the reader page.
> > > +
> > > +  +------+
> > > +  |reader|          RING BUFFER
> > > +  |page  |-------H-----------+
> > > +  +------+                   v
> > > +    |  ^          +---+   +---+   +---+
> > > +    |  |          |   |-->|   |-->|   |
> > > +    |  |          |   |<--|   |<--|   |<-+
> > > +    |  |          +---+   +---+   +---+  |
> > > +    |  |             |             ^ |   |
> > > +    |  |             +-------------+ |   |
> > > +    |  +-----------------------------+   |
> > > +    +------------------------------------+
> > > +
> > > +  +------+
> > > +  |buffer|          RING BUFFER
> > > +  |page  |-------H-----------+  <--- New head page
> > > +  +------+ <---------------+ v
> > > +    |  ^          +---+   +---+   +---+
> > > +    |  |          |   |   |   |-->|   |
> > > +    |  |  New     |   |   |   |<--|   |<-+
> > > +    |  | Reader   +---+   +---+   +---+  |
> > > +    |  |  page ----^                 |   |
> > > +    |  |                             |   |
> > > +    |  +-----------------------------+   |
> > > +    +------------------------------------+
> > > +
> > > +Another important point. The page that the reader page points back to
> > > +by its previous pointer (the one that now points to the new head page)
> > > +never points back to the reader page. That is because the reader page is
> > > +not part of the ring buffer. Traversing the ring buffer via the next pointers
> > > +will always stay in the ring buffer. Traversing the ring buffer via the
> > > +prev pointers may not.
> > > +
> > > +Note, the way to determine a reader page is simply by examining the previous
> > > +pointer of the page. If the next pointer of the previous page does not
> > > +point back to the original page, then the original page is a reader page:
> > > +
> > > +                                  
> > > +             +--------+
> > > +             | reader |  next   +----+
> > > +             |  page  |-------->|    |<====== (buffer page)
> > > +             +--------+         +----+
> > > +                 |                | ^
> > > +                 |                v | next
> > > +            prev |              +----+
> > > +                 +------------->|    |
> > > +                                +----+
> > > +
> > > +The way the head page moves forward:
> > > +
> > > +When the tail page meets the head page and the buffer is in overwrite mode
> > > +and more writes take place, the head page must be moved forward before the
> > > +writer may move the tail page. The way this is done is that the writer
> > > +performs a cmpxchg to convert the pointer to the head page from the HEADER
> > > +flag to have the UPDATE flag set. Once this is done, the reader will
> > > +not be able to swap the head page from the buffer, nor will it be able to
> > > +move the head page, until the writer is finished with the move.
> > > +
> > > +This eliminates any races that the reader can have on the writer. The reader
> > > +must spin, and this is why the reader can not preempt the writer.
> > > +
> > > +            tail page
> > > +               |
> > > +               v
> > > +    +---+    +---+    +---+    +---+
> > > +<---|   |--->|   |-H->|   |--->|   |--->
> > > +--->|   |<---|   |<---|   |<---|   |<---
> > > +    +---+    +---+    +---+    +---+
> > > +
> > > +            tail page
> > > +               |
> > > +               v
> > > +    +---+    +---+    +---+    +---+
> > > +<---|   |--->|   |-U->|   |--->|   |--->
> > > +--->|   |<---|   |<---|   |<---|   |<---
> > > +    +---+    +---+    +---+    +---+
> > > +
> > > +The following page will be made into the new head page.
> > > +
> > > +           tail page
> > > +               |
> > > +               v
> > > +    +---+    +---+    +---+    +---+
> > > +<---|   |--->|   |-U->|   |-H->|   |--->
> > > +--->|   |<---|   |<---|   |<---|   |<---
> > > +    +---+    +---+    +---+    +---+
> > > +
> > > +After the new head page has been set, we can set the old head page
> > > +pointer back to NORMAL.
> > > +
> > > +           tail page
> > > +               |
> > > +               v
> > > +    +---+    +---+    +---+    +---+
> > > +<---|   |--->|   |--->|   |-H->|   |--->
> > > +--->|   |<---|   |<---|   |<---|   |<---
> > > +    +---+    +---+    +---+    +---+
> > > +
> > > +After the head page has been moved, the tail page may now move forward.
> > > +
> > > +                    tail page
> > > +                        |
> > > +                        v
> > > +    +---+    +---+    +---+    +---+
> > > +<---|   |--->|   |--->|   |-H->|   |--->
> > > +--->|   |<---|   |<---|   |<---|   |<---
> > > +    +---+    +---+    +---+    +---+
> > > +
> > > +
> > > +The above are the trivial updates. Now for the more complex scenarios.
> > > +
> > > +
> > > +As stated before, if enough writes preempt the first write, the
> > > +tail page may make it all the way around the buffer and meet the commit
> > > +page. At this time, we must start dropping writes (usually with some kind
> > > +of warning to the user). But what happens if the commit was still on the
> > > +reader page? The commit page is not part of the ring buffer. The tail page
> > > +must account for this.
> > > +
> > > +
> > > +          reader page    commit page
> > > +              |              |
> > > +              v              |
> > > +             +---+           |
> > > +             |   |<----------+
> > > +             |   |
> > > +             |   |------+
> > > +             +---+      |
> > > +                        |
> > > +                        v
> > > +    +---+    +---+    +---+    +---+
> > > +<---|   |--->|   |-H->|   |--->|   |--->
> > > +--->|   |<---|   |<---|   |<---|   |<---
> > > +    +---+    +---+    +---+    +---+
> > > +               ^
> > > +               |
> > > +           tail page
> > > +
> > > +If the tail page were to simply push the head page forward, the commit when
> > > +leaving the reader page would not be pointing to the correct page.
> > > +
> > > +The solution to this is to test if the commit page is on the reader page
> > > +before pushing the head page. If it is, then it can be assumed that the
> > > +tail page wrapped the buffer, and we must drop new writes.
> > > +
> > > +This is not a race condition, because the commit page can only be moved
> > > +by the outter most writer (the writer that was preempted).
> > > +This means that the commit will not move while a writer is moving the
> > > +tail page. The reader can not swap the reader page if it is also being
> > > +used as the commit page. The reader can simply check that the commit
> > > +is off the reader page. Once the commit page leaves the reader page
> > > +it will never go back on it unless a reader does another swap with the
> > > +buffer page that is also the commit page.
> > > +
> > > +
> > > +Nested writes
> > > +-------------
> > > +
> > > +In the pushing forward of the tail page we must first push forward
> > > +the head page if the head page is the next page. If the head page
> > > +is not the next page, the tail page is simply updated with a cmpxchg.
> > > +
> > > +Only writers move the tail page. This must be done atomically to protect
> > > +against nested writers.
> > > +
> > > +  temp_page = tail_page
> > > +  next_page = temp_page->next
> > > +  cmpxchg(tail_page, temp_page, next_page)
> > > +
> > 
> > OK, I'll bite :
> > 
> > What happens if :
> > 
> > - a writer is at the end of a page, 
> > - needs to push the tail_page pointer
> > - reads tail_page
> >   - interrupted.
> >   - nested writers come, successfully updates the tail_page, write
> >     enough data to fill the whole buffer
> >   - concurrently (on another CPU), a reader is consuming all the data
> >   - This brings the tail_page pointer back to its original value
> >   - iret
> > - here, the writer will successfully perform the tail_page cmpxchg,
> >   because the value match. However, the page currently being written to
> >   could be only partially reserved; the writer will not re-check if the
> >   page is really full.
> > 
> > That's actually one of my main concerns with an approach where two
> > separate "pointers" are used to keep track of reserved space within a
> > buffer.
> 
> Actually, the two pointers is exactly what prevents the above scenario.
> 
> We have a commit page pointer and a commit index pointer. The commit page
> points to the page that holds the last true commit. A read can never go 
> pass the commit. That is, it can not read reserved but uncommited data.
> 

OK, I see how the commit counter can ensure the reader will not read
reserved-by-yet-uncommitted data.


> Another key point is that if the tail page meets the commit page, it will 
> not move it and drop the data. If your buffer is not big enough to hold 
> all data in a interrupt, then your buffer is too small. We count these in 
> the "commit_overrun" counter as well as return NULL on the reserve so the 
> tracer will know that it had its data dropped.
> 

Ah ok, so the following writer-only scenario :

- a writer is at the end of a page, 
- needs to push the tail_page pointer
- reads tail_page
  - interrupted.
  - nested writers come, successfully updates the tail_page, write
    enough data to fill the whole buffer
  - Brings the tail_page pointer back to its original value <----------

Cannot happen, because it would meet the commit page.

That's a bit weird to drop events in overwrite mode. Normally, one would
expect that mode to just permit to write any amount of events, from any
execution context, be it nested or not, overwriting the oldest events.

> 
> > 
> > The same concern applies to moving the head page when concurrent writers
> > are nesting.
> > 
> > More generally, I'm also concerned about the lack of memory barriers
> > around some non-cmpxchg tail/head page set operations in your code, and
> > the lack of proper rcu_dereference-style primitive for list iteration.
> 
> The cmpxchg is a memory barrier. Writes only contend with other writes on 
> the same CPU. When we update the pointer from HEAD to UPDATE a reader will
> not pass that point. The update is done via cmpxchg and thus is a memory 
> barrier. Now if cmpxchg is not a memory barrier, then I need to add 
> smp_mb() by all of them.
> 

Documentation/memory-barriers.txt states that cmpxchg must behave as if
it had smp_mb() before and after.

> > 
> > For those I've added to CC, I'm referring to the patch at :
> > 
> > http://patchwork.kernel.org/patch/29395/
> > 
> > The great news to me is that no one can say LTTng's lockless buffering
> > algorithm is complex compared to this. ;)
> 
> But can you read without worries about writers? The nice thing about this 
> approach, which a lot of ftrace depends on, is that I don't need call 
> backs or copies to check if what I read from the buffer was not stomped 
> on by a writer. There is a zero copy overhead for readers (when the buffer 
> is more than a page filled) and when a reader has its data, it belongs to 
> that reader.
> 

Hrm, now that you bring this question on the table again (I remember we
discussed about it at the collaboration summit), and now that there is
no alcohol involved, I see a way to do it. Here is the idea :

I assume you remember a bit how the global per-buffer write_offset and
read_offset counters work in LTTng : writer head and reader head are
positions in what we can think of as a virtually contiguous buffer
address space for the whole buffer.

First, let's talk in terms of get_subbuf() (reader get a subbuffer
exclusive access for reading) and put_subbuf() (reader releases its
exclusive subbuffer access). get_subbuf() returns the current
read_offset, and put_subbuf() takes this read_offset (the one returned
by get_subbuf()), as parameter.

Let's say that we let get_subbuf() use cmpxchg to write a flag in the
read_offset counter to tell the writer it's actively reading, e.g.
OFFSET_READING_FLAG = 0x1. It's reading the read_offset at the same
time because the update is done with a cmpxchg.

Now for the writer : in overwrite mode, if the write_offset comes to a
point where it would have to push the reader position (read offset) in
order to be able to reserve space *and* the reader is actively reading
data from the buffer (we know it because OFFSET_READING_FLAG is set),
the writer could set a flag in the read_offset LSBs
(OFFSET_PUSH_FLAG = 0x2). The writer would simply skip over this
specific subbuffer, and that's it : it can continue to write in the
buffer after the subbuffer owned by the reader without problem. If it
loops a few times over the buffer while the reader is still stucked
there (think of a slow serial port), it would simply skip over the
subbuffer owned by the reader.

Now, when the reader eventually releases its current subbuffer
(put_subbuf()), it would detect that the read_offset is different than
the one returned by get_subbuf() because the OFFSET_PUSH_FLAG would have
been set. This will inform the reader that it must push its own
read_offset position to the subbuffer following the current
write_offset position. That's it, we're back on track : the next reader
will read the oldest available subbuffer.

I took special care in the design above to make sure the case where
tracing starts still works. In this case, where the buffer is only
partially filled, the reader head is not in the subbuffer following the
writer head, because it points to uninitialized data. But the
OFFSET_PUSH_FLAG can only ever be set when a writer has at least
completely filled the buffer once (and meets the read_offset), so we can
consider that it's safe for put_subbuf() to move right after the write
offset subbuffer.

I must admit that the flag idea is a bit inspired from your lockless
algo I am currently reviewing. :)

Does it make sense ?

Mathieu

Note : I won't be available for implementation work before July 6th...
got a thesis to write...


> -- Steve
> 

-- 
Mathieu Desnoyers
OpenPGP key fingerprint: 8CD5 52C3 8E3C 4140 715F  BA06 3F25 A8FE 3BAE 9A68

^ permalink raw reply	[flat|nested] 29+ messages in thread

* Re: [PATCH 3/3] ring-buffer: add design document
  2009-06-11  3:51       ` Mathieu Desnoyers
@ 2009-06-11  3:59         ` Mathieu Desnoyers
  2009-06-11  4:15           ` Steven Rostedt
  0 siblings, 1 reply; 29+ messages in thread
From: Mathieu Desnoyers @ 2009-06-11  3:59 UTC (permalink / raw)
  To: Steven Rostedt
  Cc: linux-kernel, Ingo Molnar, Andrew Morton, Thomas Gleixner,
	Peter Zijlstra, Frederic Weisbecker, Theodore Tso,
	Arnaldo Carvalho de Melo, Lai Jiangshan, Martin J. Bligh,
	Christoph Hellwig, Li Zefan, Huang Ying, H. Peter Anvin,
	Hidetoshi Seto, Masami Hiramatsu, ltt-dev, Robert Wisniewski,
	Paul E. McKenney

* Mathieu Desnoyers (compudj@krystal.dyndns.org) wrote:
> * Steven Rostedt (rostedt@goodmis.org) wrote:
> > 
> > On Wed, 10 Jun 2009, Mathieu Desnoyers wrote:
> > > * Steven Rostedt (rostedt@goodmis.org) wrote:
> > > > +The Generic Ring Buffer
> > > > +-----------------------
> > > > +
> > > > +The ring buffer can be used in either an overwrite mode or in
> > > > +producer/consumer mode.
> > > > +
> > > > +Producer/consumer mode is where the producer were to fill up the
> > > > +buffer before the consumer could free up anything, the producer
> > > > +will stop writing to the buffer. This will lose most recent events.
> > > > +
> > > > +Overwrite mode is where the produce were to fill up the buffer
> > > > +before the consumer could free up anything, the producer will
> > > > +overwrite the older data. This will lose the oldest events.
> > > > +
> > > > +No two writers can write at the same time (on the same per cpu buffer),
> > > > +but a writer may preempt another writer, but it must finish writing
> > > 
> > > Hi Steven,
> > > 
> > > I would use "interrupt" instead of "preempt" here, given that preemption
> > > implies scheduler activity which is specifically forbidden here.
> > 
> > Good point, I'll update it.
> > 
> 
> Please also look thorough the code... at some places you seem to imply
> that the reader "must" be on a remote CPU, when you actually mean
> "could" be on a remote or local cpu.
> 
> > > 
> > > > +before the previous writer may continue. This is very important to the
> > > > +algorithm. The writers act like a "stack".
> > > > +
> > > > +
> > > > +  writer1 start
> > > > +     <preempted> writer2 start
> > > > +         <preempted> writer3 start
> > > > +                     writer3 finishes
> > > > +                 writer2 finishes
> > > > +  writer1 finishes
> > > > +
> > > > +This is very much like a writer being preempted by an interrupt and
> > > > +the interrupt doing a write as well.
> > > > +
> > > > +Readers can happen at any time. But no two readers may run at the
> > > > +same time, nor can a reader preempt another reader. A reader can not preempt
> > > > +a writer, but it may read/consume from the buffer at the same time as
> > > > +a writer is writing, but the reader must be on another processor.
> > > > +
> > > > +A writer can preempt a reader, but a reader can not preempt a writer.
> > > > +But a reader can read the buffer at the same time (on another processor)
> > > > +as a writer.
> > > > +
> > > 
> > > This comment is inconsistent with the following code comment :
> > > 
> > > "* Reads can happen on any CPU."
> > > 
> > > Readers should be allowed to read from their own cpu's buffers too, and
> > > support being interrupted by an incoming interrupt writer, but this
> > > design document does not discuss this case. Is it at all supported ? If
> > > not, then this algorithm would not work on uniprocessor.
> > 
> > Yes it is supported. That's what I mean by "A writer can preempt a 
> > reader". I'll change it to "A writer can interrupt a reader". Would that 
> > sound better?
> > 
> > But a reader can not interrupt a writer. I hope you don't plan on doing 
> > reads of the ring buffer from an interrupt.
> > 
> 
> Yep.
> 
> > 
> > > 
> > > > +The ring buffer is made up of a list of pages held together by a link list.
> > > > +
> > > > +At initialization a reader page is allocated for the reader that is not
> > > > +part of the ring buffer.
> > > > +
> > > > +The head_page, tail_page and commit_page are all initialized to point
> > > > +to the same page.
> > > > +
> > > > +The reader page is initialized to have its next pointer pointing to
> > > > +the head page, and its previous pointer pointing to a page before
> > > > +the head page.
> > > > +
> > > > +The reader has its own page to use. At start up time, this page is
> > > > +allocated but is not attached to the list. When the reader wants
> > > > +to read from the buffer, if its page is empty (like it is on start up)
> > > > +it will swap its page with the head_page. The old reader page will
> > > > +become part of the ring buffer and the head_page will be removed.
> > > > +A new head page goes to the page after the old head page (but not
> > > > +the page that was swapped in).
> > > > +
> > > > +Once the new page is given to the reader, the reader could do what
> > > > +it wants with it, as long as a writer has left that page.
> > > > +
> > > > +A sample of how the reader page is swapped: Note this does not
> > > > +show the head page in the buffer, it is for demonstrating a swap
> > > > +only.
> > > > +
> > > > +  +------+
> > > > +  |reader|          RING BUFFER
> > > > +  |page  |
> > > > +  +------+
> > > > +                  +---+   +---+   +---+
> > > > +                  |   |-->|   |-->|   |
> > > > +                  |   |<--|   |<--|   |
> > > > +                  +---+   +---+   +---+
> > > > +                   ^ |             ^ |
> > > > +                   | +-------------+ |
> > > > +                   +-----------------+
> > > > +
> > > > +
> > > > +  +------+
> > > > +  |reader|          RING BUFFER
> > > > +  |page  |-------------------+
> > > > +  +------+                   v
> > > > +    |             +---+   +---+   +---+
> > > > +    |             |   |-->|   |-->|   |
> > > > +    |             |   |<--|   |<--|   |<-+
> > > > +    |             +---+   +---+   +---+  |
> > > > +    |              ^ |             ^ |   |
> > > > +    |              | +-------------+ |   |
> > > > +    |              +-----------------+   |
> > > > +    +------------------------------------+
> > > > +
> > > > +  +------+
> > > > +  |reader|          RING BUFFER
> > > > +  |page  |-------------------+
> > > > +  +------+ <---------------+ v
> > > > +    |  ^          +---+   +---+   +---+
> > > > +    |  |          |   |-->|   |-->|   |
> > > > +    |  |          |   |<--|   |<--|   |<-+
> > > > +    |  |          +---+   +---+   +---+  |
> > > > +    |  |             |             ^ |   |
> > > > +    |  |             +-------------+ |   |
> > > > +    |  +-----------------------------+   |
> > > > +    +------------------------------------+
> > > > +
> > > > +  +------+
> > > > +  |buffer|          RING BUFFER
> > > > +  |page  |-------------------+
> > > > +  +------+ <---------------+ v
> > > > +    |  ^          +---+   +---+   +---+
> > > > +    |  |          |   |   |   |-->|   |
> > > > +    |  |  New     |   |   |   |<--|   |<-+
> > > > +    |  | Reader   +---+   +---+   +---+  |
> > > > +    |  |  page ----^                 |   |
> > > > +    |  |                             |   |
> > > > +    |  +-----------------------------+   |
> > > > +    +------------------------------------+
> > > > +
> > > 
> > > Nice ascii art ;)
> > > 
> > > Some important comments below,
> > 
> > I draw best with plus's and minus's ;-)
> > 
> > > 
> > > > +
> > > > +
> > > > +It is possible that the page swapped is the commit page and the tail page,
> > > > +if what is in the ring buffer is less than what is held in a buffer page.
> > > > +
> > > > +
> > > > +          reader page    commit page   tail page
> > > > +              |              |             |
> > > > +              v              |             |
> > > > +             +---+           |             |
> > > > +             |   |<----------+             |
> > > > +             |   |<------------------------+
> > > > +             |   |------+
> > > > +             +---+      |
> > > > +                        |
> > > > +                        v
> > > > +    +---+    +---+    +---+    +---+
> > > > +<---|   |--->|   |--->|   |--->|   |--->
> > > > +--->|   |<---|   |<---|   |<---|   |<---
> > > > +    +---+    +---+    +---+    +---+
> > > > +
> > > > +This case is still legal for this algorithm.
> > > > +When the writer leaves the page, it simply goes into the ring buffer
> > > > +since the reader page still points to the next location in the ring
> > > > +buffer.
> > > > +
> > > > +
> > > > +The main pointers:
> > > > +
> > > > +  reader page - The page used solely by the reader and is not part
> > > > +                of the ring buffer (may be swapped in)
> > > > +
> > > > +  head page - the next page in the ring buffer that will be swapped
> > > > +              with the reader page.
> > > > +
> > > > +  tail page - the page where the next write will take place.
> > > > +
> > > > +  commit page - the page that last finished a write.
> > > > +
> > > > +The commit page only is updated by the outer most writer in the
> > > > +writer stack. A writer that preempts another writer will not move the
> > > > +commit page.
> > > > +
> > > > +When data is written into the ring buffer, a position is reserved
> > > > +in the ring buffer and passed back to the writer. When the writer
> > > > +is finished writing data into that position, it commits the write.
> > > > +
> > > > +Another write (or a read) may take place at anytime during this
> > > > +transaction. If another write happens it must finish before continuing
> > > > +with the previous write.
> > > > +
> > > > +
> > > > +   Write reserve:
> > > > +
> > > > +       Buffer page
> > > > +      +---------+
> > > > +      |written  |
> > > > +      +---------+  <--- given back to writer (current commit)
> > > > +      |reserved |
> > > > +      +---------+ <--- tail pointer
> > > > +      | empty   |
> > > > +      +---------+
> > > > +
> > > > +   Write commit:
> > > > +
> > > > +       Buffer page
> > > > +      +---------+
> > > > +      |written  |
> > > > +      +---------+
> > > > +      |written  |
> > > > +      +---------+  <--- next positon for write (current commit)
> > > > +      | empty   |
> > > > +      +---------+
> > > > +
> > > > +
> > > > + If a write happens after the first reserve:
> > > > +
> > > > +       Buffer page
> > > > +      +---------+
> > > > +      |written  |
> > > > +      +---------+  <-- current commit
> > > > +      |reserved |
> > > > +      +---------+  <--- given back to second writer
> > > > +      |reserved |
> > > > +      +---------+ <--- tail pointer
> > > > +
> > > > +  After second writer commits:
> > > > +
> > > > +
> > > > +       Buffer page
> > > > +      +---------+
> > > > +      |written  |
> > > > +      +---------+  <--(last full commit)
> > > > +      |reserved |
> > > > +      +---------+
> > > > +      |pending  |
> > > > +      |commit   |
> > > > +      +---------+ <--- tail pointer
> > > > +
> > > > +  When the first writer commits:
> > > > +
> > > > +       Buffer page
> > > > +      +---------+
> > > > +      |written  |
> > > > +      +---------+
> > > > +      |written  |
> > > > +      +---------+
> > > > +      |written  |
> > > > +      +---------+  <--(last full commit and tail pointer)
> > > > +
> > > > +
> > > > +The commit pointer points to the last write location that was
> > > > +committed without preempting another write. When a write that
> > > > +preempted another write is committed, it only becomes a pending commit
> > > > +and will not be a full commit till all writes have been committed.
> > > > +
> > > > +The commit page points to the page that has the last full commit.
> > > > +The tail page points to the page with the last write (before
> > > > +committing).
> > > > +
> > > > +The tail page is always equal to or after the commit page. It may
> > > > +be several pages ahead. If the tail page catches up to the commit
> > > > +page then no more writes may take place (regardless of the mode
> > > > +of the ring buffer: overwrite and produce/consumer).
> > > > +
> > > > +The order of pages are:
> > > > +
> > > > + head page
> > > > + commit page
> > > > + tail page
> > > > +
> > > > +Possible scenario:
> > > > +                             tail page
> > > > +  head page         commit page  |
> > > > +      |                 |        |
> > > > +      v                 v        v
> > > > +    +---+    +---+    +---+    +---+
> > > > +<---|   |--->|   |--->|   |--->|   |--->
> > > > +--->|   |<---|   |<---|   |<---|   |<---
> > > > +    +---+    +---+    +---+    +---+
> > > > +
> > > > +There is a special case that the head page is after either the commit page
> > > > +and possibly the tail page. That is when the commit (and tail) page has been
> > > > +swapped with the reader page. This is because the head page is always
> > > > +part of the ring buffer, but the reader page is not. When ever there
> > > > +has been less than a full page that has been committed inside the ring buffer,
> > > > +and a reader swaps out a page, it will be swapping out the commit page.
> > > > +
> > > > +
> > > > +          reader page    commit page   tail page
> > > > +              |              |             |
> > > > +              v              |             |
> > > > +             +---+           |             |
> > > > +             |   |<----------+             |
> > > > +             |   |<------------------------+
> > > > +             |   |------+
> > > > +             +---+      |
> > > > +                        |
> > > > +                        v
> > > > +    +---+    +---+    +---+    +---+
> > > > +<---|   |--->|   |--->|   |--->|   |--->
> > > > +--->|   |<---|   |<---|   |<---|   |<---
> > > > +    +---+    +---+    +---+    +---+
> > > > +                        ^
> > > > +                        |
> > > > +                    head page
> > > > +
> > > > +
> > > > +In this case, the head page will not move when the tail and commit
> > > > +move back into the ring buffer.
> > > > +
> > > > +The reader can not swap a page into the ring buffer if the commit page
> > > > +is still on that page. If the read meets the last commit (real commit
> > > > +not pending or reserved), then there is nothing more to read.
> > > > +The buffer is considered empty until another full commit finishes.
> > > > +
> > > > +When the tail meets the head page, if the buffer is in overwrite mode,
> > > > +the head page will be pushed ahead one. If the buffer is in producer/consumer
> > > > +mode, the write will fail.
> > > > +
> > > > +Overwrite mode:
> > > > +
> > > > +            tail page
> > > > +               |
> > > > +               v
> > > > +    +---+    +---+    +---+    +---+
> > > > +<---|   |--->|   |--->|   |--->|   |--->
> > > > +--->|   |<---|   |<---|   |<---|   |<---
> > > > +    +---+    +---+    +---+    +---+
> > > > +                        ^
> > > > +                        |
> > > > +                    head page
> > > > +
> > > > +
> > > > +            tail page
> > > > +               |
> > > > +               v
> > > > +    +---+    +---+    +---+    +---+
> > > > +<---|   |--->|   |--->|   |--->|   |--->
> > > > +--->|   |<---|   |<---|   |<---|   |<---
> > > > +    +---+    +---+    +---+    +---+
> > > > +                                 ^
> > > > +                                 |
> > > > +                             head page
> > > > +
> > > > +
> > > > +                    tail page
> > > > +                        |
> > > > +                        v
> > > > +    +---+    +---+    +---+    +---+
> > > > +<---|   |--->|   |--->|   |--->|   |--->
> > > > +--->|   |<---|   |<---|   |<---|   |<---
> > > > +    +---+    +---+    +---+    +---+
> > > > +                                 ^
> > > > +                                 |
> > > > +                             head page
> > > > +
> > > > +Note, the reader page will still point to the previous head page.
> > > > +But when a swap takes place, it will use the most recent head page.
> > > > +
> > > > +
> > > > +Making the Ring Buffer Lockless:
> > > > +--------------------------------
> > > > +
> > > > +The main idea behind the lockless algorithm is to combine the moving
> > > > +of the head_page pointer with the swapping of pages with the reader.
> > > > +State flags are placed inside the pointer to the page. To do this,
> > > > +each page must be aligned in memory by 4 bytes. This will allow the 2
> > > > +least significant bits of the address to be used as flags. Since
> > > > +they will always be zero for the address. To get the address,
> > > > +simply mask out the flags.
> > > > +
> > > > +  MASK = ~3
> > > > +
> > > > +  address & MASK
> > > > +
> > > > +Two flags will be kept by these two bits:
> > > > +
> > > > +   HEADER - the page being pointed to is a head page
> > > > +
> > > > +   UPDATE - the page being pointed to is being updated by a writer
> > > > +          and was or is about to be a head page.
> > > > +
> > > > +
> > > > +          reader page
> > > > +              |
> > > > +              v
> > > > +             +---+
> > > > +             |   |------+
> > > > +             +---+      |
> > > > +                        |
> > > > +                        v
> > > > +    +---+    +---+    +---+    +---+
> > > > +<---|   |--->|   |-H->|   |--->|   |--->
> > > > +--->|   |<---|   |<---|   |<---|   |<---
> > > > +    +---+    +---+    +---+    +---+
> > > > +
> > > > +
> > > > +The above pointer "-H->" would have the HEADER flag set. That is
> > > > +the next page is the next page to be swapped out by the reader.
> > > > +This pointer means the next page is the head page.
> > > > +
> > > > +When the tail page meets the head pointer, it will use cmpxchg to
> > > > +change the pointer to the UPDATE state:
> > > > +
> > > > +
> > > > +            tail page
> > > > +               |
> > > > +               v
> > > > +    +---+    +---+    +---+    +---+
> > > > +<---|   |--->|   |-H->|   |--->|   |--->
> > > > +--->|   |<---|   |<---|   |<---|   |<---
> > > > +    +---+    +---+    +---+    +---+
> > > > +
> > > > +            tail page
> > > > +               |
> > > > +               v
> > > > +    +---+    +---+    +---+    +---+
> > > > +<---|   |--->|   |-U->|   |--->|   |--->
> > > > +--->|   |<---|   |<---|   |<---|   |<---
> > > > +    +---+    +---+    +---+    +---+
> > > > +
> > > > +"-U->" represents a pointer in the UPDATE state.
> > > > +
> > > > +Any access to the reader will need to take some sort of lock to serialize
> > > > +the readers. But the writers will never take a lock to write to the
> > > > +ring buffer. This means we only need to worry about a single reader,
> > > > +and writes only preempt in "stack" formation.
> > > > +
> > > > +When the reader tries to swap the page with the ring buffer, it
> > > > +will also use cmpxchg. If the flag bit in the pointer to the
> > > > +head page does not have the HEADER flag set, the compare will fail
> > > > +and the reader will need to look for the new head page and try again.
> > > > +Note, the flag UPDATE and HEADER are never set at the same time.
> > > > +
> > > > +The reader swaps the reader page as follows:
> > > > +
> > > > +  +------+
> > > > +  |reader|          RING BUFFER
> > > > +  |page  |
> > > > +  +------+
> > > > +                  +---+    +---+    +---+
> > > > +                  |   |--->|   |--->|   |
> > > > +                  |   |<---|   |<---|   |
> > > > +                  +---+    +---+    +---+
> > > > +                   ^ |               ^ |
> > > > +                   | +---------------+ |
> > > > +                   +-----H-------------+
> > > > +
> > > > +The reader sets the reader page next pointer as HEADER to the page after
> > > > +the head page.
> > > > +
> > > > +
> > > > +  +------+
> > > > +  |reader|          RING BUFFER
> > > > +  |page  |-------H-----------+
> > > > +  +------+                   v
> > > > +    |             +---+    +---+    +---+
> > > > +    |             |   |--->|   |--->|   |
> > > > +    |             |   |<---|   |<---|   |<-+
> > > > +    |             +---+    +---+    +---+  |
> > > > +    |              ^ |               ^ |   |
> > > > +    |              | +---------------+ |   |
> > > > +    |              +-----H-------------+   |
> > > > +    +--------------------------------------+
> > > > +
> > > > +It does a cmpxchg with the pointer to the previous head page to make it
> > > > +point to the reader page. Note that the new pointer does not have the HEADER
> > > > +flag set.  This action atomically moves the head page forward.
> > > > +
> > > > +  +------+
> > > > +  |reader|          RING BUFFER
> > > > +  |page  |-------H-----------+
> > > > +  +------+ <---------------+ v
> > > > +    |  ^          +---+   +---+   +---+
> > > > +    |  |          |   |-->|   |-->|   |
> > > > +    |  |          |   |<--|   |<--|   |<-+
> > > > +    |  |          +---+   +---+   +---+  |
> > > > +    |  |             |             ^ |   |
> > > > +    |  |             +-------------+ |   |
> > > > +    |  +-----------------------------+   |
> > > > +    +------------------------------------+
> > > > +
> > > > +After the new head page is set, the previous pointer of the head page is
> > > > +updated to the reader page.
> > > > +
> > > > +  +------+
> > > > +  |reader|          RING BUFFER
> > > > +  |page  |-------H-----------+
> > > > +  +------+                   v
> > > > +    |  ^          +---+   +---+   +---+
> > > > +    |  |          |   |-->|   |-->|   |
> > > > +    |  |          |   |<--|   |<--|   |<-+
> > > > +    |  |          +---+   +---+   +---+  |
> > > > +    |  |             |             ^ |   |
> > > > +    |  |             +-------------+ |   |
> > > > +    |  +-----------------------------+   |
> > > > +    +------------------------------------+
> > > > +
> > > > +  +------+
> > > > +  |buffer|          RING BUFFER
> > > > +  |page  |-------H-----------+  <--- New head page
> > > > +  +------+ <---------------+ v
> > > > +    |  ^          +---+   +---+   +---+
> > > > +    |  |          |   |   |   |-->|   |
> > > > +    |  |  New     |   |   |   |<--|   |<-+
> > > > +    |  | Reader   +---+   +---+   +---+  |
> > > > +    |  |  page ----^                 |   |
> > > > +    |  |                             |   |
> > > > +    |  +-----------------------------+   |
> > > > +    +------------------------------------+
> > > > +
> > > > +Another important point. The page that the reader page points back to
> > > > +by its previous pointer (the one that now points to the new head page)
> > > > +never points back to the reader page. That is because the reader page is
> > > > +not part of the ring buffer. Traversing the ring buffer via the next pointers
> > > > +will always stay in the ring buffer. Traversing the ring buffer via the
> > > > +prev pointers may not.
> > > > +
> > > > +Note, the way to determine a reader page is simply by examining the previous
> > > > +pointer of the page. If the next pointer of the previous page does not
> > > > +point back to the original page, then the original page is a reader page:
> > > > +
> > > > +                                  
> > > > +             +--------+
> > > > +             | reader |  next   +----+
> > > > +             |  page  |-------->|    |<====== (buffer page)
> > > > +             +--------+         +----+
> > > > +                 |                | ^
> > > > +                 |                v | next
> > > > +            prev |              +----+
> > > > +                 +------------->|    |
> > > > +                                +----+
> > > > +
> > > > +The way the head page moves forward:
> > > > +
> > > > +When the tail page meets the head page and the buffer is in overwrite mode
> > > > +and more writes take place, the head page must be moved forward before the
> > > > +writer may move the tail page. The way this is done is that the writer
> > > > +performs a cmpxchg to convert the pointer to the head page from the HEADER
> > > > +flag to have the UPDATE flag set. Once this is done, the reader will
> > > > +not be able to swap the head page from the buffer, nor will it be able to
> > > > +move the head page, until the writer is finished with the move.
> > > > +
> > > > +This eliminates any races that the reader can have on the writer. The reader
> > > > +must spin, and this is why the reader can not preempt the writer.
> > > > +
> > > > +            tail page
> > > > +               |
> > > > +               v
> > > > +    +---+    +---+    +---+    +---+
> > > > +<---|   |--->|   |-H->|   |--->|   |--->
> > > > +--->|   |<---|   |<---|   |<---|   |<---
> > > > +    +---+    +---+    +---+    +---+
> > > > +
> > > > +            tail page
> > > > +               |
> > > > +               v
> > > > +    +---+    +---+    +---+    +---+
> > > > +<---|   |--->|   |-U->|   |--->|   |--->
> > > > +--->|   |<---|   |<---|   |<---|   |<---
> > > > +    +---+    +---+    +---+    +---+
> > > > +
> > > > +The following page will be made into the new head page.
> > > > +
> > > > +           tail page
> > > > +               |
> > > > +               v
> > > > +    +---+    +---+    +---+    +---+
> > > > +<---|   |--->|   |-U->|   |-H->|   |--->
> > > > +--->|   |<---|   |<---|   |<---|   |<---
> > > > +    +---+    +---+    +---+    +---+
> > > > +
> > > > +After the new head page has been set, we can set the old head page
> > > > +pointer back to NORMAL.
> > > > +
> > > > +           tail page
> > > > +               |
> > > > +               v
> > > > +    +---+    +---+    +---+    +---+
> > > > +<---|   |--->|   |--->|   |-H->|   |--->
> > > > +--->|   |<---|   |<---|   |<---|   |<---
> > > > +    +---+    +---+    +---+    +---+
> > > > +
> > > > +After the head page has been moved, the tail page may now move forward.
> > > > +
> > > > +                    tail page
> > > > +                        |
> > > > +                        v
> > > > +    +---+    +---+    +---+    +---+
> > > > +<---|   |--->|   |--->|   |-H->|   |--->
> > > > +--->|   |<---|   |<---|   |<---|   |<---
> > > > +    +---+    +---+    +---+    +---+
> > > > +
> > > > +
> > > > +The above are the trivial updates. Now for the more complex scenarios.
> > > > +
> > > > +
> > > > +As stated before, if enough writes preempt the first write, the
> > > > +tail page may make it all the way around the buffer and meet the commit
> > > > +page. At this time, we must start dropping writes (usually with some kind
> > > > +of warning to the user). But what happens if the commit was still on the
> > > > +reader page? The commit page is not part of the ring buffer. The tail page
> > > > +must account for this.
> > > > +
> > > > +
> > > > +          reader page    commit page
> > > > +              |              |
> > > > +              v              |
> > > > +             +---+           |
> > > > +             |   |<----------+
> > > > +             |   |
> > > > +             |   |------+
> > > > +             +---+      |
> > > > +                        |
> > > > +                        v
> > > > +    +---+    +---+    +---+    +---+
> > > > +<---|   |--->|   |-H->|   |--->|   |--->
> > > > +--->|   |<---|   |<---|   |<---|   |<---
> > > > +    +---+    +---+    +---+    +---+
> > > > +               ^
> > > > +               |
> > > > +           tail page
> > > > +
> > > > +If the tail page were to simply push the head page forward, the commit when
> > > > +leaving the reader page would not be pointing to the correct page.
> > > > +
> > > > +The solution to this is to test if the commit page is on the reader page
> > > > +before pushing the head page. If it is, then it can be assumed that the
> > > > +tail page wrapped the buffer, and we must drop new writes.
> > > > +
> > > > +This is not a race condition, because the commit page can only be moved
> > > > +by the outter most writer (the writer that was preempted).
> > > > +This means that the commit will not move while a writer is moving the
> > > > +tail page. The reader can not swap the reader page if it is also being
> > > > +used as the commit page. The reader can simply check that the commit
> > > > +is off the reader page. Once the commit page leaves the reader page
> > > > +it will never go back on it unless a reader does another swap with the
> > > > +buffer page that is also the commit page.
> > > > +
> > > > +
> > > > +Nested writes
> > > > +-------------
> > > > +
> > > > +In the pushing forward of the tail page we must first push forward
> > > > +the head page if the head page is the next page. If the head page
> > > > +is not the next page, the tail page is simply updated with a cmpxchg.
> > > > +
> > > > +Only writers move the tail page. This must be done atomically to protect
> > > > +against nested writers.
> > > > +
> > > > +  temp_page = tail_page
> > > > +  next_page = temp_page->next
> > > > +  cmpxchg(tail_page, temp_page, next_page)
> > > > +
> > > 
> > > OK, I'll bite :
> > > 
> > > What happens if :
> > > 
> > > - a writer is at the end of a page, 
> > > - needs to push the tail_page pointer
> > > - reads tail_page
> > >   - interrupted.
> > >   - nested writers come, successfully updates the tail_page, write
> > >     enough data to fill the whole buffer
> > >   - concurrently (on another CPU), a reader is consuming all the data
> > >   - This brings the tail_page pointer back to its original value
> > >   - iret
> > > - here, the writer will successfully perform the tail_page cmpxchg,
> > >   because the value match. However, the page currently being written to
> > >   could be only partially reserved; the writer will not re-check if the
> > >   page is really full.
> > > 
> > > That's actually one of my main concerns with an approach where two
> > > separate "pointers" are used to keep track of reserved space within a
> > > buffer.
> > 
> > Actually, the two pointers is exactly what prevents the above scenario.
> > 
> > We have a commit page pointer and a commit index pointer. The commit page
> > points to the page that holds the last true commit. A read can never go 
> > pass the commit. That is, it can not read reserved but uncommited data.
> > 
> 
> OK, I see how the commit counter can ensure the reader will not read
> reserved-by-yet-uncommitted data.
> 
> 
> > Another key point is that if the tail page meets the commit page, it will 
> > not move it and drop the data. If your buffer is not big enough to hold 
> > all data in a interrupt, then your buffer is too small. We count these in 
> > the "commit_overrun" counter as well as return NULL on the reserve so the 
> > tracer will know that it had its data dropped.
> > 
> 
> Ah ok, so the following writer-only scenario :
> 
> - a writer is at the end of a page, 
> - needs to push the tail_page pointer
> - reads tail_page
>   - interrupted.
>   - nested writers come, successfully updates the tail_page, write
>     enough data to fill the whole buffer
>   - Brings the tail_page pointer back to its original value <----------
> 
> Cannot happen, because it would meet the commit page.
> 
> That's a bit weird to drop events in overwrite mode. Normally, one would
> expect that mode to just permit to write any amount of events, from any
> execution context, be it nested or not, overwriting the oldest events.
> 

Hrm, about this specific point, now that I think about it again, LTTng
does something similar if nested writes happen to cause a buffer wrap
around and meet a non fully committed subbuffer. It will also drop
events in overwrite mode.

Mathieu


> > 
> > > 
> > > The same concern applies to moving the head page when concurrent writers
> > > are nesting.
> > > 
> > > More generally, I'm also concerned about the lack of memory barriers
> > > around some non-cmpxchg tail/head page set operations in your code, and
> > > the lack of proper rcu_dereference-style primitive for list iteration.
> > 
> > The cmpxchg is a memory barrier. Writes only contend with other writes on 
> > the same CPU. When we update the pointer from HEAD to UPDATE a reader will
> > not pass that point. The update is done via cmpxchg and thus is a memory 
> > barrier. Now if cmpxchg is not a memory barrier, then I need to add 
> > smp_mb() by all of them.
> > 
> 
> Documentation/memory-barriers.txt states that cmpxchg must behave as if
> it had smp_mb() before and after.
> 
> > > 
> > > For those I've added to CC, I'm referring to the patch at :
> > > 
> > > http://patchwork.kernel.org/patch/29395/
> > > 
> > > The great news to me is that no one can say LTTng's lockless buffering
> > > algorithm is complex compared to this. ;)
> > 
> > But can you read without worries about writers? The nice thing about this 
> > approach, which a lot of ftrace depends on, is that I don't need call 
> > backs or copies to check if what I read from the buffer was not stomped 
> > on by a writer. There is a zero copy overhead for readers (when the buffer 
> > is more than a page filled) and when a reader has its data, it belongs to 
> > that reader.
> > 
> 
> Hrm, now that you bring this question on the table again (I remember we
> discussed about it at the collaboration summit), and now that there is
> no alcohol involved, I see a way to do it. Here is the idea :
> 
> I assume you remember a bit how the global per-buffer write_offset and
> read_offset counters work in LTTng : writer head and reader head are
> positions in what we can think of as a virtually contiguous buffer
> address space for the whole buffer.
> 
> First, let's talk in terms of get_subbuf() (reader get a subbuffer
> exclusive access for reading) and put_subbuf() (reader releases its
> exclusive subbuffer access). get_subbuf() returns the current
> read_offset, and put_subbuf() takes this read_offset (the one returned
> by get_subbuf()), as parameter.
> 
> Let's say that we let get_subbuf() use cmpxchg to write a flag in the
> read_offset counter to tell the writer it's actively reading, e.g.
> OFFSET_READING_FLAG = 0x1. It's reading the read_offset at the same
> time because the update is done with a cmpxchg.
> 
> Now for the writer : in overwrite mode, if the write_offset comes to a
> point where it would have to push the reader position (read offset) in
> order to be able to reserve space *and* the reader is actively reading
> data from the buffer (we know it because OFFSET_READING_FLAG is set),
> the writer could set a flag in the read_offset LSBs
> (OFFSET_PUSH_FLAG = 0x2). The writer would simply skip over this
> specific subbuffer, and that's it : it can continue to write in the
> buffer after the subbuffer owned by the reader without problem. If it
> loops a few times over the buffer while the reader is still stucked
> there (think of a slow serial port), it would simply skip over the
> subbuffer owned by the reader.
> 
> Now, when the reader eventually releases its current subbuffer
> (put_subbuf()), it would detect that the read_offset is different than
> the one returned by get_subbuf() because the OFFSET_PUSH_FLAG would have
> been set. This will inform the reader that it must push its own
> read_offset position to the subbuffer following the current
> write_offset position. That's it, we're back on track : the next reader
> will read the oldest available subbuffer.
> 
> I took special care in the design above to make sure the case where
> tracing starts still works. In this case, where the buffer is only
> partially filled, the reader head is not in the subbuffer following the
> writer head, because it points to uninitialized data. But the
> OFFSET_PUSH_FLAG can only ever be set when a writer has at least
> completely filled the buffer once (and meets the read_offset), so we can
> consider that it's safe for put_subbuf() to move right after the write
> offset subbuffer.
> 
> I must admit that the flag idea is a bit inspired from your lockless
> algo I am currently reviewing. :)
> 
> Does it make sense ?
> 
> Mathieu
> 
> Note : I won't be available for implementation work before July 6th...
> got a thesis to write...
> 
> 
> > -- Steve
> > 
> 
> -- 
> Mathieu Desnoyers
> OpenPGP key fingerprint: 8CD5 52C3 8E3C 4140 715F  BA06 3F25 A8FE 3BAE 9A68

-- 
Mathieu Desnoyers
OpenPGP key fingerprint: 8CD5 52C3 8E3C 4140 715F  BA06 3F25 A8FE 3BAE 9A68

^ permalink raw reply	[flat|nested] 29+ messages in thread

* Re: [PATCH 3/3] ring-buffer: add design document
  2009-06-11  3:59         ` Mathieu Desnoyers
@ 2009-06-11  4:15           ` Steven Rostedt
  2009-06-11 18:09             ` Mathieu Desnoyers
  0 siblings, 1 reply; 29+ messages in thread
From: Steven Rostedt @ 2009-06-11  4:15 UTC (permalink / raw)
  To: Mathieu Desnoyers
  Cc: linux-kernel, Ingo Molnar, Andrew Morton, Thomas Gleixner,
	Peter Zijlstra, Frederic Weisbecker, Theodore Tso,
	Arnaldo Carvalho de Melo, Lai Jiangshan, Martin J. Bligh,
	Christoph Hellwig, Li Zefan, Huang Ying, H. Peter Anvin,
	Hidetoshi Seto, Masami Hiramatsu, ltt-dev, Robert Wisniewski,
	Paul E. McKenney


On Wed, 10 Jun 2009, Mathieu Desnoyers wrote:

> * Mathieu Desnoyers (compudj@krystal.dyndns.org) wrote:
> > * Steven Rostedt (rostedt@goodmis.org) wrote:
> > > 
> > > On Wed, 10 Jun 2009, Mathieu Desnoyers wrote:
> > > > * Steven Rostedt (rostedt@goodmis.org) wrote:
> > > > > +The Generic Ring Buffer
> > > > > +-----------------------
> > > > > +
> > > > > +The ring buffer can be used in either an overwrite mode or in
> > > > > +producer/consumer mode.
> > > > > +
> > > > > +Producer/consumer mode is where the producer were to fill up the
> > > > > +buffer before the consumer could free up anything, the producer
> > > > > +will stop writing to the buffer. This will lose most recent events.
> > > > > +
> > > > > +Overwrite mode is where the produce were to fill up the buffer
> > > > > +before the consumer could free up anything, the producer will
> > > > > +overwrite the older data. This will lose the oldest events.
> > > > > +
> > > > > +No two writers can write at the same time (on the same per cpu buffer),
> > > > > +but a writer may preempt another writer, but it must finish writing
> > > > 
> > > > Hi Steven,
> > > > 
> > > > I would use "interrupt" instead of "preempt" here, given that preemption
> > > > implies scheduler activity which is specifically forbidden here.
> > > 
> > > Good point, I'll update it.
> > > 
> > 
> > Please also look thorough the code... at some places you seem to imply
> > that the reader "must" be on a remote CPU, when you actually mean
> > "could" be on a remote or local cpu.

Yeah, I'll fix up the comments to prevent confusion.

> > > > > +Nested writes
> > > > > +-------------
> > > > > +
> > > > > +In the pushing forward of the tail page we must first push forward
> > > > > +the head page if the head page is the next page. If the head page
> > > > > +is not the next page, the tail page is simply updated with a cmpxchg.
> > > > > +
> > > > > +Only writers move the tail page. This must be done atomically to protect
> > > > > +against nested writers.
> > > > > +
> > > > > +  temp_page = tail_page
> > > > > +  next_page = temp_page->next
> > > > > +  cmpxchg(tail_page, temp_page, next_page)
> > > > > +
> > > > 
> > > > OK, I'll bite :
> > > > 
> > > > What happens if :
> > > > 
> > > > - a writer is at the end of a page, 
> > > > - needs to push the tail_page pointer
> > > > - reads tail_page
> > > >   - interrupted.
> > > >   - nested writers come, successfully updates the tail_page, write
> > > >     enough data to fill the whole buffer
> > > >   - concurrently (on another CPU), a reader is consuming all the data
> > > >   - This brings the tail_page pointer back to its original value
> > > >   - iret
> > > > - here, the writer will successfully perform the tail_page cmpxchg,
> > > >   because the value match. However, the page currently being written to
> > > >   could be only partially reserved; the writer will not re-check if the
> > > >   page is really full.
> > > > 
> > > > That's actually one of my main concerns with an approach where two
> > > > separate "pointers" are used to keep track of reserved space within a
> > > > buffer.
> > > 
> > > Actually, the two pointers is exactly what prevents the above scenario.
> > > 
> > > We have a commit page pointer and a commit index pointer. The commit page
> > > points to the page that holds the last true commit. A read can never go 
> > > pass the commit. That is, it can not read reserved but uncommited data.
> > > 
> > 
> > OK, I see how the commit counter can ensure the reader will not read
> > reserved-by-yet-uncommitted data.
> > 
> > 
> > > Another key point is that if the tail page meets the commit page, it will 
> > > not move it and drop the data. If your buffer is not big enough to hold 
> > > all data in a interrupt, then your buffer is too small. We count these in 
> > > the "commit_overrun" counter as well as return NULL on the reserve so the 
> > > tracer will know that it had its data dropped.
> > > 
> > 
> > Ah ok, so the following writer-only scenario :
> > 
> > - a writer is at the end of a page, 
> > - needs to push the tail_page pointer
> > - reads tail_page
> >   - interrupted.
> >   - nested writers come, successfully updates the tail_page, write
> >     enough data to fill the whole buffer
> >   - Brings the tail_page pointer back to its original value <----------
> > 
> > Cannot happen, because it would meet the commit page.
> > 
> > That's a bit weird to drop events in overwrite mode. Normally, one would
> > expect that mode to just permit to write any amount of events, from any
> > execution context, be it nested or not, overwriting the oldest events.
> > 
> 
> Hrm, about this specific point, now that I think about it again, LTTng
> does something similar if nested writes happen to cause a buffer wrap
> around and meet a non fully committed subbuffer. It will also drop
> events in overwrite mode.
> 

Yeah, and it really should never happen. In my original code I would do a 
WARN_ON when it did. But I could easily trigger it if I make a two page
buffer. Which is the default on bootup, until something actually enables 
ftrace. But the ftrace self tests would use that two page buffer, and it 
would sometimes cause the warnings.

> > > 
> > > > 
> > > > The same concern applies to moving the head page when concurrent writers
> > > > are nesting.
> > > > 
> > > > More generally, I'm also concerned about the lack of memory barriers
> > > > around some non-cmpxchg tail/head page set operations in your code, and
> > > > the lack of proper rcu_dereference-style primitive for list iteration.
> > > 
> > > The cmpxchg is a memory barrier. Writes only contend with other writes on 
> > > the same CPU. When we update the pointer from HEAD to UPDATE a reader will
> > > not pass that point. The update is done via cmpxchg and thus is a memory 
> > > barrier. Now if cmpxchg is not a memory barrier, then I need to add 
> > > smp_mb() by all of them.
> > > 
> > 
> > Documentation/memory-barriers.txt states that cmpxchg must behave as if
> > it had smp_mb() before and after.
> > 
> > > > 
> > > > For those I've added to CC, I'm referring to the patch at :
> > > > 
> > > > http://patchwork.kernel.org/patch/29395/
> > > > 
> > > > The great news to me is that no one can say LTTng's lockless buffering
> > > > algorithm is complex compared to this. ;)
> > > 
> > > But can you read without worries about writers? The nice thing about this 
> > > approach, which a lot of ftrace depends on, is that I don't need call 
> > > backs or copies to check if what I read from the buffer was not stomped 
> > > on by a writer. There is a zero copy overhead for readers (when the buffer 
> > > is more than a page filled) and when a reader has its data, it belongs to 
> > > that reader.
> > > 
> > 
> > Hrm, now that you bring this question on the table again (I remember we
> > discussed about it at the collaboration summit), and now that there is
> > no alcohol involved, I see a way to do it. Here is the idea :

There may not be alcohol on your end, but speak for yourself ;-)

I'll look more at what you say here tomorrow.

-- Steve

> > 
> > I assume you remember a bit how the global per-buffer write_offset and
> > read_offset counters work in LTTng : writer head and reader head are
> > positions in what we can think of as a virtually contiguous buffer
> > address space for the whole buffer.
> > 
> > First, let's talk in terms of get_subbuf() (reader get a subbuffer
> > exclusive access for reading) and put_subbuf() (reader releases its
> > exclusive subbuffer access). get_subbuf() returns the current
> > read_offset, and put_subbuf() takes this read_offset (the one returned
> > by get_subbuf()), as parameter.
> > 
> > Let's say that we let get_subbuf() use cmpxchg to write a flag in the
> > read_offset counter to tell the writer it's actively reading, e.g.
> > OFFSET_READING_FLAG = 0x1. It's reading the read_offset at the same
> > time because the update is done with a cmpxchg.
> > 
> > Now for the writer : in overwrite mode, if the write_offset comes to a
> > point where it would have to push the reader position (read offset) in
> > order to be able to reserve space *and* the reader is actively reading
> > data from the buffer (we know it because OFFSET_READING_FLAG is set),
> > the writer could set a flag in the read_offset LSBs
> > (OFFSET_PUSH_FLAG = 0x2). The writer would simply skip over this
> > specific subbuffer, and that's it : it can continue to write in the
> > buffer after the subbuffer owned by the reader without problem. If it
> > loops a few times over the buffer while the reader is still stucked
> > there (think of a slow serial port), it would simply skip over the
> > subbuffer owned by the reader.
> > 
> > Now, when the reader eventually releases its current subbuffer
> > (put_subbuf()), it would detect that the read_offset is different than
> > the one returned by get_subbuf() because the OFFSET_PUSH_FLAG would have
> > been set. This will inform the reader that it must push its own
> > read_offset position to the subbuffer following the current
> > write_offset position. That's it, we're back on track : the next reader
> > will read the oldest available subbuffer.
> > 
> > I took special care in the design above to make sure the case where
> > tracing starts still works. In this case, where the buffer is only
> > partially filled, the reader head is not in the subbuffer following the
> > writer head, because it points to uninitialized data. But the
> > OFFSET_PUSH_FLAG can only ever be set when a writer has at least
> > completely filled the buffer once (and meets the read_offset), so we can
> > consider that it's safe for put_subbuf() to move right after the write
> > offset subbuffer.
> > 
> > I must admit that the flag idea is a bit inspired from your lockless
> > algo I am currently reviewing. :)
> > 
> > Does it make sense ?
> > 
> > Mathieu
> > 
> > Note : I won't be available for implementation work before July 6th...
> > got a thesis to write...
> > 
> > 
> > > -- Steve
> > > 
> > 
> > -- 
> > Mathieu Desnoyers
> > OpenPGP key fingerprint: 8CD5 52C3 8E3C 4140 715F  BA06 3F25 A8FE 3BAE 9A68
> 
> -- 
> Mathieu Desnoyers
> OpenPGP key fingerprint: 8CD5 52C3 8E3C 4140 715F  BA06 3F25 A8FE 3BAE 9A68
> 

^ permalink raw reply	[flat|nested] 29+ messages in thread

* Re: [PATCH 3/3] ring-buffer: add design document
  2009-06-11  4:15           ` Steven Rostedt
@ 2009-06-11 18:09             ` Mathieu Desnoyers
  0 siblings, 0 replies; 29+ messages in thread
From: Mathieu Desnoyers @ 2009-06-11 18:09 UTC (permalink / raw)
  To: Steven Rostedt
  Cc: linux-kernel, Ingo Molnar, Andrew Morton, Thomas Gleixner,
	Peter Zijlstra, Frederic Weisbecker, Theodore Tso,
	Arnaldo Carvalho de Melo, Lai Jiangshan, Martin J. Bligh,
	Christoph Hellwig, Li Zefan, Huang Ying, H. Peter Anvin,
	Hidetoshi Seto, Masami Hiramatsu, ltt-dev, Robert Wisniewski,
	Paul E. McKenney

* Steven Rostedt (rostedt@goodmis.org) wrote:
> 
> On Wed, 10 Jun 2009, Mathieu Desnoyers wrote:
> 
> > * Mathieu Desnoyers (compudj@krystal.dyndns.org) wrote:
> > > * Steven Rostedt (rostedt@goodmis.org) wrote:
> > > > 
> > > > On Wed, 10 Jun 2009, Mathieu Desnoyers wrote:
> > > > > * Steven Rostedt (rostedt@goodmis.org) wrote:
> > > > > > +The Generic Ring Buffer
> > > > > > +-----------------------
> > > > > > +
> > > > > > +The ring buffer can be used in either an overwrite mode or in
> > > > > > +producer/consumer mode.
> > > > > > +
> > > > > > +Producer/consumer mode is where the producer were to fill up the
> > > > > > +buffer before the consumer could free up anything, the producer
> > > > > > +will stop writing to the buffer. This will lose most recent events.
> > > > > > +
> > > > > > +Overwrite mode is where the produce were to fill up the buffer
> > > > > > +before the consumer could free up anything, the producer will
> > > > > > +overwrite the older data. This will lose the oldest events.
> > > > > > +
> > > > > > +No two writers can write at the same time (on the same per cpu buffer),
> > > > > > +but a writer may preempt another writer, but it must finish writing
> > > > > 
> > > > > Hi Steven,
> > > > > 
> > > > > I would use "interrupt" instead of "preempt" here, given that preemption
> > > > > implies scheduler activity which is specifically forbidden here.
> > > > 
> > > > Good point, I'll update it.
> > > > 
> > > 
> > > Please also look thorough the code... at some places you seem to imply
> > > that the reader "must" be on a remote CPU, when you actually mean
> > > "could" be on a remote or local cpu.
> 
> Yeah, I'll fix up the comments to prevent confusion.
> 
> > > > > > +Nested writes
> > > > > > +-------------
> > > > > > +
> > > > > > +In the pushing forward of the tail page we must first push forward
> > > > > > +the head page if the head page is the next page. If the head page
> > > > > > +is not the next page, the tail page is simply updated with a cmpxchg.
> > > > > > +
> > > > > > +Only writers move the tail page. This must be done atomically to protect
> > > > > > +against nested writers.
> > > > > > +
> > > > > > +  temp_page = tail_page
> > > > > > +  next_page = temp_page->next
> > > > > > +  cmpxchg(tail_page, temp_page, next_page)
> > > > > > +
> > > > > 
> > > > > OK, I'll bite :
> > > > > 
> > > > > What happens if :
> > > > > 
> > > > > - a writer is at the end of a page, 
> > > > > - needs to push the tail_page pointer
> > > > > - reads tail_page
> > > > >   - interrupted.
> > > > >   - nested writers come, successfully updates the tail_page, write
> > > > >     enough data to fill the whole buffer
> > > > >   - concurrently (on another CPU), a reader is consuming all the data
> > > > >   - This brings the tail_page pointer back to its original value
> > > > >   - iret
> > > > > - here, the writer will successfully perform the tail_page cmpxchg,
> > > > >   because the value match. However, the page currently being written to
> > > > >   could be only partially reserved; the writer will not re-check if the
> > > > >   page is really full.
> > > > > 
> > > > > That's actually one of my main concerns with an approach where two
> > > > > separate "pointers" are used to keep track of reserved space within a
> > > > > buffer.
> > > > 
> > > > Actually, the two pointers is exactly what prevents the above scenario.
> > > > 
> > > > We have a commit page pointer and a commit index pointer. The commit page
> > > > points to the page that holds the last true commit. A read can never go 
> > > > pass the commit. That is, it can not read reserved but uncommited data.
> > > > 
> > > 
> > > OK, I see how the commit counter can ensure the reader will not read
> > > reserved-by-yet-uncommitted data.
> > > 
> > > 
> > > > Another key point is that if the tail page meets the commit page, it will 
> > > > not move it and drop the data. If your buffer is not big enough to hold 
> > > > all data in a interrupt, then your buffer is too small. We count these in 
> > > > the "commit_overrun" counter as well as return NULL on the reserve so the 
> > > > tracer will know that it had its data dropped.
> > > > 
> > > 
> > > Ah ok, so the following writer-only scenario :
> > > 
> > > - a writer is at the end of a page, 
> > > - needs to push the tail_page pointer
> > > - reads tail_page
> > >   - interrupted.
> > >   - nested writers come, successfully updates the tail_page, write
> > >     enough data to fill the whole buffer
> > >   - Brings the tail_page pointer back to its original value <----------
> > > 
> > > Cannot happen, because it would meet the commit page.
> > > 
> > > That's a bit weird to drop events in overwrite mode. Normally, one would
> > > expect that mode to just permit to write any amount of events, from any
> > > execution context, be it nested or not, overwriting the oldest events.
> > > 
> > 
> > Hrm, about this specific point, now that I think about it again, LTTng
> > does something similar if nested writes happen to cause a buffer wrap
> > around and meet a non fully committed subbuffer. It will also drop
> > events in overwrite mode.
> > 
> 
> Yeah, and it really should never happen. In my original code I would do a 
> WARN_ON when it did. But I could easily trigger it if I make a two page
> buffer. Which is the default on bootup, until something actually enables 
> ftrace. But the ftrace self tests would use that two page buffer, and it 
> would sometimes cause the warnings.
> 
> > > > 
> > > > > 
> > > > > The same concern applies to moving the head page when concurrent writers
> > > > > are nesting.
> > > > > 
> > > > > More generally, I'm also concerned about the lack of memory barriers
> > > > > around some non-cmpxchg tail/head page set operations in your code, and
> > > > > the lack of proper rcu_dereference-style primitive for list iteration.
> > > > 
> > > > The cmpxchg is a memory barrier. Writes only contend with other writes on 
> > > > the same CPU. When we update the pointer from HEAD to UPDATE a reader will
> > > > not pass that point. The update is done via cmpxchg and thus is a memory 
> > > > barrier. Now if cmpxchg is not a memory barrier, then I need to add 
> > > > smp_mb() by all of them.
> > > > 
> > > 
> > > Documentation/memory-barriers.txt states that cmpxchg must behave as if
> > > it had smp_mb() before and after.
> > > 
> > > > > 
> > > > > For those I've added to CC, I'm referring to the patch at :
> > > > > 
> > > > > http://patchwork.kernel.org/patch/29395/
> > > > > 
> > > > > The great news to me is that no one can say LTTng's lockless buffering
> > > > > algorithm is complex compared to this. ;)
> > > > 
> > > > But can you read without worries about writers? The nice thing about this 
> > > > approach, which a lot of ftrace depends on, is that I don't need call 
> > > > backs or copies to check if what I read from the buffer was not stomped 
> > > > on by a writer. There is a zero copy overhead for readers (when the buffer 
> > > > is more than a page filled) and when a reader has its data, it belongs to 
> > > > that reader.
> > > > 
> > > 
> > > Hrm, now that you bring this question on the table again (I remember we
> > > discussed about it at the collaboration summit), and now that there is
> > > no alcohol involved, I see a way to do it. Here is the idea :
> 
> There may not be alcohol on your end, but speak for yourself ;-)
> 
> I'll look more at what you say here tomorrow.
> 

I agree that, for overwrite mode, having the ability to let the reader
"privatise" its current subbuffer is a very nice thing, especially if
you are doing some live computation on this buffer. For the
post-processing approach LTTng is taking, it does not matter as much
though, given we can detect the subbuffer corruption when doing the
put_subbuf() operation and just trim the output data. However, this
involves a copy (either to disk, to the network or to a separate memory
location) before the data can be considered as consistent in overwrite
mode.

Actually, one much simpler alternative for live buffer read-side
processing in LTTng would be to check the read_offset value after each
event header read and event payload read. This would confirm that the
data is not corrupted. It would be trivial to do, and the copy involved
would only imply sending the event data into the local CPU L1-cache or
registers (very close to zero copy cost). This would imply an added read
memory barrier after each data read, which should not be very costly
neither. This would permit to keep low complexity on the write-side.

Mathieu

P.S.:
There are two elements that would still need to be addressed in the
design presented in my previous mail :

- A first one, simple, involves the fact that the reader should test and
  clear a per-subbuffer flag before reading. The writer should set this
  flag when it produces data into a buffer, so the reader would not
  re-read the subbuffer skipped by the writer until it's populated.
- Taking care of synchronization concerns regarding read_offset and
  write_offset.

So until I have time to spend on this issue (especially the second one),
I'll leave it on the ice (and go back to my thesis). :-)


> -- Steve
> 
> > > 
> > > I assume you remember a bit how the global per-buffer write_offset and
> > > read_offset counters work in LTTng : writer head and reader head are
> > > positions in what we can think of as a virtually contiguous buffer
> > > address space for the whole buffer.
> > > 
> > > First, let's talk in terms of get_subbuf() (reader get a subbuffer
> > > exclusive access for reading) and put_subbuf() (reader releases its
> > > exclusive subbuffer access). get_subbuf() returns the current
> > > read_offset, and put_subbuf() takes this read_offset (the one returned
> > > by get_subbuf()), as parameter.
> > > 
> > > Let's say that we let get_subbuf() use cmpxchg to write a flag in the
> > > read_offset counter to tell the writer it's actively reading, e.g.
> > > OFFSET_READING_FLAG = 0x1. It's reading the read_offset at the same
> > > time because the update is done with a cmpxchg.
> > > 
> > > Now for the writer : in overwrite mode, if the write_offset comes to a
> > > point where it would have to push the reader position (read offset) in
> > > order to be able to reserve space *and* the reader is actively reading
> > > data from the buffer (we know it because OFFSET_READING_FLAG is set),
> > > the writer could set a flag in the read_offset LSBs
> > > (OFFSET_PUSH_FLAG = 0x2). The writer would simply skip over this
> > > specific subbuffer, and that's it : it can continue to write in the
> > > buffer after the subbuffer owned by the reader without problem. If it
> > > loops a few times over the buffer while the reader is still stucked
> > > there (think of a slow serial port), it would simply skip over the
> > > subbuffer owned by the reader.
> > > 
> > > Now, when the reader eventually releases its current subbuffer
> > > (put_subbuf()), it would detect that the read_offset is different than
> > > the one returned by get_subbuf() because the OFFSET_PUSH_FLAG would have
> > > been set. This will inform the reader that it must push its own
> > > read_offset position to the subbuffer following the current
> > > write_offset position. That's it, we're back on track : the next reader
> > > will read the oldest available subbuffer.
> > > 
> > > I took special care in the design above to make sure the case where
> > > tracing starts still works. In this case, where the buffer is only
> > > partially filled, the reader head is not in the subbuffer following the
> > > writer head, because it points to uninitialized data. But the
> > > OFFSET_PUSH_FLAG can only ever be set when a writer has at least
> > > completely filled the buffer once (and meets the read_offset), so we can
> > > consider that it's safe for put_subbuf() to move right after the write
> > > offset subbuffer.
> > > 
> > > I must admit that the flag idea is a bit inspired from your lockless
> > > algo I am currently reviewing. :)
> > > 
> > > Does it make sense ?
> > > 
> > > Mathieu
> > > 
> > > Note : I won't be available for implementation work before July 6th...
> > > got a thesis to write...
> > > 
> > > 
> > > > -- Steve
> > > > 
> > > 
> > > -- 
> > > Mathieu Desnoyers
> > > OpenPGP key fingerprint: 8CD5 52C3 8E3C 4140 715F  BA06 3F25 A8FE 3BAE 9A68
> > 
> > -- 
> > Mathieu Desnoyers
> > OpenPGP key fingerprint: 8CD5 52C3 8E3C 4140 715F  BA06 3F25 A8FE 3BAE 9A68
> > 
> 

-- 
Mathieu Desnoyers
OpenPGP key fingerprint: 8CD5 52C3 8E3C 4140 715F  BA06 3F25 A8FE 3BAE 9A68

^ permalink raw reply	[flat|nested] 29+ messages in thread

* Re: [PATCH 3/3] ring-buffer: add design document
  2009-06-11  2:38         ` Mathieu Desnoyers
@ 2009-06-12  3:13           ` Huang Ying
  2009-06-12  3:46             ` H. Peter Anvin
  0 siblings, 1 reply; 29+ messages in thread
From: Huang Ying @ 2009-06-12  3:13 UTC (permalink / raw)
  To: Mathieu Desnoyers
  Cc: Steven Rostedt, linux-kernel, Ingo Molnar, Andrew Morton,
	Thomas Gleixner, Peter Zijlstra, Frederic Weisbecker,
	Theodore Tso, Arnaldo Carvalho de Melo, Lai Jiangshan,
	Martin J. Bligh, Christoph Hellwig, Li Zefan, H. Peter Anvin,
	Hidetoshi Seto, Masami Hiramatsu

On Thu, 2009-06-11 at 10:38 +0800, Mathieu Desnoyers wrote:
> > > Are these archs without cmpxchg and NMIs, a concern for you?
> > 
> > ARM has no cmpxchg until ARM v6, but it has NMI like mechanism named
> > FIQ.
> > 
> 
> One could probably adapt the cmpxchg for earlier ARM so it disables
> FIQs. Note that the current limitation is that there is only a
> fiq disable, not a fiq save/restore.

Yes. It seems that ARM is OK after FIQ save/restore issue is fixed.
Another machine with NMI but no NMI-safe cmpxchg is "real" 386. That is
very old machine, does that matter?

Best Regards,
Huang Ying



^ permalink raw reply	[flat|nested] 29+ messages in thread

* Re: [PATCH 3/3] ring-buffer: add design document
  2009-06-12  3:13           ` Huang Ying
@ 2009-06-12  3:46             ` H. Peter Anvin
  0 siblings, 0 replies; 29+ messages in thread
From: H. Peter Anvin @ 2009-06-12  3:46 UTC (permalink / raw)
  To: Huang Ying
  Cc: Mathieu Desnoyers, Steven Rostedt, linux-kernel, Ingo Molnar,
	Andrew Morton, Thomas Gleixner, Peter Zijlstra,
	Frederic Weisbecker, Theodore Tso, Arnaldo Carvalho de Melo,
	Lai Jiangshan, Martin J. Bligh, Christoph Hellwig, Li Zefan,
	Hidetoshi Seto, Masami Hiramatsu

Huang Ying wrote:
> 
> Yes. It seems that ARM is OK after FIQ save/restore issue is fixed.
> Another machine with NMI but no NMI-safe cmpxchg is "real" 386. That is
> very old machine, does that matter?
> 

Well, we still support it (UP only, though.)  It all depends on if there
is a fallback that is good enough.

	-hpa

-- 
H. Peter Anvin, Intel Open Source Technology Center
I work for Intel.  I don't speak on their behalf.


^ permalink raw reply	[flat|nested] 29+ messages in thread

* Re: [PATCH 3/3] ring-buffer: add design document
  2009-06-10 19:53 ` [PATCH 3/3] ring-buffer: add design document Steven Rostedt
                     ` (2 preceding siblings ...)
  2009-06-11  3:15   ` Hidetoshi Seto
@ 2009-06-13  1:54   ` Frederic Weisbecker
  2009-06-13  2:16     ` Steven Rostedt
  2009-06-15  0:56   ` Frederic Weisbecker
  4 siblings, 1 reply; 29+ messages in thread
From: Frederic Weisbecker @ 2009-06-13  1:54 UTC (permalink / raw)
  To: Steven Rostedt
  Cc: linux-kernel, Ingo Molnar, Andrew Morton, Thomas Gleixner,
	Peter Zijlstra, Theodore Tso, Arnaldo Carvalho de Melo,
	Mathieu Desnoyers, Lai Jiangshan, Martin J. Bligh,
	Christoph Hellwig, Li Zefan, Huang Ying, H. Peter Anvin,
	Hidetoshi Seto, Masami Hiramatsu

On Wed, Jun 10, 2009 at 03:53:14PM -0400, Steven Rostedt wrote:
> From: Steven Rostedt <srostedt@redhat.com>
> 
> This adds the design document for the ring buffer and also
> explains how it is designed to have lockless writes.
> 
> Signed-off-by: Steven Rostedt <rostedt@goodmis.org>
> ---
>  Documentation/trace/ring-buffer-design.txt |  949 ++++++++++++++++++++++++++++
>  1 files changed, 949 insertions(+), 0 deletions(-)
>  create mode 100644 Documentation/trace/ring-buffer-design.txt
> 
> diff --git a/Documentation/trace/ring-buffer-design.txt b/Documentation/trace/ring-buffer-design.txt
> new file mode 100644
> index 0000000..cca290b
> --- /dev/null
> +++ b/Documentation/trace/ring-buffer-design.txt
> @@ -0,0 +1,949 @@
> +		Lockless Ring Buffer Design
> +		===========================
> +
> +Copyright 2009 Red Hat Inc.
> +   Author:   Steven Rostedt <srostedt@redhat.com>
> +  License:   The GNU Free Documentation License, Version 1.2
> +               (dual licensed under the GPL v2)
> +
> +Written for: 2.6.31
> +
> +Terminology used in this Document
> +---------------------------------
> +
> +tail - where new writes happen in the ring buffer.
> +
> +head - where new reads happen in the ring buffer.
> +
> +producer - the task that writes into the ring buffer (same as writer)
> +
> +writer - same as producer
> +
> +consumer - the task that reads from the buffer (same as reader)
> +
> +reader - same as consumer.
> +
> +reader_page - A page outside the ring buffer used solely (for the most part)
> +    by the reader.
> +
> +head_page - a pointer to the page that the reader will use next
> +
> +tail_page - a pointer to the page that will be written to next
> +
> +commit_page - a pointer to the page with the last finished non nested write.
> +
> +cmpxchg - hardware assisted atomic transaction that performs the following:
> +
> +   A = B iff previous A == C
> +
> +   R = cmpxchg(A, C, B) is saying that we replace A with B if and only if
> +      current A is equal to C, and we put the old (current) A into R
> +
> +   R gets the previous A regardless if A is updated with B or not.
> +
> +   To see if the update was successful a compare of R == C may be used.
> +
> +The Generic Ring Buffer
> +-----------------------
> +
> +The ring buffer can be used in either an overwrite mode or in
> +producer/consumer mode.
> +
> +Producer/consumer mode is where the producer were to fill up the
> +buffer before the consumer could free up anything, the producer
> +will stop writing to the buffer. This will lose most recent events.
> +
> +Overwrite mode is where the produce were to fill up the buffer
> +before the consumer could free up anything, the producer will
> +overwrite the older data. This will lose the oldest events.
> +
> +No two writers can write at the same time (on the same per cpu buffer),
> +but a writer may preempt another writer, but it must finish writing
> +before the previous writer may continue. This is very important to the
> +algorithm. The writers act like a "stack".
> +
> +
> +  writer1 start
> +     <preempted> writer2 start
> +         <preempted> writer3 start
> +                     writer3 finishes
> +                 writer2 finishes
> +  writer1 finishes
> +
> +This is very much like a writer being preempted by an interrupt and
> +the interrupt doing a write as well.
> +
> +Readers can happen at any time. But no two readers may run at the
> +same time, nor can a reader preempt another reader. A reader can not preempt
> +a writer, but it may read/consume from the buffer at the same time as
> +a writer is writing, but the reader must be on another processor.
> +
> +A writer can preempt a reader, but a reader can not preempt a writer.
> +But a reader can read the buffer at the same time (on another processor)
> +as a writer.
> +
> +The ring buffer is made up of a list of pages held together by a link list.
> +
> +At initialization a reader page is allocated for the reader that is not
> +part of the ring buffer.
> +
> +The head_page, tail_page and commit_page are all initialized to point
> +to the same page.
> +
> +The reader page is initialized to have its next pointer pointing to
> +the head page, and its previous pointer pointing to a page before
> +the head page.
> +
> +The reader has its own page to use. At start up time, this page is
> +allocated but is not attached to the list. When the reader wants
> +to read from the buffer, if its page is empty (like it is on start up)
> +it will swap its page with the head_page. The old reader page will
> +become part of the ring buffer and the head_page will be removed.
> +A new head page goes to the page after the old head page (but not
> +the page that was swapped in).



I wonder if you could reformulate this last sentence. It took me
some time to understand it.


I first understood it as:

"""
A new page which comes from nowhere is
going to become a (and not "the") head page. Moreover, it will
be pointed by old_head_page->next...(which is actually true btw),
but this new head page will not be the next pointer on the page
that has just been swapped in.
"""

Well, actually may be it's because my english understanding is a bit....



> +
> +Once the new page is given to the reader, the reader could do what
> +it wants with it, as long as a writer has left that page.
> +
> +A sample of how the reader page is swapped: Note this does not
> +show the head page in the buffer, it is for demonstrating a swap
> +only.
> +
> +  +------+
> +  |reader|          RING BUFFER
> +  |page  |
> +  +------+
> +                  +---+   +---+   +---+
> +                  |   |-->|   |-->|   |
> +                  |   |<--|   |<--|   |
> +                  +---+   +---+   +---+
> +                   ^ |             ^ |
> +                   | +-------------+ |
> +                   +-----------------+



But may be you could also show the head page at the same time,
that would help the readers IMO (not those on the ring buffer,
but at least those from real life who can preempt several things..)


  +------+
  |reader|          RING BUFFER
  |page  |
  +------+
                  +---+   +---+   +---+
                  |   |-->|   |-->|   |
                  | H |<--|   |<--|   |
                  +---+   +---+   +---+
                   ^ |             ^ |
                   | +-------------+ |
                   +-----------------+




> +
> +  +------+
> +  |reader|          RING BUFFER
> +  |page  |-------------------+
> +  +------+                   v
> +    |             +---+   +---+   +---+
> +    |             |   |-->|   |-->|   |
> +    |             |   |<--|   |<--|   |<-+
> +    |             +---+   +---+   +---+  |
> +    |              ^ |             ^ |   |
> +    |              | +-------------+ |   |
> +    |              +-----------------+   |
> +    +------------------------------------+



  +------+
  |reader|          RING BUFFER
  |page  |-------------------+
  +------+                   v
    |             +---+   +---+   +---+
    |             |   |-->|   |-->|   |
    |             | H |<--|   |<--|   |<-+
    |             +---+   +---+   +---+  |
    |              ^ |             ^ |   |
    |              | +-------------+ |   |
    |              +-----------------+   |
    +------------------------------------+



> +  +------+
> +  |reader|          RING BUFFER
> +  |page  |-------------------+
> +  +------+ <---------------+ v
> +    |  ^          +---+   +---+   +---+
> +    |  |          |   |-->|   |-->|   |
> +    |  |          |   |<--|   |<--|   |<-+
> +    |  |          +---+   +---+   +---+  |
> +    |  |             |             ^ |   |
> +    |  |             +-------------+ |   |
> +    |  +-----------------------------+   |
> +    +------------------------------------+



  +------+
  |reader|          RING BUFFER
  |page  |-------------------+
  +------+ <---------------+ v
    |  ^          +---+   +---+   +---+
    |  |          |   |-->|   |-->|   |
    |  |          | H |<--|   |<--|   |<-+
    |  |          +---+   +---+   +---+  |
    |  |             |             ^ |   |
    |  |             +-------------+ |   |
    |  +-----------------------------+   |
    +------------------------------------+




> +  +------+
> +  |buffer|          RING BUFFER
> +  |page  |-------------------+
> +  +------+ <---------------+ v
> +    |  ^          +---+   +---+   +---+
> +    |  |          |   |   |   |-->|   |
> +    |  |  New     |   |   |   |<--|   |<-+
> +    |  | Reader   +---+   +---+   +---+  |
> +    |  |  page ----^                 |   |
> +    |  |                             |   |
> +    |  +-----------------------------+   |
> +    +------------------------------------+
> +



  +------+
  |buffer|          RING BUFFER
  |page  |-------------------+
  +------+ <---------------+ v
    |  ^          +---+   +---+   +---+
    |  |          |   |   |   |-->|   |
    |  |  New     |   |   | H |<--|   |<-+
    |  | Reader   +---+   +---+   +---+  |
    |  |  page ----^                 |   |
    |  |                             |   |
    |  +-----------------------------+   |
    +------------------------------------+


Sorry it was too tempting to try out some ascii art too,
but also it's an occasion to tell me if I misunderstood something
about the head page.


> +
> +It is possible that the page swapped is the commit page and the tail page,
> +if what is in the ring buffer is less than what is held in a buffer page.
> +
> +
> +          reader page    commit page   tail page
> +              |              |             |
> +              v              |             |
> +             +---+           |             |
> +             |   |<----------+             |
> +             |   |<------------------------+
> +             |   |------+
> +             +---+      |
> +                        |
> +                        v
> +    +---+    +---+    +---+    +---+
> +<---|   |--->|   |--->|   |--->|   |--->
> +--->|   |<---|   |<---|   |<---|   |<---
> +    +---+    +---+    +---+    +---+
> +
> +This case is still legal for this algorithm.
> +When the writer leaves the page, it simply goes into the ring buffer
> +since the reader page still points to the next location in the ring
> +buffer.
> +
> +
> +The main pointers:
> +
> +  reader page - The page used solely by the reader and is not part
> +                of the ring buffer (may be swapped in)
> +
> +  head page - the next page in the ring buffer that will be swapped
> +              with the reader page.
> +
> +  tail page - the page where the next write will take place.
> +
> +  commit page - the page that last finished a write.
> +
> +The commit page only is updated by the outer most writer in the
> +writer stack. A writer that preempts another writer will not move the
> +commit page.



Btw, how do you check that? Is there a nesting counter or something?



> +
> +When data is written into the ring buffer, a position is reserved
> +in the ring buffer and passed back to the writer. When the writer
> +is finished writing data into that position, it commits the write.
> +
> +Another write (or a read) may take place at anytime during this
> +transaction. If another write happens it must finish before continuing
> +with the previous write.


[...]


> +Nested writes
> +-------------
> +
> +In the pushing forward of the tail page we must first push forward
> +the head page if the head page is the next page. If the head page
> +is not the next page, the tail page is simply updated with a cmpxchg.
> +
> +Only writers move the tail page. This must be done atomically to protect
> +against nested writers.
> +
> +  temp_page = tail_page
> +  next_page = temp_page->next
> +  cmpxchg(tail_page, temp_page, next_page)
> +
> +The above will update the tail page if it is still pointing to the expected
> +page. If this fails, a nested write pushed it forward, the the current write
> +does not need to push it.
> +
> +
> +           temp page
> +               |
> +               v
> +            tail page
> +               |
> +               v
> +    +---+    +---+    +---+    +---+
> +<---|   |--->|   |--->|   |--->|   |--->
> +--->|   |<---|   |<---|   |<---|   |<---
> +    +---+    +---+    +---+    +---+
> +
> +Nested write comes in and moves the tail page forward:
> +
> +                    tail page (moved by nested writer)
> +            temp page   |
> +               |        |
> +               v        v
> +    +---+    +---+    +---+    +---+
> +<---|   |--->|   |--->|   |--->|   |--->
> +--->|   |<---|   |<---|   |<---|   |<---
> +    +---+    +---+    +---+    +---+
> +
> +The above would fail the cmpxchg, but since the tail page has already
> +been moved forward, the writer will just try again to reserve storage
> +on the new tail page.
> +
> +But the moving of the head page is a bit more complex.
> +
> +            tail page
> +               |
> +               v
> +    +---+    +---+    +---+    +---+
> +<---|   |--->|   |-H->|   |--->|   |--->
> +--->|   |<---|   |<---|   |<---|   |<---
> +    +---+    +---+    +---+    +---+
> +
> +The write converts the head page pointer to UPDATE.
> +
> +            tail page
> +               |
> +               v
> +    +---+    +---+    +---+    +---+
> +<---|   |--->|   |-U->|   |--->|   |--->
> +--->|   |<---|   |<---|   |<---|   |<---
> +    +---+    +---+    +---+    +---+
> +
> +But if a nested writer preempts here. It will see that the next
> +page is a head page, but it is also nested. It will detect that
> +it is nested and will save that information. The detection is the
> +fact that it sees the UPDATE flag instead of a HEADER or NORMAL
> +pointer.
> +
> +The nested writer will set the new head page pointer.
> +
> +           tail page
> +               |
> +               v
> +    +---+    +---+    +---+    +---+
> +<---|   |--->|   |-U->|   |-H->|   |--->
> +--->|   |<---|   |<---|   |<---|   |<---
> +    +---+    +---+    +---+    +---+
> +
> +But it will not reset the update back to normal. Only the writer
> +that converted a pointer from HEAD to UPDATE will convert it back
> +to NORMAL.
> +
> +                    tail page
> +                        |
> +                        v
> +    +---+    +---+    +---+    +---+
> +<---|   |--->|   |-U->|   |-H->|   |--->
> +--->|   |<---|   |<---|   |<---|   |<---
> +    +---+    +---+    +---+    +---+
> +
> +After the nested writer finishes, the outer most writer will convert
> +the UPDATE pointer to NORMAL.
> +
> +
> +                    tail page
> +                        |
> +                        v
> +    +---+    +---+    +---+    +---+
> +<---|   |--->|   |--->|   |-H->|   |--->
> +--->|   |<---|   |<---|   |<---|   |<---
> +    +---+    +---+    +---+    +---+
> +
> +
> +It can be even more complex if several nested writes came in and moved
> +the tail page ahead several pages:
> +
> +
> +(first writer)
> +
> +            tail page
> +               |
> +               v
> +    +---+    +---+    +---+    +---+
> +<---|   |--->|   |-H->|   |--->|   |--->
> +--->|   |<---|   |<---|   |<---|   |<---
> +    +---+    +---+    +---+    +---+
> +
> +The write converts the head page pointer to UPDATE.
> +
> +            tail page
> +               |
> +               v
> +    +---+    +---+    +---+    +---+
> +<---|   |--->|   |-U->|   |--->|   |--->
> +--->|   |<---|   |<---|   |<---|   |<---
> +    +---+    +---+    +---+    +---+
> +
> +Next writer comes in, and sees the update and sets up the new
> +head page.
> +
> +(second writer)
> +
> +           tail page
> +               |
> +               v
> +    +---+    +---+    +---+    +---+
> +<---|   |--->|   |-U->|   |-H->|   |--->
> +--->|   |<---|   |<---|   |<---|   |<---
> +    +---+    +---+    +---+    +---+
> +
> +The nested writer moves the tail page forward. But does not set the old
> +update page to NORMAL because it is not the outer most writer.
> +
> +                    tail page
> +                        |
> +                        v
> +    +---+    +---+    +---+    +---+
> +<---|   |--->|   |-U->|   |-H->|   |--->
> +--->|   |<---|   |<---|   |<---|   |<---
> +    +---+    +---+    +---+    +---+
> +
> +Another writer preempts and sees the page after the tail page is a head page.
> +It changes it from HEAD to UPDATE.
> +
> +(third writer)
> +
> +                    tail page
> +                        |
> +                        v
> +    +---+    +---+    +---+    +---+
> +<---|   |--->|   |-U->|   |-U->|   |--->
> +--->|   |<---|   |<---|   |<---|   |<---
> +    +---+    +---+    +---+    +---+
> +
> +The writer will move the head page forward:
> +
> +
> +(third writer)
> +
> +                    tail page
> +                        |
> +                        v
> +    +---+    +---+    +---+    +---+
> +<---|   |--->|   |-U->|   |-U->|   |-H->
> +--->|   |<---|   |<---|   |<---|   |<---
> +    +---+    +---+    +---+    +---+
> +
> +But now that the third writer did change the HEAD flag to UPDATE it
> +will convert it to normal:
> +
> +
> +(third writer)
> +
> +                    tail page
> +                        |
> +                        v
> +    +---+    +---+    +---+    +---+
> +<---|   |--->|   |-U->|   |--->|   |-H->
> +--->|   |<---|   |<---|   |<---|   |<---
> +    +---+    +---+    +---+    +---+
> +
> +
> +Then it will move the tail page, and return back to the second writer.
> +
> +
> +(second writer)
> +
> +                             tail page
> +                                 |
> +                                 v
> +    +---+    +---+    +---+    +---+
> +<---|   |--->|   |-U->|   |--->|   |-H->
> +--->|   |<---|   |<---|   |<---|   |<---
> +    +---+    +---+    +---+    +---+
> +
> +
> +The second writer will fail to move the tail page because it was already
> +moved, so it will try again and add its data to the new tail page.
> +It will return to the first writer.
> +
> +
> +(first writer)
> +
> +                             tail page
> +                                 |
> +                                 v
> +    +---+    +---+    +---+    +---+
> +<---|   |--->|   |-U->|   |--->|   |-H->
> +--->|   |<---|   |<---|   |<---|   |<---
> +    +---+    +---+    +---+    +---+
> +
> +The first writer can not know atomically test if the tail page moved
> +while it updates the HEAD page. It will then update the head page to
> +what it thinks is the new head page.
> +
> +
> +(first writer)
> +
> +                             tail page
> +                                 |
> +                                 v
> +    +---+    +---+    +---+    +---+
> +<---|   |--->|   |-U->|   |-H->|   |-H->
> +--->|   |<---|   |<---|   |<---|   |<---
> +    +---+    +---+    +---+    +---+
> +
> +Since the cmpxchg returns the old value of the pointer the first writer
> +will see it succeeded in updating the pointer from NORMAL to HEAD.
> +But as we can see, this is not good enough. It must also check to see
> +if the tail page is either where it use to be or on the next page:
> +
> +
> +(first writer)
> +
> +               A        B    tail page
> +               |        |        |
> +               v        v        v
> +    +---+    +---+    +---+    +---+
> +<---|   |--->|   |-U->|   |-H->|   |-H->
> +--->|   |<---|   |<---|   |<---|   |<---
> +    +---+    +---+    +---+    +---+
> +
> +If tail page != A and tail page does not equal B, then it must reset the
> +pointer back to NORMAL. The fact that it only needs to worry about
> +nested writers, it only needs to check this after setting the HEAD page.
> +
> +
> +(first writer)
> +
> +               A        B    tail page
> +               |        |        |
> +               v        v        v
> +    +---+    +---+    +---+    +---+
> +<---|   |--->|   |-U->|   |--->|   |-H->
> +--->|   |<---|   |<---|   |<---|   |<---
> +    +---+    +---+    +---+    +---+
> +
> +Now the writer can update the head page. This is also why the head page must
> +remain in UPDATE and only reset by the outer most writer. This prevents
> +the reader from seeing the incorrect head page.
> +
> +
> +(first writer)
> +
> +               A        B    tail page
> +               |        |        |
> +               v        v        v
> +    +---+    +---+    +---+    +---+
> +<---|   |--->|   |--->|   |--->|   |-H->
> +--->|   |<---|   |<---|   |<---|   |<---
> +    +---+    +---+    +---+    +---+


Even more tricky!

I just have a stupid question: why can't this be done
only through HEAD and NORMAL flags?

There is something certainly very obvious that I'm missing
with the point of the UPDATE flag.

Thanks,
Frederic.



^ permalink raw reply	[flat|nested] 29+ messages in thread

* Re: [PATCH 3/3] ring-buffer: add design document
  2009-06-13  1:54   ` Frederic Weisbecker
@ 2009-06-13  2:16     ` Steven Rostedt
  2009-06-13 22:36       ` Frederic Weisbecker
  0 siblings, 1 reply; 29+ messages in thread
From: Steven Rostedt @ 2009-06-13  2:16 UTC (permalink / raw)
  To: Frederic Weisbecker
  Cc: linux-kernel, Ingo Molnar, Andrew Morton, Thomas Gleixner,
	Peter Zijlstra, Theodore Tso, Arnaldo Carvalho de Melo,
	Mathieu Desnoyers, Lai Jiangshan, Martin J. Bligh,
	Christoph Hellwig, Li Zefan, Huang Ying, H. Peter Anvin,
	Hidetoshi Seto, Masami Hiramatsu


On Sat, 13 Jun 2009, Frederic Weisbecker wrote:

> On Wed, Jun 10, 2009 at 03:53:14PM -0400, Steven Rostedt wrote:
> > From: Steven Rostedt <srostedt@redhat.com>
> > 
> > This adds the design document for the ring buffer and also
> > explains how it is designed to have lockless writes.
> > 
> > Signed-off-by: Steven Rostedt <rostedt@goodmis.org>
> > ---
> >  Documentation/trace/ring-buffer-design.txt |  949 ++++++++++++++++++++++++++++
> >  1 files changed, 949 insertions(+), 0 deletions(-)
> >  create mode 100644 Documentation/trace/ring-buffer-design.txt
> > 
> > diff --git a/Documentation/trace/ring-buffer-design.txt b/Documentation/trace/ring-buffer-design.txt
> > new file mode 100644
> > index 0000000..cca290b
> > --- /dev/null
> > +++ b/Documentation/trace/ring-buffer-design.txt
> > @@ -0,0 +1,949 @@
> > +		Lockless Ring Buffer Design
> > +		===========================
> > +
> > +Copyright 2009 Red Hat Inc.
> > +   Author:   Steven Rostedt <srostedt@redhat.com>
> > +  License:   The GNU Free Documentation License, Version 1.2
> > +               (dual licensed under the GPL v2)
> > +
> > +Written for: 2.6.31
> > +
> > +Terminology used in this Document
> > +---------------------------------
> > +
> > +tail - where new writes happen in the ring buffer.
> > +
> > +head - where new reads happen in the ring buffer.
> > +
> > +producer - the task that writes into the ring buffer (same as writer)
> > +
> > +writer - same as producer
> > +
> > +consumer - the task that reads from the buffer (same as reader)
> > +
> > +reader - same as consumer.
> > +
> > +reader_page - A page outside the ring buffer used solely (for the most part)
> > +    by the reader.
> > +
> > +head_page - a pointer to the page that the reader will use next
> > +
> > +tail_page - a pointer to the page that will be written to next
> > +
> > +commit_page - a pointer to the page with the last finished non nested write.
> > +
> > +cmpxchg - hardware assisted atomic transaction that performs the following:
> > +
> > +   A = B iff previous A == C
> > +
> > +   R = cmpxchg(A, C, B) is saying that we replace A with B if and only if
> > +      current A is equal to C, and we put the old (current) A into R
> > +
> > +   R gets the previous A regardless if A is updated with B or not.
> > +
> > +   To see if the update was successful a compare of R == C may be used.
> > +
> > +The Generic Ring Buffer
> > +-----------------------
> > +
> > +The ring buffer can be used in either an overwrite mode or in
> > +producer/consumer mode.
> > +
> > +Producer/consumer mode is where the producer were to fill up the
> > +buffer before the consumer could free up anything, the producer
> > +will stop writing to the buffer. This will lose most recent events.
> > +
> > +Overwrite mode is where the produce were to fill up the buffer
> > +before the consumer could free up anything, the producer will
> > +overwrite the older data. This will lose the oldest events.
> > +
> > +No two writers can write at the same time (on the same per cpu buffer),
> > +but a writer may preempt another writer, but it must finish writing
> > +before the previous writer may continue. This is very important to the
> > +algorithm. The writers act like a "stack".
> > +
> > +
> > +  writer1 start
> > +     <preempted> writer2 start
> > +         <preempted> writer3 start
> > +                     writer3 finishes
> > +                 writer2 finishes
> > +  writer1 finishes
> > +
> > +This is very much like a writer being preempted by an interrupt and
> > +the interrupt doing a write as well.
> > +
> > +Readers can happen at any time. But no two readers may run at the
> > +same time, nor can a reader preempt another reader. A reader can not preempt
> > +a writer, but it may read/consume from the buffer at the same time as
> > +a writer is writing, but the reader must be on another processor.
> > +
> > +A writer can preempt a reader, but a reader can not preempt a writer.
> > +But a reader can read the buffer at the same time (on another processor)
> > +as a writer.
> > +
> > +The ring buffer is made up of a list of pages held together by a link list.
> > +
> > +At initialization a reader page is allocated for the reader that is not
> > +part of the ring buffer.
> > +
> > +The head_page, tail_page and commit_page are all initialized to point
> > +to the same page.
> > +
> > +The reader page is initialized to have its next pointer pointing to
> > +the head page, and its previous pointer pointing to a page before
> > +the head page.
> > +
> > +The reader has its own page to use. At start up time, this page is
> > +allocated but is not attached to the list. When the reader wants
> > +to read from the buffer, if its page is empty (like it is on start up)
> > +it will swap its page with the head_page. The old reader page will
> > +become part of the ring buffer and the head_page will be removed.
> > +A new head page goes to the page after the old head page (but not
> > +the page that was swapped in).
> 
> 
> 
> I wonder if you could reformulate this last sentence. It took me
> some time to understand it.

Yuck, that last sentence is ugly.

> 
> 
> I first understood it as:
> 
> """
> A new page which comes from nowhere is
> going to become a (and not "the") head page. Moreover, it will
> be pointed by old_head_page->next...(which is actually true btw),
> but this new head page will not be the next pointer on the page
> that has just been swapped in.
> """
> 
> Well, actually may be it's because my english understanding is a bit....

No, I think I wrote that at 3am.

How about this:

"The page after the inserted page (old reader_page) will become the new 
head page."

?

> 
> 
> 
> > +
> > +Once the new page is given to the reader, the reader could do what
> > +it wants with it, as long as a writer has left that page.
> > +



> > +A sample of how the reader page is swapped: Note this does not
> > +show the head page in the buffer, it is for demonstrating a swap
> > +only.

Note above.


> > +
> > +  +------+
> > +  |reader|          RING BUFFER
> > +  |page  |
> > +  +------+
> > +                  +---+   +---+   +---+
> > +                  |   |-->|   |-->|   |
> > +                  |   |<--|   |<--|   |
> > +                  +---+   +---+   +---+
> > +                   ^ |             ^ |
> > +                   | +-------------+ |
> > +                   +-----------------+
> 
> 
> 
> But may be you could also show the head page at the same time,
> that would help the readers IMO (not those on the ring buffer,
> but at least those from real life who can preempt several things..)

I could add the H, but I just wanted to concentrate on the swap without 
having too many details. But if you think the H would help, I'm fine with 
it.


> 
> 
>   +------+
>   |reader|          RING BUFFER
>   |page  |
>   +------+
>                   +---+   +---+   +---+
>                   |   |-->|   |-->|   |
>                   | H |<--|   |<--|   |
>                   +---+   +---+   +---+
>                    ^ |             ^ |
>                    | +-------------+ |
>                    +-----------------+
> 
> 
> 
> 
> > +
> > +  +------+
> > +  |reader|          RING BUFFER
> > +  |page  |-------------------+
> > +  +------+                   v
> > +    |             +---+   +---+   +---+
> > +    |             |   |-->|   |-->|   |
> > +    |             |   |<--|   |<--|   |<-+
> > +    |             +---+   +---+   +---+  |
> > +    |              ^ |             ^ |   |
> > +    |              | +-------------+ |   |
> > +    |              +-----------------+   |
> > +    +------------------------------------+
> 
> 
> 
>   +------+
>   |reader|          RING BUFFER
>   |page  |-------------------+
>   +------+                   v
>     |             +---+   +---+   +---+
>     |             |   |-->|   |-->|   |
>     |             | H |<--|   |<--|   |<-+
>     |             +---+   +---+   +---+  |
>     |              ^ |             ^ |   |
>     |              | +-------------+ |   |
>     |              +-----------------+   |
>     +------------------------------------+
> 
> 
> 
> > +  +------+
> > +  |reader|          RING BUFFER
> > +  |page  |-------------------+
> > +  +------+ <---------------+ v
> > +    |  ^          +---+   +---+   +---+
> > +    |  |          |   |-->|   |-->|   |
> > +    |  |          |   |<--|   |<--|   |<-+
> > +    |  |          +---+   +---+   +---+  |
> > +    |  |             |             ^ |   |
> > +    |  |             +-------------+ |   |
> > +    |  +-----------------------------+   |
> > +    +------------------------------------+
> 
> 
> 
>   +------+
>   |reader|          RING BUFFER
>   |page  |-------------------+
>   +------+ <---------------+ v
>     |  ^          +---+   +---+   +---+
>     |  |          |   |-->|   |-->|   |
>     |  |          | H |<--|   |<--|   |<-+
>     |  |          +---+   +---+   +---+  |
>     |  |             |             ^ |   |
>     |  |             +-------------+ |   |
>     |  +-----------------------------+   |
>     +------------------------------------+

Oooh, you cut and paste the error in the above. Do you see it?

> 
> 
> 
> 
> > +  +------+
> > +  |buffer|          RING BUFFER
> > +  |page  |-------------------+
> > +  +------+ <---------------+ v
> > +    |  ^          +---+   +---+   +---+
> > +    |  |          |   |   |   |-->|   |
> > +    |  |  New     |   |   |   |<--|   |<-+
> > +    |  | Reader   +---+   +---+   +---+  |
> > +    |  |  page ----^                 |   |
> > +    |  |                             |   |
> > +    |  +-----------------------------+   |
> > +    +------------------------------------+
> > +
> 
> 
> 
>   +------+
>   |buffer|          RING BUFFER
>   |page  |-------------------+
>   +------+ <---------------+ v
>     |  ^          +---+   +---+   +---+
>     |  |          |   |   |   |-->|   |
>     |  |  New     |   |   | H |<--|   |<-+
>     |  | Reader   +---+   +---+   +---+  |
>     |  |  page ----^                 |   |
>     |  |                             |   |
>     |  +-----------------------------+   |
>     +------------------------------------+
> 
> 
> Sorry it was too tempting to try out some ascii art too,
> but also it's an occasion to tell me if I misunderstood something
> about the head page.

Yeah, the above seems correct (except for the error you left in).

> 
> 
> > +
> > +It is possible that the page swapped is the commit page and the tail page,
> > +if what is in the ring buffer is less than what is held in a buffer page.
> > +
> > +
> > +          reader page    commit page   tail page
> > +              |              |             |
> > +              v              |             |
> > +             +---+           |             |
> > +             |   |<----------+             |
> > +             |   |<------------------------+
> > +             |   |------+
> > +             +---+      |
> > +                        |
> > +                        v
> > +    +---+    +---+    +---+    +---+
> > +<---|   |--->|   |--->|   |--->|   |--->
> > +--->|   |<---|   |<---|   |<---|   |<---
> > +    +---+    +---+    +---+    +---+
> > +
> > +This case is still legal for this algorithm.
> > +When the writer leaves the page, it simply goes into the ring buffer
> > +since the reader page still points to the next location in the ring
> > +buffer.
> > +
> > +
> > +The main pointers:
> > +
> > +  reader page - The page used solely by the reader and is not part
> > +                of the ring buffer (may be swapped in)
> > +
> > +  head page - the next page in the ring buffer that will be swapped
> > +              with the reader page.
> > +
> > +  tail page - the page where the next write will take place.
> > +
> > +  commit page - the page that last finished a write.
> > +
> > +The commit page only is updated by the outer most writer in the
> > +writer stack. A writer that preempts another writer will not move the
> > +commit page.
> 
> 
> 
> Btw, how do you check that? Is there a nesting counter or something?

Because only the writer that reserves the pointer after the commit, is the 
committer.

static int
rb_is_commit(struct ring_buffer_per_cpu *cpu_buffer,
             struct ring_buffer_event *event)
{
        unsigned long addr = (unsigned long)event;
        unsigned long index;

        index = rb_event_index(event);
        addr &= PAGE_MASK;

        return cpu_buffer->commit_page->page == (void *)addr &&
                rb_commit_index(cpu_buffer) == index;
}


Although, I'm thinking of replacing it with a counter. May eliminate some 
of the tight races I need to prevent. And may even clean up the code, and 
speed it up.

Hmm, I may implement that now.


> 
> 
> 
> > +
> > +When data is written into the ring buffer, a position is reserved
> > +in the ring buffer and passed back to the writer. When the writer
> > +is finished writing data into that position, it commits the write.
> > +
> > +Another write (or a read) may take place at anytime during this
> > +transaction. If another write happens it must finish before continuing
> > +with the previous write.
> 
> 
> [...]
> 
> 
> > +Nested writes
> > +-------------
> > +
> > +In the pushing forward of the tail page we must first push forward
> > +the head page if the head page is the next page. If the head page
> > +is not the next page, the tail page is simply updated with a cmpxchg.
> > +
> > +Only writers move the tail page. This must be done atomically to protect
> > +against nested writers.
> > +
> > +  temp_page = tail_page
> > +  next_page = temp_page->next
> > +  cmpxchg(tail_page, temp_page, next_page)
> > +
> > +The above will update the tail page if it is still pointing to the expected
> > +page. If this fails, a nested write pushed it forward, the the current write
> > +does not need to push it.
> > +
> > +
> > +           temp page
> > +               |
> > +               v
> > +            tail page
> > +               |
> > +               v
> > +    +---+    +---+    +---+    +---+
> > +<---|   |--->|   |--->|   |--->|   |--->
> > +--->|   |<---|   |<---|   |<---|   |<---
> > +    +---+    +---+    +---+    +---+
> > +
> > +Nested write comes in and moves the tail page forward:
> > +
> > +                    tail page (moved by nested writer)
> > +            temp page   |
> > +               |        |
> > +               v        v
> > +    +---+    +---+    +---+    +---+
> > +<---|   |--->|   |--->|   |--->|   |--->
> > +--->|   |<---|   |<---|   |<---|   |<---
> > +    +---+    +---+    +---+    +---+
> > +
> > +The above would fail the cmpxchg, but since the tail page has already
> > +been moved forward, the writer will just try again to reserve storage
> > +on the new tail page.
> > +
> > +But the moving of the head page is a bit more complex.
> > +
> > +            tail page
> > +               |
> > +               v
> > +    +---+    +---+    +---+    +---+
> > +<---|   |--->|   |-H->|   |--->|   |--->
> > +--->|   |<---|   |<---|   |<---|   |<---
> > +    +---+    +---+    +---+    +---+
> > +
> > +The write converts the head page pointer to UPDATE.
> > +
> > +            tail page
> > +               |
> > +               v
> > +    +---+    +---+    +---+    +---+
> > +<---|   |--->|   |-U->|   |--->|   |--->
> > +--->|   |<---|   |<---|   |<---|   |<---
> > +    +---+    +---+    +---+    +---+
> > +
> > +But if a nested writer preempts here. It will see that the next
> > +page is a head page, but it is also nested. It will detect that
> > +it is nested and will save that information. The detection is the
> > +fact that it sees the UPDATE flag instead of a HEADER or NORMAL
> > +pointer.
> > +
> > +The nested writer will set the new head page pointer.
> > +
> > +           tail page
> > +               |
> > +               v
> > +    +---+    +---+    +---+    +---+
> > +<---|   |--->|   |-U->|   |-H->|   |--->
> > +--->|   |<---|   |<---|   |<---|   |<---
> > +    +---+    +---+    +---+    +---+
> > +
> > +But it will not reset the update back to normal. Only the writer
> > +that converted a pointer from HEAD to UPDATE will convert it back
> > +to NORMAL.
> > +
> > +                    tail page
> > +                        |
> > +                        v
> > +    +---+    +---+    +---+    +---+
> > +<---|   |--->|   |-U->|   |-H->|   |--->
> > +--->|   |<---|   |<---|   |<---|   |<---
> > +    +---+    +---+    +---+    +---+
> > +
> > +After the nested writer finishes, the outer most writer will convert
> > +the UPDATE pointer to NORMAL.
> > +
> > +
> > +                    tail page
> > +                        |
> > +                        v
> > +    +---+    +---+    +---+    +---+
> > +<---|   |--->|   |--->|   |-H->|   |--->
> > +--->|   |<---|   |<---|   |<---|   |<---
> > +    +---+    +---+    +---+    +---+
> > +
> > +
> > +It can be even more complex if several nested writes came in and moved
> > +the tail page ahead several pages:
> > +
> > +
> > +(first writer)
> > +
> > +            tail page
> > +               |
> > +               v
> > +    +---+    +---+    +---+    +---+
> > +<---|   |--->|   |-H->|   |--->|   |--->
> > +--->|   |<---|   |<---|   |<---|   |<---
> > +    +---+    +---+    +---+    +---+
> > +
> > +The write converts the head page pointer to UPDATE.
> > +
> > +            tail page
> > +               |
> > +               v
> > +    +---+    +---+    +---+    +---+
> > +<---|   |--->|   |-U->|   |--->|   |--->
> > +--->|   |<---|   |<---|   |<---|   |<---
> > +    +---+    +---+    +---+    +---+
> > +
> > +Next writer comes in, and sees the update and sets up the new
> > +head page.
> > +
> > +(second writer)
> > +
> > +           tail page
> > +               |
> > +               v
> > +    +---+    +---+    +---+    +---+
> > +<---|   |--->|   |-U->|   |-H->|   |--->
> > +--->|   |<---|   |<---|   |<---|   |<---
> > +    +---+    +---+    +---+    +---+
> > +
> > +The nested writer moves the tail page forward. But does not set the old
> > +update page to NORMAL because it is not the outer most writer.
> > +
> > +                    tail page
> > +                        |
> > +                        v
> > +    +---+    +---+    +---+    +---+
> > +<---|   |--->|   |-U->|   |-H->|   |--->
> > +--->|   |<---|   |<---|   |<---|   |<---
> > +    +---+    +---+    +---+    +---+
> > +
> > +Another writer preempts and sees the page after the tail page is a head page.
> > +It changes it from HEAD to UPDATE.
> > +
> > +(third writer)
> > +
> > +                    tail page
> > +                        |
> > +                        v
> > +    +---+    +---+    +---+    +---+
> > +<---|   |--->|   |-U->|   |-U->|   |--->
> > +--->|   |<---|   |<---|   |<---|   |<---
> > +    +---+    +---+    +---+    +---+
> > +
> > +The writer will move the head page forward:
> > +
> > +
> > +(third writer)
> > +
> > +                    tail page
> > +                        |
> > +                        v
> > +    +---+    +---+    +---+    +---+
> > +<---|   |--->|   |-U->|   |-U->|   |-H->
> > +--->|   |<---|   |<---|   |<---|   |<---
> > +    +---+    +---+    +---+    +---+
> > +
> > +But now that the third writer did change the HEAD flag to UPDATE it
> > +will convert it to normal:
> > +
> > +
> > +(third writer)
> > +
> > +                    tail page
> > +                        |
> > +                        v
> > +    +---+    +---+    +---+    +---+
> > +<---|   |--->|   |-U->|   |--->|   |-H->
> > +--->|   |<---|   |<---|   |<---|   |<---
> > +    +---+    +---+    +---+    +---+
> > +
> > +
> > +Then it will move the tail page, and return back to the second writer.
> > +
> > +
> > +(second writer)
> > +
> > +                             tail page
> > +                                 |
> > +                                 v
> > +    +---+    +---+    +---+    +---+
> > +<---|   |--->|   |-U->|   |--->|   |-H->
> > +--->|   |<---|   |<---|   |<---|   |<---
> > +    +---+    +---+    +---+    +---+
> > +
> > +
> > +The second writer will fail to move the tail page because it was already
> > +moved, so it will try again and add its data to the new tail page.
> > +It will return to the first writer.
> > +
> > +
> > +(first writer)
> > +
> > +                             tail page
> > +                                 |
> > +                                 v
> > +    +---+    +---+    +---+    +---+
> > +<---|   |--->|   |-U->|   |--->|   |-H->
> > +--->|   |<---|   |<---|   |<---|   |<---
> > +    +---+    +---+    +---+    +---+
> > +
> > +The first writer can not know atomically test if the tail page moved
> > +while it updates the HEAD page. It will then update the head page to
> > +what it thinks is the new head page.
> > +
> > +
> > +(first writer)
> > +
> > +                             tail page
> > +                                 |
> > +                                 v
> > +    +---+    +---+    +---+    +---+
> > +<---|   |--->|   |-U->|   |-H->|   |-H->
> > +--->|   |<---|   |<---|   |<---|   |<---
> > +    +---+    +---+    +---+    +---+
> > +
> > +Since the cmpxchg returns the old value of the pointer the first writer
> > +will see it succeeded in updating the pointer from NORMAL to HEAD.
> > +But as we can see, this is not good enough. It must also check to see
> > +if the tail page is either where it use to be or on the next page:
> > +
> > +
> > +(first writer)
> > +
> > +               A        B    tail page
> > +               |        |        |
> > +               v        v        v
> > +    +---+    +---+    +---+    +---+
> > +<---|   |--->|   |-U->|   |-H->|   |-H->
> > +--->|   |<---|   |<---|   |<---|   |<---
> > +    +---+    +---+    +---+    +---+
> > +
> > +If tail page != A and tail page does not equal B, then it must reset the
> > +pointer back to NORMAL. The fact that it only needs to worry about
> > +nested writers, it only needs to check this after setting the HEAD page.
> > +
> > +
> > +(first writer)
> > +
> > +               A        B    tail page
> > +               |        |        |
> > +               v        v        v
> > +    +---+    +---+    +---+    +---+
> > +<---|   |--->|   |-U->|   |--->|   |-H->
> > +--->|   |<---|   |<---|   |<---|   |<---
> > +    +---+    +---+    +---+    +---+
> > +
> > +Now the writer can update the head page. This is also why the head page must
> > +remain in UPDATE and only reset by the outer most writer. This prevents
> > +the reader from seeing the incorrect head page.
> > +
> > +
> > +(first writer)
> > +
> > +               A        B    tail page
> > +               |        |        |
> > +               v        v        v
> > +    +---+    +---+    +---+    +---+
> > +<---|   |--->|   |--->|   |--->|   |-H->
> > +--->|   |<---|   |<---|   |<---|   |<---
> > +    +---+    +---+    +---+    +---+
> 
> 
> Even more tricky!
> 
> I just have a stupid question: why can't this be done
> only through HEAD and NORMAL flags?
> 
> There is something certainly very obvious that I'm missing
> with the point of the UPDATE flag.

If you can demonstrate how to do the above lockless with just HEAD and 
NORMAL, then sure, I'm all ears ;-)

When we switch the HEAD to UPDATE, we stop the reader from moving forward 
and being another thing to handle while we move the HEAD forward. A reader 
does a cmpxchg to move the head too, and that cmpxchg will always fail if 
the pointer is has UPDATE set. The reader will just spin until it 
succeeds.

Then, the rest of the moving of the header is just races with other 
writers that are always on the same CPU, and it becomes a recursive 
problem and not a parallel one.

-- Steve


^ permalink raw reply	[flat|nested] 29+ messages in thread

* Re: [PATCH 3/3] ring-buffer: add design document
  2009-06-13  2:16     ` Steven Rostedt
@ 2009-06-13 22:36       ` Frederic Weisbecker
  2009-06-14 12:39         ` Steven Rostedt
  0 siblings, 1 reply; 29+ messages in thread
From: Frederic Weisbecker @ 2009-06-13 22:36 UTC (permalink / raw)
  To: Steven Rostedt
  Cc: linux-kernel, Ingo Molnar, Andrew Morton, Thomas Gleixner,
	Peter Zijlstra, Theodore Tso, Arnaldo Carvalho de Melo,
	Mathieu Desnoyers, Lai Jiangshan, Martin J. Bligh,
	Christoph Hellwig, Li Zefan, Huang Ying, H. Peter Anvin,
	Hidetoshi Seto, Masami Hiramatsu

On Fri, Jun 12, 2009 at 10:16:45PM -0400, Steven Rostedt wrote:
> 
> On Sat, 13 Jun 2009, Frederic Weisbecker wrote:
> 
> > On Wed, Jun 10, 2009 at 03:53:14PM -0400, Steven Rostedt wrote:
> > > From: Steven Rostedt <srostedt@redhat.com>
> > > 
> > > This adds the design document for the ring buffer and also
> > > explains how it is designed to have lockless writes.
> > > 
> > > Signed-off-by: Steven Rostedt <rostedt@goodmis.org>
> > > ---
> > >  Documentation/trace/ring-buffer-design.txt |  949 ++++++++++++++++++++++++++++
> > >  1 files changed, 949 insertions(+), 0 deletions(-)
> > >  create mode 100644 Documentation/trace/ring-buffer-design.txt
> > > 
> > > diff --git a/Documentation/trace/ring-buffer-design.txt b/Documentation/trace/ring-buffer-design.txt
> > > new file mode 100644
> > > index 0000000..cca290b
> > > --- /dev/null
> > > +++ b/Documentation/trace/ring-buffer-design.txt
> > > @@ -0,0 +1,949 @@
> > > +		Lockless Ring Buffer Design
> > > +		===========================
> > > +
> > > +Copyright 2009 Red Hat Inc.
> > > +   Author:   Steven Rostedt <srostedt@redhat.com>
> > > +  License:   The GNU Free Documentation License, Version 1.2
> > > +               (dual licensed under the GPL v2)
> > > +
> > > +Written for: 2.6.31
> > > +
> > > +Terminology used in this Document
> > > +---------------------------------
> > > +
> > > +tail - where new writes happen in the ring buffer.
> > > +
> > > +head - where new reads happen in the ring buffer.
> > > +
> > > +producer - the task that writes into the ring buffer (same as writer)
> > > +
> > > +writer - same as producer
> > > +
> > > +consumer - the task that reads from the buffer (same as reader)
> > > +
> > > +reader - same as consumer.
> > > +
> > > +reader_page - A page outside the ring buffer used solely (for the most part)
> > > +    by the reader.
> > > +
> > > +head_page - a pointer to the page that the reader will use next
> > > +
> > > +tail_page - a pointer to the page that will be written to next
> > > +
> > > +commit_page - a pointer to the page with the last finished non nested write.
> > > +
> > > +cmpxchg - hardware assisted atomic transaction that performs the following:
> > > +
> > > +   A = B iff previous A == C
> > > +
> > > +   R = cmpxchg(A, C, B) is saying that we replace A with B if and only if
> > > +      current A is equal to C, and we put the old (current) A into R
> > > +
> > > +   R gets the previous A regardless if A is updated with B or not.
> > > +
> > > +   To see if the update was successful a compare of R == C may be used.
> > > +
> > > +The Generic Ring Buffer
> > > +-----------------------
> > > +
> > > +The ring buffer can be used in either an overwrite mode or in
> > > +producer/consumer mode.
> > > +
> > > +Producer/consumer mode is where the producer were to fill up the
> > > +buffer before the consumer could free up anything, the producer
> > > +will stop writing to the buffer. This will lose most recent events.
> > > +
> > > +Overwrite mode is where the produce were to fill up the buffer
> > > +before the consumer could free up anything, the producer will
> > > +overwrite the older data. This will lose the oldest events.
> > > +
> > > +No two writers can write at the same time (on the same per cpu buffer),
> > > +but a writer may preempt another writer, but it must finish writing
> > > +before the previous writer may continue. This is very important to the
> > > +algorithm. The writers act like a "stack".
> > > +
> > > +
> > > +  writer1 start
> > > +     <preempted> writer2 start
> > > +         <preempted> writer3 start
> > > +                     writer3 finishes
> > > +                 writer2 finishes
> > > +  writer1 finishes
> > > +
> > > +This is very much like a writer being preempted by an interrupt and
> > > +the interrupt doing a write as well.
> > > +
> > > +Readers can happen at any time. But no two readers may run at the
> > > +same time, nor can a reader preempt another reader. A reader can not preempt
> > > +a writer, but it may read/consume from the buffer at the same time as
> > > +a writer is writing, but the reader must be on another processor.
> > > +
> > > +A writer can preempt a reader, but a reader can not preempt a writer.
> > > +But a reader can read the buffer at the same time (on another processor)
> > > +as a writer.
> > > +
> > > +The ring buffer is made up of a list of pages held together by a link list.
> > > +
> > > +At initialization a reader page is allocated for the reader that is not
> > > +part of the ring buffer.
> > > +
> > > +The head_page, tail_page and commit_page are all initialized to point
> > > +to the same page.
> > > +
> > > +The reader page is initialized to have its next pointer pointing to
> > > +the head page, and its previous pointer pointing to a page before
> > > +the head page.
> > > +
> > > +The reader has its own page to use. At start up time, this page is
> > > +allocated but is not attached to the list. When the reader wants
> > > +to read from the buffer, if its page is empty (like it is on start up)
> > > +it will swap its page with the head_page. The old reader page will
> > > +become part of the ring buffer and the head_page will be removed.
> > > +A new head page goes to the page after the old head page (but not
> > > +the page that was swapped in).
> > 
> > 
> > 
> > I wonder if you could reformulate this last sentence. It took me
> > some time to understand it.
> 
> Yuck, that last sentence is ugly.
> 
> > 
> > 
> > I first understood it as:
> > 
> > """
> > A new page which comes from nowhere is
> > going to become a (and not "the") head page. Moreover, it will
> > be pointed by old_head_page->next...(which is actually true btw),
> > but this new head page will not be the next pointer on the page
> > that has just been swapped in.
> > """
> > 
> > Well, actually may be it's because my english understanding is a bit....
> 
> No, I think I wrote that at 3am.
> 
> How about this:
> 
> "The page after the inserted page (old reader_page) will become the new 
> head page."
> 
> ?


Perfect!

 
> > 
> > 
> > 
> > > +
> > > +Once the new page is given to the reader, the reader could do what
> > > +it wants with it, as long as a writer has left that page.
> > > +
> 
> 
> 
> > > +A sample of how the reader page is swapped: Note this does not
> > > +show the head page in the buffer, it is for demonstrating a swap
> > > +only.
> 
> Note above.
> 
> 
> > > +
> > > +  +------+
> > > +  |reader|          RING BUFFER
> > > +  |page  |
> > > +  +------+
> > > +                  +---+   +---+   +---+
> > > +                  |   |-->|   |-->|   |
> > > +                  |   |<--|   |<--|   |
> > > +                  +---+   +---+   +---+
> > > +                   ^ |             ^ |
> > > +                   | +-------------+ |
> > > +                   +-----------------+
> > 
> > 
> > 
> > But may be you could also show the head page at the same time,
> > that would help the readers IMO (not those on the ring buffer,
> > but at least those from real life who can preempt several things..)
> 
> I could add the H, but I just wanted to concentrate on the swap without 
> having too many details. But if you think the H would help, I'm fine with 
> it.
> 


You're right. It's better to only keep the page swapping picture. The
header page is explained just after anyway.


> > 
> > 
> >   +------+
> >   |reader|          RING BUFFER
> >   |page  |
> >   +------+
> >                   +---+   +---+   +---+
> >                   |   |-->|   |-->|   |
> >                   | H |<--|   |<--|   |
> >                   +---+   +---+   +---+
> >                    ^ |             ^ |
> >                    | +-------------+ |
> >                    +-----------------+
> > 
> > 
> > 
> > 
> > > +
> > > +  +------+
> > > +  |reader|          RING BUFFER
> > > +  |page  |-------------------+
> > > +  +------+                   v
> > > +    |             +---+   +---+   +---+
> > > +    |             |   |-->|   |-->|   |
> > > +    |             |   |<--|   |<--|   |<-+
> > > +    |             +---+   +---+   +---+  |
> > > +    |              ^ |             ^ |   |
> > > +    |              | +-------------+ |   |
> > > +    |              +-----------------+   |
> > > +    +------------------------------------+
> > 
> > 
> > 
> >   +------+
> >   |reader|          RING BUFFER
> >   |page  |-------------------+
> >   +------+                   v
> >     |             +---+   +---+   +---+
> >     |             |   |-->|   |-->|   |
> >     |             | H |<--|   |<--|   |<-+
> >     |             +---+   +---+   +---+  |
> >     |              ^ |             ^ |   |
> >     |              | +-------------+ |   |
> >     |              +-----------------+   |
> >     +------------------------------------+
> > 
> > 
> > 
> > > +  +------+
> > > +  |reader|          RING BUFFER
> > > +  |page  |-------------------+
> > > +  +------+ <---------------+ v
> > > +    |  ^          +---+   +---+   +---+
> > > +    |  |          |   |-->|   |-->|   |
> > > +    |  |          |   |<--|   |<--|   |<-+
> > > +    |  |          +---+   +---+   +---+  |
> > > +    |  |             |             ^ |   |
> > > +    |  |             +-------------+ |   |
> > > +    |  +-----------------------------+   |
> > > +    +------------------------------------+
> > 
> > 
> > 
> >   +------+
> >   |reader|          RING BUFFER
> >   |page  |-------------------+
> >   +------+ <---------------+ v
> >     |  ^          +---+   +---+   +---+
> >     |  |          |   |-->|   |-->|   |
> >     |  |          | H |<--|   |<--|   |<-+
> >     |  |          +---+   +---+   +---+  |
> >     |  |             |             ^ |   |
> >     |  |             +-------------+ |   |
> >     |  +-----------------------------+   |
> >     +------------------------------------+
> 
> Oooh, you cut and paste the error in the above. Do you see it?



Yeah but I was too lazy to fix it, and the mistake has already
been reported :)



> > 
> > 
> > 
> > 
> > > +  +------+
> > > +  |buffer|          RING BUFFER
> > > +  |page  |-------------------+
> > > +  +------+ <---------------+ v
> > > +    |  ^          +---+   +---+   +---+
> > > +    |  |          |   |   |   |-->|   |
> > > +    |  |  New     |   |   |   |<--|   |<-+
> > > +    |  | Reader   +---+   +---+   +---+  |
> > > +    |  |  page ----^                 |   |
> > > +    |  |                             |   |
> > > +    |  +-----------------------------+   |
> > > +    +------------------------------------+
> > > +
> > 
> > 
> > 
> >   +------+
> >   |buffer|          RING BUFFER
> >   |page  |-------------------+
> >   +------+ <---------------+ v
> >     |  ^          +---+   +---+   +---+
> >     |  |          |   |   |   |-->|   |
> >     |  |  New     |   |   | H |<--|   |<-+
> >     |  | Reader   +---+   +---+   +---+  |
> >     |  |  page ----^                 |   |
> >     |  |                             |   |
> >     |  +-----------------------------+   |
> >     +------------------------------------+
> > 
> > 
> > Sorry it was too tempting to try out some ascii art too,
> > but also it's an occasion to tell me if I misunderstood something
> > about the head page.
> 
> Yeah, the above seems correct (except for the error you left in).
> 
> > 
> > 
> > > +
> > > +It is possible that the page swapped is the commit page and the tail page,
> > > +if what is in the ring buffer is less than what is held in a buffer page.
> > > +
> > > +
> > > +          reader page    commit page   tail page
> > > +              |              |             |
> > > +              v              |             |
> > > +             +---+           |             |
> > > +             |   |<----------+             |
> > > +             |   |<------------------------+
> > > +             |   |------+
> > > +             +---+      |
> > > +                        |
> > > +                        v
> > > +    +---+    +---+    +---+    +---+
> > > +<---|   |--->|   |--->|   |--->|   |--->
> > > +--->|   |<---|   |<---|   |<---|   |<---
> > > +    +---+    +---+    +---+    +---+
> > > +
> > > +This case is still legal for this algorithm.
> > > +When the writer leaves the page, it simply goes into the ring buffer
> > > +since the reader page still points to the next location in the ring
> > > +buffer.
> > > +
> > > +
> > > +The main pointers:
> > > +
> > > +  reader page - The page used solely by the reader and is not part
> > > +                of the ring buffer (may be swapped in)
> > > +
> > > +  head page - the next page in the ring buffer that will be swapped
> > > +              with the reader page.
> > > +
> > > +  tail page - the page where the next write will take place.
> > > +
> > > +  commit page - the page that last finished a write.
> > > +
> > > +The commit page only is updated by the outer most writer in the
> > > +writer stack. A writer that preempts another writer will not move the
> > > +commit page.
> > 
> > 
> > 
> > Btw, how do you check that? Is there a nesting counter or something?
> 
> Because only the writer that reserves the pointer after the commit, is the 
> committer.
> 
> static int
> rb_is_commit(struct ring_buffer_per_cpu *cpu_buffer,
>              struct ring_buffer_event *event)
> {
>         unsigned long addr = (unsigned long)event;
>         unsigned long index;
> 
>         index = rb_event_index(event);
>         addr &= PAGE_MASK;
> 
>         return cpu_buffer->commit_page->page == (void *)addr &&
>                 rb_commit_index(cpu_buffer) == index;
> }
> 
> 
> Although, I'm thinking of replacing it with a counter. May eliminate some 
> of the tight races I need to prevent. And may even clean up the code, and 
> speed it up.
> 
> Hmm, I may implement that now.
> 


Yeah it should be sufficient I guess.



> > 
> > 
> > 
> > > +
> > > +When data is written into the ring buffer, a position is reserved
> > > +in the ring buffer and passed back to the writer. When the writer
> > > +is finished writing data into that position, it commits the write.
> > > +
> > > +Another write (or a read) may take place at anytime during this
> > > +transaction. If another write happens it must finish before continuing
> > > +with the previous write.
> > 
> > 
> > [...]
> > 
> > 
> > > +Nested writes
> > > +-------------
> > > +
> > > +In the pushing forward of the tail page we must first push forward
> > > +the head page if the head page is the next page. If the head page
> > > +is not the next page, the tail page is simply updated with a cmpxchg.
> > > +
> > > +Only writers move the tail page. This must be done atomically to protect
> > > +against nested writers.
> > > +
> > > +  temp_page = tail_page
> > > +  next_page = temp_page->next
> > > +  cmpxchg(tail_page, temp_page, next_page)
> > > +
> > > +The above will update the tail page if it is still pointing to the expected
> > > +page. If this fails, a nested write pushed it forward, the the current write
> > > +does not need to push it.
> > > +
> > > +
> > > +           temp page
> > > +               |
> > > +               v
> > > +            tail page
> > > +               |
> > > +               v
> > > +    +---+    +---+    +---+    +---+
> > > +<---|   |--->|   |--->|   |--->|   |--->
> > > +--->|   |<---|   |<---|   |<---|   |<---
> > > +    +---+    +---+    +---+    +---+
> > > +
> > > +Nested write comes in and moves the tail page forward:
> > > +
> > > +                    tail page (moved by nested writer)
> > > +            temp page   |
> > > +               |        |
> > > +               v        v
> > > +    +---+    +---+    +---+    +---+
> > > +<---|   |--->|   |--->|   |--->|   |--->
> > > +--->|   |<---|   |<---|   |<---|   |<---
> > > +    +---+    +---+    +---+    +---+
> > > +
> > > +The above would fail the cmpxchg, but since the tail page has already
> > > +been moved forward, the writer will just try again to reserve storage
> > > +on the new tail page.
> > > +
> > > +But the moving of the head page is a bit more complex.
> > > +
> > > +            tail page
> > > +               |
> > > +               v
> > > +    +---+    +---+    +---+    +---+
> > > +<---|   |--->|   |-H->|   |--->|   |--->
> > > +--->|   |<---|   |<---|   |<---|   |<---
> > > +    +---+    +---+    +---+    +---+
> > > +
> > > +The write converts the head page pointer to UPDATE.
> > > +
> > > +            tail page
> > > +               |
> > > +               v
> > > +    +---+    +---+    +---+    +---+
> > > +<---|   |--->|   |-U->|   |--->|   |--->
> > > +--->|   |<---|   |<---|   |<---|   |<---
> > > +    +---+    +---+    +---+    +---+
> > > +
> > > +But if a nested writer preempts here. It will see that the next
> > > +page is a head page, but it is also nested. It will detect that
> > > +it is nested and will save that information. The detection is the
> > > +fact that it sees the UPDATE flag instead of a HEADER or NORMAL
> > > +pointer.
> > > +
> > > +The nested writer will set the new head page pointer.
> > > +
> > > +           tail page
> > > +               |
> > > +               v
> > > +    +---+    +---+    +---+    +---+
> > > +<---|   |--->|   |-U->|   |-H->|   |--->
> > > +--->|   |<---|   |<---|   |<---|   |<---
> > > +    +---+    +---+    +---+    +---+
> > > +
> > > +But it will not reset the update back to normal. Only the writer
> > > +that converted a pointer from HEAD to UPDATE will convert it back
> > > +to NORMAL.
> > > +
> > > +                    tail page
> > > +                        |
> > > +                        v
> > > +    +---+    +---+    +---+    +---+
> > > +<---|   |--->|   |-U->|   |-H->|   |--->
> > > +--->|   |<---|   |<---|   |<---|   |<---
> > > +    +---+    +---+    +---+    +---+
> > > +
> > > +After the nested writer finishes, the outer most writer will convert
> > > +the UPDATE pointer to NORMAL.
> > > +
> > > +
> > > +                    tail page
> > > +                        |
> > > +                        v
> > > +    +---+    +---+    +---+    +---+
> > > +<---|   |--->|   |--->|   |-H->|   |--->
> > > +--->|   |<---|   |<---|   |<---|   |<---
> > > +    +---+    +---+    +---+    +---+
> > > +
> > > +
> > > +It can be even more complex if several nested writes came in and moved
> > > +the tail page ahead several pages:
> > > +
> > > +
> > > +(first writer)
> > > +
> > > +            tail page
> > > +               |
> > > +               v
> > > +    +---+    +---+    +---+    +---+
> > > +<---|   |--->|   |-H->|   |--->|   |--->
> > > +--->|   |<---|   |<---|   |<---|   |<---
> > > +    +---+    +---+    +---+    +---+
> > > +
> > > +The write converts the head page pointer to UPDATE.
> > > +
> > > +            tail page
> > > +               |
> > > +               v
> > > +    +---+    +---+    +---+    +---+
> > > +<---|   |--->|   |-U->|   |--->|   |--->
> > > +--->|   |<---|   |<---|   |<---|   |<---
> > > +    +---+    +---+    +---+    +---+
> > > +
> > > +Next writer comes in, and sees the update and sets up the new
> > > +head page.
> > > +
> > > +(second writer)
> > > +
> > > +           tail page
> > > +               |
> > > +               v
> > > +    +---+    +---+    +---+    +---+
> > > +<---|   |--->|   |-U->|   |-H->|   |--->
> > > +--->|   |<---|   |<---|   |<---|   |<---
> > > +    +---+    +---+    +---+    +---+
> > > +
> > > +The nested writer moves the tail page forward. But does not set the old
> > > +update page to NORMAL because it is not the outer most writer.
> > > +
> > > +                    tail page
> > > +                        |
> > > +                        v
> > > +    +---+    +---+    +---+    +---+
> > > +<---|   |--->|   |-U->|   |-H->|   |--->
> > > +--->|   |<---|   |<---|   |<---|   |<---
> > > +    +---+    +---+    +---+    +---+
> > > +
> > > +Another writer preempts and sees the page after the tail page is a head page.
> > > +It changes it from HEAD to UPDATE.
> > > +
> > > +(third writer)
> > > +
> > > +                    tail page
> > > +                        |
> > > +                        v
> > > +    +---+    +---+    +---+    +---+
> > > +<---|   |--->|   |-U->|   |-U->|   |--->
> > > +--->|   |<---|   |<---|   |<---|   |<---
> > > +    +---+    +---+    +---+    +---+
> > > +
> > > +The writer will move the head page forward:
> > > +
> > > +
> > > +(third writer)
> > > +
> > > +                    tail page
> > > +                        |
> > > +                        v
> > > +    +---+    +---+    +---+    +---+
> > > +<---|   |--->|   |-U->|   |-U->|   |-H->
> > > +--->|   |<---|   |<---|   |<---|   |<---
> > > +    +---+    +---+    +---+    +---+
> > > +
> > > +But now that the third writer did change the HEAD flag to UPDATE it
> > > +will convert it to normal:
> > > +
> > > +
> > > +(third writer)
> > > +
> > > +                    tail page
> > > +                        |
> > > +                        v
> > > +    +---+    +---+    +---+    +---+
> > > +<---|   |--->|   |-U->|   |--->|   |-H->
> > > +--->|   |<---|   |<---|   |<---|   |<---
> > > +    +---+    +---+    +---+    +---+
> > > +
> > > +
> > > +Then it will move the tail page, and return back to the second writer.
> > > +
> > > +
> > > +(second writer)
> > > +
> > > +                             tail page
> > > +                                 |
> > > +                                 v
> > > +    +---+    +---+    +---+    +---+
> > > +<---|   |--->|   |-U->|   |--->|   |-H->
> > > +--->|   |<---|   |<---|   |<---|   |<---
> > > +    +---+    +---+    +---+    +---+
> > > +
> > > +
> > > +The second writer will fail to move the tail page because it was already
> > > +moved, so it will try again and add its data to the new tail page.
> > > +It will return to the first writer.
> > > +
> > > +
> > > +(first writer)
> > > +
> > > +                             tail page
> > > +                                 |
> > > +                                 v
> > > +    +---+    +---+    +---+    +---+
> > > +<---|   |--->|   |-U->|   |--->|   |-H->
> > > +--->|   |<---|   |<---|   |<---|   |<---
> > > +    +---+    +---+    +---+    +---+
> > > +
> > > +The first writer can not know atomically test if the tail page moved
> > > +while it updates the HEAD page. It will then update the head page to
> > > +what it thinks is the new head page.
> > > +
> > > +
> > > +(first writer)
> > > +
> > > +                             tail page
> > > +                                 |
> > > +                                 v
> > > +    +---+    +---+    +---+    +---+
> > > +<---|   |--->|   |-U->|   |-H->|   |-H->
> > > +--->|   |<---|   |<---|   |<---|   |<---
> > > +    +---+    +---+    +---+    +---+
> > > +
> > > +Since the cmpxchg returns the old value of the pointer the first writer
> > > +will see it succeeded in updating the pointer from NORMAL to HEAD.
> > > +But as we can see, this is not good enough. It must also check to see
> > > +if the tail page is either where it use to be or on the next page:
> > > +
> > > +
> > > +(first writer)
> > > +
> > > +               A        B    tail page
> > > +               |        |        |
> > > +               v        v        v
> > > +    +---+    +---+    +---+    +---+
> > > +<---|   |--->|   |-U->|   |-H->|   |-H->
> > > +--->|   |<---|   |<---|   |<---|   |<---
> > > +    +---+    +---+    +---+    +---+
> > > +
> > > +If tail page != A and tail page does not equal B, then it must reset the
> > > +pointer back to NORMAL. The fact that it only needs to worry about
> > > +nested writers, it only needs to check this after setting the HEAD page.
> > > +
> > > +
> > > +(first writer)
> > > +
> > > +               A        B    tail page
> > > +               |        |        |
> > > +               v        v        v
> > > +    +---+    +---+    +---+    +---+
> > > +<---|   |--->|   |-U->|   |--->|   |-H->
> > > +--->|   |<---|   |<---|   |<---|   |<---
> > > +    +---+    +---+    +---+    +---+
> > > +
> > > +Now the writer can update the head page. This is also why the head page must
> > > +remain in UPDATE and only reset by the outer most writer. This prevents
> > > +the reader from seeing the incorrect head page.
> > > +
> > > +
> > > +(first writer)
> > > +
> > > +               A        B    tail page
> > > +               |        |        |
> > > +               v        v        v
> > > +    +---+    +---+    +---+    +---+
> > > +<---|   |--->|   |--->|   |--->|   |-H->
> > > +--->|   |<---|   |<---|   |<---|   |<---
> > > +    +---+    +---+    +---+    +---+
> > 
> > 
> > Even more tricky!
> > 
> > I just have a stupid question: why can't this be done
> > only through HEAD and NORMAL flags?
> > 
> > There is something certainly very obvious that I'm missing
> > with the point of the UPDATE flag.
> 
> If you can demonstrate how to do the above lockless with just HEAD and 
> NORMAL, then sure, I'm all ears ;-)
> 
> When we switch the HEAD to UPDATE, we stop the reader from moving forward 
> and being another thing to handle while we move the HEAD forward. A reader 
> does a cmpxchg to move the head too, and that cmpxchg will always fail if 
> the pointer is has UPDATE set. The reader will just spin until it 
> succeeds.


Aah, so it's here to protect against paralell readers from another cpu
reading the current cpu buffer, right?


> Then, the rest of the moving of the header is just races with other 
> writers that are always on the same CPU, and it becomes a recursive 
> problem and not a parallel one.
> 
> -- Steve
> 


^ permalink raw reply	[flat|nested] 29+ messages in thread

* Re: [PATCH 3/3] ring-buffer: add design document
  2009-06-13 22:36       ` Frederic Weisbecker
@ 2009-06-14 12:39         ` Steven Rostedt
  2009-06-15  0:05           ` Frederic Weisbecker
  0 siblings, 1 reply; 29+ messages in thread
From: Steven Rostedt @ 2009-06-14 12:39 UTC (permalink / raw)
  To: Frederic Weisbecker
  Cc: linux-kernel, Ingo Molnar, Andrew Morton, Thomas Gleixner,
	Peter Zijlstra, Theodore Tso, Arnaldo Carvalho de Melo,
	Mathieu Desnoyers, Lai Jiangshan, Martin J. Bligh,
	Christoph Hellwig, Li Zefan, Huang Ying, H. Peter Anvin,
	Hidetoshi Seto, Masami Hiramatsu


On Sun, 14 Jun 2009, Frederic Weisbecker wrote:
> > > > +
> > > > +Now the writer can update the head page. This is also why the head page must
> > > > +remain in UPDATE and only reset by the outer most writer. This prevents
> > > > +the reader from seeing the incorrect head page.
> > > > +
> > > > +
> > > > +(first writer)
> > > > +
> > > > +               A        B    tail page
> > > > +               |        |        |
> > > > +               v        v        v
> > > > +    +---+    +---+    +---+    +---+
> > > > +<---|   |--->|   |--->|   |--->|   |-H->
> > > > +--->|   |<---|   |<---|   |<---|   |<---
> > > > +    +---+    +---+    +---+    +---+
> > > 
> > > 
> > > Even more tricky!
> > > 
> > > I just have a stupid question: why can't this be done
> > > only through HEAD and NORMAL flags?
> > > 
> > > There is something certainly very obvious that I'm missing
> > > with the point of the UPDATE flag.
> > 
> > If you can demonstrate how to do the above lockless with just HEAD and 
> > NORMAL, then sure, I'm all ears ;-)
> > 
> > When we switch the HEAD to UPDATE, we stop the reader from moving forward 
> > and being another thing to handle while we move the HEAD forward. A reader 
> > does a cmpxchg to move the head too, and that cmpxchg will always fail if 
> > the pointer is has UPDATE set. The reader will just spin until it 
> > succeeds.
> 
> 
> Aah, so it's here to protect against paralell readers from another cpu
> reading the current cpu buffer, right?

Not readers, but reader. The reader side uses locks to serialize the
accesses. The writer side is lockless.  But it is here to protect the 
writers against a reader on another CPU.

-- Steve


> 
> 
> > Then, the rest of the moving of the header is just races with other 
> > writers that are always on the same CPU, and it becomes a recursive 
> > problem and not a parallel one.

^ permalink raw reply	[flat|nested] 29+ messages in thread

* Re: [PATCH 3/3] ring-buffer: add design document
  2009-06-14 12:39         ` Steven Rostedt
@ 2009-06-15  0:05           ` Frederic Weisbecker
  0 siblings, 0 replies; 29+ messages in thread
From: Frederic Weisbecker @ 2009-06-15  0:05 UTC (permalink / raw)
  To: Steven Rostedt
  Cc: linux-kernel, Ingo Molnar, Andrew Morton, Thomas Gleixner,
	Peter Zijlstra, Theodore Tso, Arnaldo Carvalho de Melo,
	Mathieu Desnoyers, Lai Jiangshan, Martin J. Bligh,
	Christoph Hellwig, Li Zefan, Huang Ying, H. Peter Anvin,
	Hidetoshi Seto, Masami Hiramatsu

On Sun, Jun 14, 2009 at 08:39:03AM -0400, Steven Rostedt wrote:
> 
> On Sun, 14 Jun 2009, Frederic Weisbecker wrote:
> > > > > +
> > > > > +Now the writer can update the head page. This is also why the head page must
> > > > > +remain in UPDATE and only reset by the outer most writer. This prevents
> > > > > +the reader from seeing the incorrect head page.
> > > > > +
> > > > > +
> > > > > +(first writer)
> > > > > +
> > > > > +               A        B    tail page
> > > > > +               |        |        |
> > > > > +               v        v        v
> > > > > +    +---+    +---+    +---+    +---+
> > > > > +<---|   |--->|   |--->|   |--->|   |-H->
> > > > > +--->|   |<---|   |<---|   |<---|   |<---
> > > > > +    +---+    +---+    +---+    +---+
> > > > 
> > > > 
> > > > Even more tricky!
> > > > 
> > > > I just have a stupid question: why can't this be done
> > > > only through HEAD and NORMAL flags?
> > > > 
> > > > There is something certainly very obvious that I'm missing
> > > > with the point of the UPDATE flag.
> > > 
> > > If you can demonstrate how to do the above lockless with just HEAD and 
> > > NORMAL, then sure, I'm all ears ;-)
> > > 
> > > When we switch the HEAD to UPDATE, we stop the reader from moving forward 
> > > and being another thing to handle while we move the HEAD forward. A reader 
> > > does a cmpxchg to move the head too, and that cmpxchg will always fail if 
> > > the pointer is has UPDATE set. The reader will just spin until it 
> > > succeeds.
> > 
> > 
> > Aah, so it's here to protect against paralell readers from another cpu
> > reading the current cpu buffer, right?
> 
> Not readers, but reader. The reader side uses locks to serialize the
> accesses. The writer side is lockless.  But it is here to protect the 
> writers against a reader on another CPU.
> 
> -- Steve


Ok, my problem is that I've read this doc having in mind that the reader
we are talking about is always reading the buffer on the current cpu,
then a writer always preempt it. I forgot that a reader may also read
from another cpu.

Now I understand.

Thanks.


^ permalink raw reply	[flat|nested] 29+ messages in thread

* Re: [PATCH 3/3] ring-buffer: add design document
  2009-06-10 19:53 ` [PATCH 3/3] ring-buffer: add design document Steven Rostedt
                     ` (3 preceding siblings ...)
  2009-06-13  1:54   ` Frederic Weisbecker
@ 2009-06-15  0:56   ` Frederic Weisbecker
  4 siblings, 0 replies; 29+ messages in thread
From: Frederic Weisbecker @ 2009-06-15  0:56 UTC (permalink / raw)
  To: Steven Rostedt
  Cc: linux-kernel, Ingo Molnar, Andrew Morton, Thomas Gleixner,
	Peter Zijlstra, Theodore Tso, Arnaldo Carvalho de Melo,
	Mathieu Desnoyers, Lai Jiangshan, Martin J. Bligh,
	Christoph Hellwig, Li Zefan, Huang Ying, H. Peter Anvin,
	Hidetoshi Seto, Masami Hiramatsu

On Wed, Jun 10, 2009 at 03:53:14PM -0400, Steven Rostedt wrote:
> From: Steven Rostedt <srostedt@redhat.com>
> 
> This adds the design document for the ring buffer and also
> explains how it is designed to have lockless writes.
> 
> Signed-off-by: Steven Rostedt <rostedt@goodmis.org>
> ---
>  Documentation/trace/ring-buffer-design.txt |  949 ++++++++++++++++++++++++++++
>  1 files changed, 949 insertions(+), 0 deletions(-)
>  create mode 100644 Documentation/trace/ring-buffer-design.txt
> 
> diff --git a/Documentation/trace/ring-buffer-design.txt b/Documentation/trace/ring-buffer-design.txt
> new file mode 100644
> index 0000000..cca290b
> --- /dev/null
> +++ b/Documentation/trace/ring-buffer-design.txt
> @@ -0,0 +1,949 @@
> +		Lockless Ring Buffer Design
> +		===========================
> +
> +Copyright 2009 Red Hat Inc.
> +   Author:   Steven Rostedt <srostedt@redhat.com>
> +  License:   The GNU Free Documentation License, Version 1.2
> +               (dual licensed under the GPL v2)
> +
> +Written for: 2.6.31
> +
> +Terminology used in this Document
> +---------------------------------
> +
> +tail - where new writes happen in the ring buffer.
> +
> +head - where new reads happen in the ring buffer.
> +
> +producer - the task that writes into the ring buffer (same as writer)
> +
> +writer - same as producer
> +
> +consumer - the task that reads from the buffer (same as reader)
> +
> +reader - same as consumer.
> +
> +reader_page - A page outside the ring buffer used solely (for the most part)
> +    by the reader.
> +
> +head_page - a pointer to the page that the reader will use next
> +
> +tail_page - a pointer to the page that will be written to next
> +
> +commit_page - a pointer to the page with the last finished non nested write.
> +
> +cmpxchg - hardware assisted atomic transaction that performs the following:
> +
> +   A = B iff previous A == C
> +
> +   R = cmpxchg(A, C, B) is saying that we replace A with B if and only if
> +      current A is equal to C, and we put the old (current) A into R
> +
> +   R gets the previous A regardless if A is updated with B or not.
> +
> +   To see if the update was successful a compare of R == C may be used.
> +
> +The Generic Ring Buffer
> +-----------------------
> +
> +The ring buffer can be used in either an overwrite mode or in
> +producer/consumer mode.
> +
> +Producer/consumer mode is where the producer were to fill up the
> +buffer before the consumer could free up anything, the producer
> +will stop writing to the buffer. This will lose most recent events.
> +
> +Overwrite mode is where the produce were to fill up the buffer
> +before the consumer could free up anything, the producer will
> +overwrite the older data. This will lose the oldest events.
> +
> +No two writers can write at the same time (on the same per cpu buffer),
> +but a writer may preempt another writer, but it must finish writing
> +before the previous writer may continue. This is very important to the
> +algorithm. The writers act like a "stack".
> +
> +
> +  writer1 start
> +     <preempted> writer2 start
> +         <preempted> writer3 start
> +                     writer3 finishes
> +                 writer2 finishes
> +  writer1 finishes
> +
> +This is very much like a writer being preempted by an interrupt and
> +the interrupt doing a write as well.
> +
> +Readers can happen at any time. But no two readers may run at the
> +same time, nor can a reader preempt another reader. A reader can not preempt
> +a writer, but it may read/consume from the buffer at the same time as
> +a writer is writing, but the reader must be on another processor.
> +
> +A writer can preempt a reader, but a reader can not preempt a writer.
> +But a reader can read the buffer at the same time (on another processor)
> +as a writer.
> +
> +The ring buffer is made up of a list of pages held together by a link list.
> +
> +At initialization a reader page is allocated for the reader that is not
> +part of the ring buffer.
> +
> +The head_page, tail_page and commit_page are all initialized to point
> +to the same page.
> +
> +The reader page is initialized to have its next pointer pointing to
> +the head page, and its previous pointer pointing to a page before
> +the head page.
> +
> +The reader has its own page to use. At start up time, this page is
> +allocated but is not attached to the list. When the reader wants
> +to read from the buffer, if its page is empty (like it is on start up)
> +it will swap its page with the head_page. The old reader page will
> +become part of the ring buffer and the head_page will be removed.
> +A new head page goes to the page after the old head page (but not
> +the page that was swapped in).
> +
> +Once the new page is given to the reader, the reader could do what
> +it wants with it, as long as a writer has left that page.
> +
> +A sample of how the reader page is swapped: Note this does not
> +show the head page in the buffer, it is for demonstrating a swap
> +only.
> +
> +  +------+
> +  |reader|          RING BUFFER
> +  |page  |
> +  +------+
> +                  +---+   +---+   +---+
> +                  |   |-->|   |-->|   |
> +                  |   |<--|   |<--|   |
> +                  +---+   +---+   +---+
> +                   ^ |             ^ |
> +                   | +-------------+ |
> +                   +-----------------+
> +
> +
> +  +------+
> +  |reader|          RING BUFFER
> +  |page  |-------------------+
> +  +------+                   v
> +    |             +---+   +---+   +---+
> +    |             |   |-->|   |-->|   |
> +    |             |   |<--|   |<--|   |<-+
> +    |             +---+   +---+   +---+  |
> +    |              ^ |             ^ |   |
> +    |              | +-------------+ |   |
> +    |              +-----------------+   |
> +    +------------------------------------+
> +
> +  +------+
> +  |reader|          RING BUFFER
> +  |page  |-------------------+
> +  +------+ <---------------+ v
> +    |  ^          +---+   +---+   +---+
> +    |  |          |   |-->|   |-->|   |
> +    |  |          |   |<--|   |<--|   |<-+
> +    |  |          +---+   +---+   +---+  |
> +    |  |             |             ^ |   |
> +    |  |             +-------------+ |   |
> +    |  +-----------------------------+   |
> +    +------------------------------------+
> +
> +  +------+
> +  |buffer|          RING BUFFER
> +  |page  |-------------------+
> +  +------+ <---------------+ v
> +    |  ^          +---+   +---+   +---+
> +    |  |          |   |   |   |-->|   |
> +    |  |  New     |   |   |   |<--|   |<-+
> +    |  | Reader   +---+   +---+   +---+  |
> +    |  |  page ----^                 |   |
> +    |  |                             |   |
> +    |  +-----------------------------+   |
> +    +------------------------------------+
> +
> +
> +
> +It is possible that the page swapped is the commit page and the tail page,
> +if what is in the ring buffer is less than what is held in a buffer page.
> +
> +
> +          reader page    commit page   tail page
> +              |              |             |
> +              v              |             |
> +             +---+           |             |
> +             |   |<----------+             |
> +             |   |<------------------------+
> +             |   |------+
> +             +---+      |
> +                        |
> +                        v
> +    +---+    +---+    +---+    +---+
> +<---|   |--->|   |--->|   |--->|   |--->
> +--->|   |<---|   |<---|   |<---|   |<---
> +    +---+    +---+    +---+    +---+
> +
> +This case is still legal for this algorithm.
> +When the writer leaves the page, it simply goes into the ring buffer
> +since the reader page still points to the next location in the ring
> +buffer.
> +
> +
> +The main pointers:
> +
> +  reader page - The page used solely by the reader and is not part
> +                of the ring buffer (may be swapped in)
> +
> +  head page - the next page in the ring buffer that will be swapped
> +              with the reader page.
> +
> +  tail page - the page where the next write will take place.
> +
> +  commit page - the page that last finished a write.
> +
> +The commit page only is updated by the outer most writer in the
> +writer stack. A writer that preempts another writer will not move the
> +commit page.
> +
> +When data is written into the ring buffer, a position is reserved
> +in the ring buffer and passed back to the writer. When the writer
> +is finished writing data into that position, it commits the write.
> +
> +Another write (or a read) may take place at anytime during this
> +transaction. If another write happens it must finish before continuing
> +with the previous write.
> +
> +
> +   Write reserve:
> +
> +       Buffer page
> +      +---------+
> +      |written  |
> +      +---------+  <--- given back to writer (current commit)
> +      |reserved |
> +      +---------+ <--- tail pointer
> +      | empty   |
> +      +---------+
> +
> +   Write commit:
> +
> +       Buffer page
> +      +---------+
> +      |written  |
> +      +---------+
> +      |written  |
> +      +---------+  <--- next positon for write (current commit)
> +      | empty   |
> +      +---------+
> +
> +
> + If a write happens after the first reserve:
> +
> +       Buffer page
> +      +---------+
> +      |written  |
> +      +---------+  <-- current commit
> +      |reserved |
> +      +---------+  <--- given back to second writer
> +      |reserved |
> +      +---------+ <--- tail pointer
> +
> +  After second writer commits:
> +
> +
> +       Buffer page
> +      +---------+
> +      |written  |
> +      +---------+  <--(last full commit)
> +      |reserved |
> +      +---------+
> +      |pending  |
> +      |commit   |
> +      +---------+ <--- tail pointer
> +
> +  When the first writer commits:
> +
> +       Buffer page
> +      +---------+
> +      |written  |
> +      +---------+
> +      |written  |
> +      +---------+
> +      |written  |
> +      +---------+  <--(last full commit and tail pointer)
> +
> +
> +The commit pointer points to the last write location that was
> +committed without preempting another write. When a write that
> +preempted another write is committed, it only becomes a pending commit
> +and will not be a full commit till all writes have been committed.
> +
> +The commit page points to the page that has the last full commit.
> +The tail page points to the page with the last write (before
> +committing).
> +
> +The tail page is always equal to or after the commit page. It may
> +be several pages ahead. If the tail page catches up to the commit
> +page then no more writes may take place (regardless of the mode
> +of the ring buffer: overwrite and produce/consumer).
> +
> +The order of pages are:
> +
> + head page
> + commit page
> + tail page
> +
> +Possible scenario:
> +                             tail page
> +  head page         commit page  |
> +      |                 |        |
> +      v                 v        v
> +    +---+    +---+    +---+    +---+
> +<---|   |--->|   |--->|   |--->|   |--->
> +--->|   |<---|   |<---|   |<---|   |<---
> +    +---+    +---+    +---+    +---+
> +
> +There is a special case that the head page is after either the commit page
> +and possibly the tail page. That is when the commit (and tail) page has been
> +swapped with the reader page. This is because the head page is always
> +part of the ring buffer, but the reader page is not. When ever there
> +has been less than a full page that has been committed inside the ring buffer,
> +and a reader swaps out a page, it will be swapping out the commit page.
> +
> +
> +          reader page    commit page   tail page
> +              |              |             |
> +              v              |             |
> +             +---+           |             |
> +             |   |<----------+             |
> +             |   |<------------------------+
> +             |   |------+
> +             +---+      |
> +                        |
> +                        v
> +    +---+    +---+    +---+    +---+
> +<---|   |--->|   |--->|   |--->|   |--->
> +--->|   |<---|   |<---|   |<---|   |<---
> +    +---+    +---+    +---+    +---+
> +                        ^
> +                        |
> +                    head page
> +
> +
> +In this case, the head page will not move when the tail and commit
> +move back into the ring buffer.
> +
> +The reader can not swap a page into the ring buffer if the commit page
> +is still on that page. If the read meets the last commit (real commit
> +not pending or reserved), then there is nothing more to read.
> +The buffer is considered empty until another full commit finishes.
> +
> +When the tail meets the head page, if the buffer is in overwrite mode,
> +the head page will be pushed ahead one. If the buffer is in producer/consumer
> +mode, the write will fail.
> +
> +Overwrite mode:
> +
> +            tail page
> +               |
> +               v
> +    +---+    +---+    +---+    +---+
> +<---|   |--->|   |--->|   |--->|   |--->
> +--->|   |<---|   |<---|   |<---|   |<---
> +    +---+    +---+    +---+    +---+
> +                        ^
> +                        |
> +                    head page
> +
> +
> +            tail page
> +               |
> +               v
> +    +---+    +---+    +---+    +---+
> +<---|   |--->|   |--->|   |--->|   |--->
> +--->|   |<---|   |<---|   |<---|   |<---
> +    +---+    +---+    +---+    +---+
> +                                 ^
> +                                 |
> +                             head page
> +
> +
> +                    tail page
> +                        |
> +                        v
> +    +---+    +---+    +---+    +---+
> +<---|   |--->|   |--->|   |--->|   |--->
> +--->|   |<---|   |<---|   |<---|   |<---
> +    +---+    +---+    +---+    +---+
> +                                 ^
> +                                 |
> +                             head page
> +
> +Note, the reader page will still point to the previous head page.
> +But when a swap takes place, it will use the most recent head page.
> +
> +
> +Making the Ring Buffer Lockless:
> +--------------------------------
> +
> +The main idea behind the lockless algorithm is to combine the moving
> +of the head_page pointer with the swapping of pages with the reader.


Curious: how was it done before? There was a spinlock which protected
the head_page access between the reader and writers?


> +State flags are placed inside the pointer to the page. To do this,
> +each page must be aligned in memory by 4 bytes. This will allow the 2
> +least significant bits of the address to be used as flags. Since
> +they will always be zero for the address. To get the address,
> +simply mask out the flags.
> +
> +  MASK = ~3
> +
> +  address & MASK
> +
> +Two flags will be kept by these two bits:
> +
> +   HEADER - the page being pointed to is a head page
> +
> +   UPDATE - the page being pointed to is being updated by a writer
> +          and was or is about to be a head page.
> +
> +
> +          reader page
> +              |
> +              v
> +             +---+
> +             |   |------+
> +             +---+      |
> +                        |
> +                        v
> +    +---+    +---+    +---+    +---+
> +<---|   |--->|   |-H->|   |--->|   |--->
> +--->|   |<---|   |<---|   |<---|   |<---
> +    +---+    +---+    +---+    +---+
> +
> +
> +The above pointer "-H->" would have the HEADER flag set. That is
> +the next page is the next page to be swapped out by the reader.
> +This pointer means the next page is the head page.
> +
> +When the tail page meets the head pointer, it will use cmpxchg to
> +change the pointer to the UPDATE state:
> +
> +
> +            tail page
> +               |
> +               v
> +    +---+    +---+    +---+    +---+
> +<---|   |--->|   |-H->|   |--->|   |--->
> +--->|   |<---|   |<---|   |<---|   |<---
> +    +---+    +---+    +---+    +---+
> +
> +            tail page
> +               |
> +               v
> +    +---+    +---+    +---+    +---+
> +<---|   |--->|   |-U->|   |--->|   |--->
> +--->|   |<---|   |<---|   |<---|   |<---
> +    +---+    +---+    +---+    +---+
> +
> +"-U->" represents a pointer in the UPDATE state.
> +
> +Any access to the reader will need to take some sort of lock to serialize
> +the readers. But the writers will never take a lock to write to the
> +ring buffer. This means we only need to worry about a single reader,
> +and writes only preempt in "stack" formation.
> +
> +When the reader tries to swap the page with the ring buffer, it
> +will also use cmpxchg. If the flag bit in the pointer to the
> +head page does not have the HEADER flag set, the compare will fail
> +and the reader will need to look for the new head page and try again.
> +Note, the flag UPDATE and HEADER are never set at the same time.
> +
> +The reader swaps the reader page as follows:
> +
> +  +------+
> +  |reader|          RING BUFFER
> +  |page  |
> +  +------+
> +                  +---+    +---+    +---+
> +                  |   |--->|   |--->|   |
> +                  |   |<---|   |<---|   |
> +                  +---+    +---+    +---+
> +                   ^ |               ^ |
> +                   | +---------------+ |
> +                   +-----H-------------+
> +
> +The reader sets the reader page next pointer as HEADER to the page after
> +the head page.
> +
> +
> +  +------+
> +  |reader|          RING BUFFER
> +  |page  |-------H-----------+
> +  +------+                   v
> +    |             +---+    +---+    +---+
> +    |             |   |--->|   |--->|   |
> +    |             |   |<---|   |<---|   |<-+
> +    |             +---+    +---+    +---+  |
> +    |              ^ |               ^ |   |
> +    |              | +---------------+ |   |
> +    |              +-----H-------------+   |
> +    +--------------------------------------+
> +
> +It does a cmpxchg with the pointer to the previous head page to make it
> +point to the reader page. Note that the new pointer does not have the HEADER
> +flag set.  This action atomically moves the head page forward.
> +
> +  +------+
> +  |reader|          RING BUFFER
> +  |page  |-------H-----------+
> +  +------+ <---------------+ v



Ah, you have set the prev pointer of the new header page
to point to the new reader page. It seems too soon.
You are actually doing it in the next stage which you
describe below, right?




> +    |  ^          +---+   +---+   +---+
> +    |  |          |   |-->|   |-->|   |
> +    |  |          |   |<--|   |<--|   |<-+
> +    |  |          +---+   +---+   +---+  |
> +    |  |             |             ^ |   |
> +    |  |             +-------------+ |   |
> +    |  +-----------------------------+   |
> +    +------------------------------------+
> +
> +After the new head page is set, the previous pointer of the head page is
> +updated to the reader page.
> +
> +  +------+
> +  |reader|          RING BUFFER
> +  |page  |-------H-----------+
> +  +------+                   v
> +    |  ^          +---+   +---+   +---+
> +    |  |          |   |-->|   |-->|   |
> +    |  |          |   |<--|   |<--|   |<-+
> +    |  |          +---+   +---+   +---+  |
> +    |  |             |             ^ |   |
> +    |  |             +-------------+ |   |
> +    |  +-----------------------------+   |
> +    +------------------------------------+
> +
> +  +------+
> +  |buffer|          RING BUFFER
> +  |page  |-------H-----------+  <--- New head page
> +  +------+ <---------------+ v
> +    |  ^          +---+   +---+   +---+
> +    |  |          |   |   |   |-->|   |
> +    |  |  New     |   |   |   |<--|   |<-+
> +    |  | Reader   +---+   +---+   +---+  |
> +    |  |  page ----^                 |   |
> +    |  |                             |   |
> +    |  +-----------------------------+   |
> +    +------------------------------------+
> +
> +Another important point. The page that the reader page points back to
> +by its previous pointer (the one that now points to the new head page)
> +never points back to the reader page. That is because the reader page is
> +not part of the ring buffer. Traversing the ring buffer via the next pointers
> +will always stay in the ring buffer. Traversing the ring buffer via the
> +prev pointers may not.
> +
> +Note, the way to determine a reader page is simply by examining the previous
> +pointer of the page. If the next pointer of the previous page does not
> +point back to the original page, then the original page is a reader page:
> +
> +                                  
> +             +--------+
> +             | reader |  next   +----+
> +             |  page  |-------->|    |<====== (buffer page)
> +             +--------+         +----+
> +                 |                | ^
> +                 |                v | next
> +            prev |              +----+
> +                 +------------->|    |
> +                                +----+
> +
> +The way the head page moves forward:
> +
> +When the tail page meets the head page and the buffer is in overwrite mode
> +and more writes take place, the head page must be moved forward before the
> +writer may move the tail page. The way this is done is that the writer
> +performs a cmpxchg to convert the pointer to the head page from the HEADER
> +flag to have the UPDATE flag set. Once this is done, the reader will
> +not be able to swap the head page from the buffer, nor will it be able to
> +move the head page, until the writer is finished with the move.
> +
> +This eliminates any races that the reader can have on the writer. The reader
> +must spin, and this is why the reader can not preempt the writer.
> +
> +            tail page
> +               |
> +               v
> +    +---+    +---+    +---+    +---+
> +<---|   |--->|   |-H->|   |--->|   |--->
> +--->|   |<---|   |<---|   |<---|   |<---
> +    +---+    +---+    +---+    +---+
> +
> +            tail page
> +               |
> +               v
> +    +---+    +---+    +---+    +---+
> +<---|   |--->|   |-U->|   |--->|   |--->
> +--->|   |<---|   |<---|   |<---|   |<---
> +    +---+    +---+    +---+    +---+
> +
> +The following page will be made into the new head page.
> +
> +           tail page
> +               |
> +               v
> +    +---+    +---+    +---+    +---+
> +<---|   |--->|   |-U->|   |-H->|   |--->
> +--->|   |<---|   |<---|   |<---|   |<---
> +    +---+    +---+    +---+    +---+
> +
> +After the new head page has been set, we can set the old head page
> +pointer back to NORMAL.
> +
> +           tail page
> +               |
> +               v
> +    +---+    +---+    +---+    +---+
> +<---|   |--->|   |--->|   |-H->|   |--->
> +--->|   |<---|   |<---|   |<---|   |<---
> +    +---+    +---+    +---+    +---+



What happens between the time H is turned into U and U is cleared back
to N? Does the reader directly tries to find ahead the next page pointer
which have the H flag, or does it spin on U before doing this?


> +
> +After the head page has been moved, the tail page may now move forward.
> +
> +                    tail page
> +                        |
> +                        v
> +    +---+    +---+    +---+    +---+
> +<---|   |--->|   |--->|   |-H->|   |--->
> +--->|   |<---|   |<---|   |<---|   |<---
> +    +---+    +---+    +---+    +---+
> +
> +
> +The above are the trivial updates. Now for the more complex scenarios.
> +
> +
> +As stated before, if enough writes preempt the first write, the
> +tail page may make it all the way around the buffer and meet the commit
> +page. At this time, we must start dropping writes (usually with some kind
> +of warning to the user). But what happens if the commit was still on the
> +reader page? The commit page is not part of the ring buffer. The tail page
> +must account for this.
> +
> +
> +          reader page    commit page
> +              |              |
> +              v              |
> +             +---+           |
> +             |   |<----------+
> +             |   |
> +             |   |------+
> +             +---+      |
> +                        |
> +                        v
> +    +---+    +---+    +---+    +---+
> +<---|   |--->|   |-H->|   |--->|   |--->
> +--->|   |<---|   |<---|   |<---|   |<---
> +    +---+    +---+    +---+    +---+
> +               ^
> +               |
> +           tail page
> +
> +If the tail page were to simply push the head page forward, the commit when
> +leaving the reader page would not be pointing to the correct page.



So if I understand well the problem at this point, imagine that the tail
push the head page forward, it would set H to U and then set the next pointer
of the next page to H.

The problem here is that the reader page may then find the next page with
a H pointer and swap itself with this new head page, then the commit pointer would
only commit one page whereas all the buffer should be committed, right?

Thanks,
Frederic (and his silly questions :)


> +The solution to this is to test if the commit page is on the reader page
> +before pushing the head page. If it is, then it can be assumed that the
> +tail page wrapped the buffer, and we must drop new writes.
> +
> +This is not a race condition, because the commit page can only be moved
> +by the outter most writer (the writer that was preempted).
> +This means that the commit will not move while a writer is moving the
> +tail page. The reader can not swap the reader page if it is also being
> +used as the commit page. The reader can simply check that the commit
> +is off the reader page. Once the commit page leaves the reader page
> +it will never go back on it unless a reader does another swap with the
> +buffer page that is also the commit page.
> +
> +
> +Nested writes
> +-------------
> +
> +In the pushing forward of the tail page we must first push forward
> +the head page if the head page is the next page. If the head page
> +is not the next page, the tail page is simply updated with a cmpxchg.
> +
> +Only writers move the tail page. This must be done atomically to protect
> +against nested writers.
> +
> +  temp_page = tail_page
> +  next_page = temp_page->next
> +  cmpxchg(tail_page, temp_page, next_page)
> +
> +The above will update the tail page if it is still pointing to the expected
> +page. If this fails, a nested write pushed it forward, the the current write
> +does not need to push it.
> +
> +
> +           temp page
> +               |
> +               v
> +            tail page
> +               |
> +               v
> +    +---+    +---+    +---+    +---+
> +<---|   |--->|   |--->|   |--->|   |--->
> +--->|   |<---|   |<---|   |<---|   |<---
> +    +---+    +---+    +---+    +---+
> +
> +Nested write comes in and moves the tail page forward:
> +
> +                    tail page (moved by nested writer)
> +            temp page   |
> +               |        |
> +               v        v
> +    +---+    +---+    +---+    +---+
> +<---|   |--->|   |--->|   |--->|   |--->
> +--->|   |<---|   |<---|   |<---|   |<---
> +    +---+    +---+    +---+    +---+
> +
> +The above would fail the cmpxchg, but since the tail page has already
> +been moved forward, the writer will just try again to reserve storage
> +on the new tail page.
> +
> +But the moving of the head page is a bit more complex.
> +
> +            tail page
> +               |
> +               v
> +    +---+    +---+    +---+    +---+
> +<---|   |--->|   |-H->|   |--->|   |--->
> +--->|   |<---|   |<---|   |<---|   |<---
> +    +---+    +---+    +---+    +---+
> +
> +The write converts the head page pointer to UPDATE.
> +
> +            tail page
> +               |
> +               v
> +    +---+    +---+    +---+    +---+
> +<---|   |--->|   |-U->|   |--->|   |--->
> +--->|   |<---|   |<---|   |<---|   |<---
> +    +---+    +---+    +---+    +---+
> +
> +But if a nested writer preempts here. It will see that the next
> +page is a head page, but it is also nested. It will detect that
> +it is nested and will save that information. The detection is the
> +fact that it sees the UPDATE flag instead of a HEADER or NORMAL
> +pointer.
> +
> +The nested writer will set the new head page pointer.
> +
> +           tail page
> +               |
> +               v
> +    +---+    +---+    +---+    +---+
> +<---|   |--->|   |-U->|   |-H->|   |--->
> +--->|   |<---|   |<---|   |<---|   |<---
> +    +---+    +---+    +---+    +---+
> +
> +But it will not reset the update back to normal. Only the writer
> +that converted a pointer from HEAD to UPDATE will convert it back
> +to NORMAL.
> +
> +                    tail page
> +                        |
> +                        v
> +    +---+    +---+    +---+    +---+
> +<---|   |--->|   |-U->|   |-H->|   |--->
> +--->|   |<---|   |<---|   |<---|   |<---
> +    +---+    +---+    +---+    +---+
> +
> +After the nested writer finishes, the outer most writer will convert
> +the UPDATE pointer to NORMAL.
> +
> +
> +                    tail page
> +                        |
> +                        v
> +    +---+    +---+    +---+    +---+
> +<---|   |--->|   |--->|   |-H->|   |--->
> +--->|   |<---|   |<---|   |<---|   |<---
> +    +---+    +---+    +---+    +---+
> +
> +
> +It can be even more complex if several nested writes came in and moved
> +the tail page ahead several pages:
> +
> +
> +(first writer)
> +
> +            tail page
> +               |
> +               v
> +    +---+    +---+    +---+    +---+
> +<---|   |--->|   |-H->|   |--->|   |--->
> +--->|   |<---|   |<---|   |<---|   |<---
> +    +---+    +---+    +---+    +---+
> +
> +The write converts the head page pointer to UPDATE.
> +
> +            tail page
> +               |
> +               v
> +    +---+    +---+    +---+    +---+
> +<---|   |--->|   |-U->|   |--->|   |--->
> +--->|   |<---|   |<---|   |<---|   |<---
> +    +---+    +---+    +---+    +---+
> +
> +Next writer comes in, and sees the update and sets up the new
> +head page.
> +
> +(second writer)
> +
> +           tail page
> +               |
> +               v
> +    +---+    +---+    +---+    +---+
> +<---|   |--->|   |-U->|   |-H->|   |--->
> +--->|   |<---|   |<---|   |<---|   |<---
> +    +---+    +---+    +---+    +---+
> +
> +The nested writer moves the tail page forward. But does not set the old
> +update page to NORMAL because it is not the outer most writer.
> +
> +                    tail page
> +                        |
> +                        v
> +    +---+    +---+    +---+    +---+
> +<---|   |--->|   |-U->|   |-H->|   |--->
> +--->|   |<---|   |<---|   |<---|   |<---
> +    +---+    +---+    +---+    +---+
> +
> +Another writer preempts and sees the page after the tail page is a head page.
> +It changes it from HEAD to UPDATE.
> +
> +(third writer)
> +
> +                    tail page
> +                        |
> +                        v
> +    +---+    +---+    +---+    +---+
> +<---|   |--->|   |-U->|   |-U->|   |--->
> +--->|   |<---|   |<---|   |<---|   |<---
> +    +---+    +---+    +---+    +---+
> +
> +The writer will move the head page forward:
> +
> +
> +(third writer)
> +
> +                    tail page
> +                        |
> +                        v
> +    +---+    +---+    +---+    +---+
> +<---|   |--->|   |-U->|   |-U->|   |-H->
> +--->|   |<---|   |<---|   |<---|   |<---
> +    +---+    +---+    +---+    +---+
> +
> +But now that the third writer did change the HEAD flag to UPDATE it
> +will convert it to normal:
> +
> +
> +(third writer)
> +
> +                    tail page
> +                        |
> +                        v
> +    +---+    +---+    +---+    +---+
> +<---|   |--->|   |-U->|   |--->|   |-H->
> +--->|   |<---|   |<---|   |<---|   |<---
> +    +---+    +---+    +---+    +---+
> +
> +
> +Then it will move the tail page, and return back to the second writer.
> +
> +
> +(second writer)
> +
> +                             tail page
> +                                 |
> +                                 v
> +    +---+    +---+    +---+    +---+
> +<---|   |--->|   |-U->|   |--->|   |-H->
> +--->|   |<---|   |<---|   |<---|   |<---
> +    +---+    +---+    +---+    +---+
> +
> +
> +The second writer will fail to move the tail page because it was already
> +moved, so it will try again and add its data to the new tail page.
> +It will return to the first writer.
> +
> +
> +(first writer)
> +
> +                             tail page
> +                                 |
> +                                 v
> +    +---+    +---+    +---+    +---+
> +<---|   |--->|   |-U->|   |--->|   |-H->
> +--->|   |<---|   |<---|   |<---|   |<---
> +    +---+    +---+    +---+    +---+
> +
> +The first writer can not know atomically test if the tail page moved
> +while it updates the HEAD page. It will then update the head page to
> +what it thinks is the new head page.
> +
> +
> +(first writer)
> +
> +                             tail page
> +                                 |
> +                                 v
> +    +---+    +---+    +---+    +---+
> +<---|   |--->|   |-U->|   |-H->|   |-H->
> +--->|   |<---|   |<---|   |<---|   |<---
> +    +---+    +---+    +---+    +---+
> +
> +Since the cmpxchg returns the old value of the pointer the first writer
> +will see it succeeded in updating the pointer from NORMAL to HEAD.
> +But as we can see, this is not good enough. It must also check to see
> +if the tail page is either where it use to be or on the next page:
> +
> +
> +(first writer)
> +
> +               A        B    tail page
> +               |        |        |
> +               v        v        v
> +    +---+    +---+    +---+    +---+
> +<---|   |--->|   |-U->|   |-H->|   |-H->
> +--->|   |<---|   |<---|   |<---|   |<---
> +    +---+    +---+    +---+    +---+
> +
> +If tail page != A and tail page does not equal B, then it must reset the
> +pointer back to NORMAL. The fact that it only needs to worry about
> +nested writers, it only needs to check this after setting the HEAD page.
> +
> +
> +(first writer)
> +
> +               A        B    tail page
> +               |        |        |
> +               v        v        v
> +    +---+    +---+    +---+    +---+
> +<---|   |--->|   |-U->|   |--->|   |-H->
> +--->|   |<---|   |<---|   |<---|   |<---
> +    +---+    +---+    +---+    +---+
> +
> +Now the writer can update the head page. This is also why the head page must
> +remain in UPDATE and only reset by the outer most writer. This prevents
> +the reader from seeing the incorrect head page.
> +
> +
> +(first writer)
> +
> +               A        B    tail page
> +               |        |        |
> +               v        v        v
> +    +---+    +---+    +---+    +---+
> +<---|   |--->|   |--->|   |--->|   |-H->
> +--->|   |<---|   |<---|   |<---|   |<---
> +    +---+    +---+    +---+    +---+
> +
> -- 
> 1.6.3.1
> 
> -- 


^ permalink raw reply	[flat|nested] 29+ messages in thread

end of thread, other threads:[~2009-06-15  0:56 UTC | newest]

Thread overview: 29+ messages (download: mbox.gz / follow: Atom feed)
-- links below jump to the message on this page --
2009-06-10 19:53 [PATCH 0/3] [GIT PULL][for 2.6.32] lockless ring buffer Steven Rostedt
2009-06-10 19:53 ` [PATCH 1/3] ring-buffer: make the buffer a true circular link list Steven Rostedt
2009-06-11  1:12   ` Lai Jiangshan
2009-06-11  2:00     ` Steven Rostedt
2009-06-11  3:25       ` Lai Jiangshan
2009-06-11  3:35         ` Steven Rostedt
2009-06-10 19:53 ` [PATCH 2/3] ring-buffer: make lockless Steven Rostedt
2009-06-10 19:53 ` [PATCH 3/3] ring-buffer: add design document Steven Rostedt
2009-06-10 22:13   ` Mathieu Desnoyers
2009-06-11  1:55     ` Steven Rostedt
2009-06-11  3:51       ` Mathieu Desnoyers
2009-06-11  3:59         ` Mathieu Desnoyers
2009-06-11  4:15           ` Steven Rostedt
2009-06-11 18:09             ` Mathieu Desnoyers
2009-06-11  0:51   ` Huang Ying
2009-06-11  0:54     ` H. Peter Anvin
2009-06-11  1:58     ` Steven Rostedt
2009-06-11  2:33       ` Huang Ying
2009-06-11  2:38         ` Mathieu Desnoyers
2009-06-12  3:13           ` Huang Ying
2009-06-12  3:46             ` H. Peter Anvin
2009-06-11  3:15   ` Hidetoshi Seto
2009-06-11  3:25     ` Steven Rostedt
2009-06-13  1:54   ` Frederic Weisbecker
2009-06-13  2:16     ` Steven Rostedt
2009-06-13 22:36       ` Frederic Weisbecker
2009-06-14 12:39         ` Steven Rostedt
2009-06-15  0:05           ` Frederic Weisbecker
2009-06-15  0:56   ` Frederic Weisbecker

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox;
as well as URLs for NNTP newsgroup(s).