RCU lock-free stack: don't hold read lock across retry
[urcu.git] / urcu / rculfstack.h
1 /*
2 * rculfstack.h
3 *
4 * Userspace RCU library - Lock-Free RCU Stack
5 *
6 * Copyright 2010 - Mathieu Desnoyers <mathieu.desnoyers@efficios.com>
7 *
8 * This library is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU Lesser General Public
10 * License as published by the Free Software Foundation; either
11 * version 2.1 of the License, or (at your option) any later version.
12 *
13 * This library is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 * Lesser General Public License for more details.
17 *
18 * You should have received a copy of the GNU Lesser General Public
19 * License along with this library; if not, write to the Free Software
20 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21 */
22
23 #if (!defined(_GNU_SOURCE) && !defined(_LGPL_SOURCE))
24 #error "Dynamic loader LGPL wrappers not implemented yet"
25 #endif
26
27 struct rcu_lfs_node {
28 struct rcu_lfs_node *next;
29 };
30
31 struct rcu_lfs_stack {
32 struct rcu_lfs_node *head;
33 };
34
35 void rcu_lfs_node_init(struct rcu_lfs_node *node)
36 {
37 }
38
39 void rcu_lfs_init(struct rcu_lfs_stack *s)
40 {
41 s->head = NULL;
42 }
43
44 void rcu_lfs_push(struct rcu_lfs_stack *s, struct rcu_lfs_node *node)
45 {
46 for (;;) {
47 struct rcu_lfs_node *head;
48
49 rcu_read_lock();
50 head = rcu_dereference(s->head);
51 node->next = head;
52 /*
53 * uatomic_cmpxchg() implicit memory barrier orders earlier
54 * stores to node before publication.
55 */
56 if (uatomic_cmpxchg(&s->head, head, node) == head) {
57 rcu_read_unlock();
58 return;
59 } else {
60 /* Failure to prepend. Retry. */
61 rcu_read_unlock();
62 continue;
63 }
64 }
65 }
66
67 /*
68 * The caller must wait for a grace period to pass before freeing the returned
69 * node.
70 * Returns NULL if stack is empty.
71 */
72 struct rcu_lfs_node *
73 rcu_lfs_pop(struct rcu_lfs_stack *s)
74 {
75 for (;;) {
76 struct rcu_lfs_node *head;
77
78 rcu_read_lock();
79 head = rcu_dereference(s->head);
80 if (head) {
81 struct rcu_lfs_node *next = rcu_dereference(head->next);
82
83 if (uatomic_cmpxchg(&s->head, head, next) == head) {
84 rcu_read_unlock();
85 return head;
86 } else {
87 /* Concurrent modification. Retry. */
88 rcu_read_unlock();
89 continue;
90 }
91 } else {
92 /* Empty stack */
93 rcu_read_unlock();
94 return NULL;
95 }
96 }
97 }
This page took 0.03124 seconds and 5 git commands to generate.