summaryrefslogtreecommitdiffstats
path: root/lib
diff options
context:
space:
mode:
authorAhmad Fatoum <a.fatoum@pengutronix.de>2023-11-22 18:29:33 +0100
committerSascha Hauer <s.hauer@pengutronix.de>2023-11-23 15:45:54 +0100
commitb686114ba03d9d6a222ca21384ea8534f77a1af4 (patch)
tree1bc7fa16b229b2d6a216e6aa77e2c2e8fd7f6631 /lib
parentc7710eefb960f08f8d812ce69b8aead786bb866b (diff)
downloadbarebox-b686114ba03d9d6a222ca21384ea8534f77a1af4.tar.gz
barebox-b686114ba03d9d6a222ca21384ea8534f77a1af4.tar.xz
include: add linux/refcount.h
For complex interactions, especially in communication protocols, it can be beneficial to keep the reference counts used in the Linux drivers as is to avoid resource leaks or use-after-frees. Provide a simplified kref and refcount API to facilitate this. Signed-off-by: Ahmad Fatoum <a.fatoum@pengutronix.de> Link: https://lore.barebox.org/20231122172951.376531-3-a.fatoum@pengutronix.de Signed-off-by: Sascha Hauer <s.hauer@pengutronix.de>
Diffstat (limited to 'lib')
-rw-r--r--lib/Makefile1
-rw-r--r--lib/refcount.c34
2 files changed, 35 insertions, 0 deletions
diff --git a/lib/Makefile b/lib/Makefile
index 791080b2d1..3e476a2c04 100644
--- a/lib/Makefile
+++ b/lib/Makefile
@@ -70,6 +70,7 @@ obj-$(CONFIG_BAREBOX_LOGO) += logo/
obj-y += reed_solomon/
obj-$(CONFIG_RATP) += ratp.o
obj-y += list_sort.o
+obj-y += refcount.o
obj-y += int_sqrt.o
obj-y += parseopt.o
obj-y += clz_ctz.o
diff --git a/lib/refcount.c b/lib/refcount.c
new file mode 100644
index 0000000000..8c6f98b480
--- /dev/null
+++ b/lib/refcount.c
@@ -0,0 +1,34 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * Out-of-line refcount functions.
+ */
+
+#include <linux/refcount.h>
+#include <linux/printk.h>
+
+#define REFCOUNT_WARN(str) WARN_ONCE(1, "refcount_t: " str ".\n")
+
+void refcount_warn_saturate(refcount_t *r, enum refcount_saturation_type t)
+{
+ refcount_set(r, REFCOUNT_SATURATED);
+
+ switch (t) {
+ case REFCOUNT_ADD_NOT_ZERO_OVF:
+ REFCOUNT_WARN("saturated; leaking memory");
+ break;
+ case REFCOUNT_ADD_OVF:
+ REFCOUNT_WARN("saturated; leaking memory");
+ break;
+ case REFCOUNT_ADD_UAF:
+ REFCOUNT_WARN("addition on 0; use-after-free");
+ break;
+ case REFCOUNT_SUB_UAF:
+ REFCOUNT_WARN("underflow; use-after-free");
+ break;
+ case REFCOUNT_DEC_LEAK:
+ REFCOUNT_WARN("decrement hit 0; leaking memory");
+ break;
+ default:
+ REFCOUNT_WARN("unknown saturation event!?");
+ }
+}