]> xenbits.xensource.com Git - unikraft/unikraft.git/commitdiff
include/uk/weak_refcount: Add try acquire op
authorAndrei Tatar <andrei@unikraft.io>
Tue, 24 Sep 2024 14:54:53 +0000 (16:54 +0200)
committerUnikraft Bot <monkey@unikraft.io>
Mon, 10 Feb 2025 10:47:39 +0000 (10:47 +0000)
This change adds a `try_acquire` operation to strong/weak refcounts,
allowing a caller holding a weakref to attempt to acquire a strong ref.
This call may fail if no other strong references exist.

Signed-off-by: Andrei Tatar <andrei@unikraft.io>
Approved-by: Sergiu Moga <sergiu@unikraft.io>
Reviewed-by: Sergiu Moga <sergiu@unikraft.io>
GitHub-Closes: #1579

include/uk/weak_refcount.h

index 0a17bde8ebcb5a3664cbf311c32fce2b1b5c9bed..19200a66d50824c295f50ff48c9c8e507cf18ac6 100644 (file)
@@ -74,6 +74,26 @@ int uk_swrefcount_release_weak(struct uk_swrefcount *sw)
        return uk_refcount_release(&sw->refcount) ? UK_SWREFCOUNT_LAST_REF : 0;
 }
 
+/**
+ * Try to acquire a strong reference on `sw` with only a weak reference held.
+ *
+ * May fail if no other strong references exist.
+ *
+ * @return
+ *  0: Failed to acquire a strong reference
+ *  1: Successfully acquired a strong reference
+ */
+static inline
+int uk_swrefcount_try_acquire(struct uk_swrefcount *sw)
+{
+       uk_swrefcount_acquire_weak(sw);
+       if (!uk_refcount_acquire_if_not_zero(&sw->strong)) {
+               uk_swrefcount_release_weak(sw);
+               return 0;
+       }
+       return 1;
+}
+
 /**
  * Release a strong reference on `sw` and return whether it was the last.
  *
@@ -89,7 +109,11 @@ int uk_swrefcount_release(struct uk_swrefcount *sw)
 
        if (uk_refcount_release(&sw->strong))
                ret |= UK_SWREFCOUNT_LAST_STRONG;
-       return ret | uk_swrefcount_release_weak(sw);
+       if (uk_swrefcount_release_weak(sw)) {
+               UK_ASSERT(ret); /* There cannot be more strong than total ref */
+               ret |= UK_SWREFCOUNT_LAST_REF;
+       }
+       return ret;
 }
 
 #endif /* __UK_WEAK_REFCOUNT_H__ */