public inbox for linux-kernel@vger.kernel.org
 help / color / mirror / Atom feed
* [PATCH] lib/bsearch: add mutex protection for thread-safe binary search
@ 2025-10-16  9:06 XueBing Chen
  2025-10-16  9:42 ` Kuan-Wei Chiu
                   ` (2 more replies)
  0 siblings, 3 replies; 4+ messages in thread
From: XueBing Chen @ 2025-10-16  9:06 UTC (permalink / raw)
  To: akpm; +Cc: linux-kernel, XueBing Chen

Replace the __inline_bsearch() wrapper with a full implementation
that includes mutex protection to ensure thread safety when
multiple threads call bsearch() concurrently.

The original implementation lacked synchronization, which could
lead to race conditions in multi-threaded environments when
accessing shared arrays or using non-atomic comparison functions.

Signed-off-by: XueBing Chen <chenxb_99091@126.com>
---
 lib/bsearch.c | 29 ++++++++++++++++++++++++++---
 1 file changed, 26 insertions(+), 3 deletions(-)

diff --git a/lib/bsearch.c b/lib/bsearch.c
index bf86aa66f..9a5a2e949 100644
--- a/lib/bsearch.c
+++ b/lib/bsearch.c
@@ -1,9 +1,12 @@
-// SPDX-License-Identifier: GPL-2.0-only
 /*
  * A generic implementation of binary search for the Linux kernel
  *
  * Copyright (C) 2008-2009 Ksplice, Inc.
  * Author: Tim Abbott <tabbott@ksplice.com>
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License as
+ * published by the Free Software Foundation; version 2.
  */
 
 #include <linux/export.h>
@@ -28,9 +31,29 @@
  * the key and elements in the array are of the same type, you can use
  * the same comparison function for both sort() and bsearch().
  */
-void *bsearch(const void *key, const void *base, size_t num, size_t size, cmp_func_t cmp)
+DEFINE_MUTEX(cmp_mutex);
+void *bsearch(const void *key, const void *base, size_t num, size_t size,
+	      int (*cmp)(const void *key, const void *elt))
 {
-	return __inline_bsearch(key, base, num, size, cmp);
+	const char *pivot;
+	int result;
+
+	while (num > 0) {
+		pivot = base + (num >> 1) * size;
+		mutex_lock(&cmp_mutex);
+		result = cmp(key, pivot);
+		mutex_unlock(&cmp_mutex);
+		if (result == 0)
+			return (void *)pivot;
+
+		if (result > 0) {
+			base = pivot + size;
+			num--;
+		}
+		num >>= 1;
+	}
+
+	return NULL;
 }
 EXPORT_SYMBOL(bsearch);
 NOKPROBE_SYMBOL(bsearch);
-- 
2.17.1


^ permalink raw reply related	[flat|nested] 4+ messages in thread

end of thread, other threads:[~2025-10-21  4:47 UTC | newest]

Thread overview: 4+ messages (download: mbox.gz follow: Atom feed
-- links below jump to the message on this page --
2025-10-16  9:06 [PATCH] lib/bsearch: add mutex protection for thread-safe binary search XueBing Chen
2025-10-16  9:42 ` Kuan-Wei Chiu
2025-10-17  7:28 ` kernel test robot
2025-10-21  4:47 ` kernel test robot

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox