@@ -12,6 +12,7 @@ please read on.
1212Reference counting on elements of lists which are protected by traditional
1313reader/writer spinlocks or semaphores are straightforward:
1414
15+ CODE LISTING A:
15161. 2.
1617add() search_and_reference()
1718{ {
@@ -28,7 +29,8 @@ add() search_and_reference()
2829release_referenced() delete()
2930{ {
3031 ... write_lock(&list_lock);
31- atomic_dec(&el->rc, relfunc) ...
32+ if(atomic_dec_and_test(&el->rc)) ...
33+ kfree(el);
3234 ... remove_element
3335} write_unlock(&list_lock);
3436 ...
@@ -44,6 +46,7 @@ search_and_reference() could potentially hold reference to an element which
4446has already been deleted from the list/array. Use atomic_inc_not_zero()
4547in this scenario as follows:
4648
49+ CODE LISTING B:
47501. 2.
4851add() search_and_reference()
4952{ {
@@ -79,6 +82,7 @@ search_and_reference() code path. In such cases, the
7982atomic_dec_and_test() may be moved from delete() to el_free()
8083as follows:
8184
85+ CODE LISTING C:
82861. 2.
8387add() search_and_reference()
8488{ {
@@ -114,6 +118,17 @@ element can therefore safely be freed. This in turn guarantees that if
114118any reader finds the element, that reader may safely acquire a reference
115119without checking the value of the reference counter.
116120
121+ A clear advantage of the RCU-based pattern in listing C over the one
122+ in listing B is that any call to search_and_reference() that locates
123+ a given object will succeed in obtaining a reference to that object,
124+ even given a concurrent invocation of delete() for that same object.
125+ Similarly, a clear advantage of both listings B and C over listing A is
126+ that a call to delete() is not delayed even if there are an arbitrarily
127+ large number of calls to search_and_reference() searching for the same
128+ object that delete() was invoked on. Instead, all that is delayed is
129+ the eventual invocation of kfree(), which is usually not a problem on
130+ modern computer systems, even the small ones.
131+
117132In cases where delete() can sleep, synchronize_rcu() can be called from
118133delete(), so that el_free() can be subsumed into delete as follows:
119134
@@ -130,3 +145,7 @@ delete()
130145 kfree(el);
131146 ...
132147}
148+
149+ As additional examples in the kernel, the pattern in listing C is used by
150+ reference counting of struct pid, while the pattern in listing B is used by
151+ struct posix_acl.
0 commit comments