| 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 | rcu_read_lock(); |
| 47 | for (;;) { |
| 48 | struct rcu_lfs_node *head = rcu_dereference(s->head); |
| 49 | |
| 50 | node->next = head; |
| 51 | /* |
| 52 | * uatomic_cmpxchg() implicit memory barrier orders earlier |
| 53 | * stores to node before publication. |
| 54 | */ |
| 55 | if (uatomic_cmpxchg(&s->head, head, node) == head) { |
| 56 | rcu_read_unlock(); |
| 57 | return; |
| 58 | } else { |
| 59 | /* Failure to prepend. Retry. */ |
| 60 | continue; |
| 61 | } |
| 62 | } |
| 63 | } |
| 64 | |
| 65 | /* |
| 66 | * The caller must wait for a grace period to pass before freeing the returned |
| 67 | * node. |
| 68 | * Returns NULL if stack is empty. |
| 69 | */ |
| 70 | struct rcu_lfs_node * |
| 71 | rcu_lfs_pop(struct rcu_lfs_stack *s) |
| 72 | { |
| 73 | rcu_read_lock(); |
| 74 | for (;;) { |
| 75 | struct rcu_lfs_node *head = rcu_dereference(s->head); |
| 76 | |
| 77 | if (head) { |
| 78 | struct rcu_lfs_node *next = rcu_dereference(head->next); |
| 79 | |
| 80 | if (uatomic_cmpxchg(&s->head, head, next) == head) { |
| 81 | rcu_read_unlock(); |
| 82 | return head; |
| 83 | } else { |
| 84 | /* Concurrent modification. Retry. */ |
| 85 | continue; |
| 86 | } |
| 87 | } else { |
| 88 | /* Empty stack */ |
| 89 | rcu_read_unlock(); |
| 90 | return NULL; |
| 91 | } |
| 92 | } |
| 93 | } |