diff mbox series

[net-next,3/4] sock_lock: Add try_sock_lock

Message ID 20171222194755.8544-4-tom@quantonium.net
State Superseded, archived
Delegated to: David Miller
Headers show
Series kcm: Fix two locking issues | expand

Commit Message

Tom Herbert Dec. 22, 2017, 7:47 p.m. UTC
try_sock lock is an opportunistic attempt to acquire a socket lock
without blocking or sleeping. If the socket lock is acquired then
true is returned, else false is returned.

Signed-off-by: Tom Herbert <tom@quantonium.net>
---
 include/net/sock.h |  7 +++++++
 net/core/sock.c    | 20 ++++++++++++++++++++
 2 files changed, 27 insertions(+)
diff mbox series

Patch

diff --git a/include/net/sock.h b/include/net/sock.h
index 3b4ca2046f8c..69fdd1a89591 100644
--- a/include/net/sock.h
+++ b/include/net/sock.h
@@ -1462,6 +1462,13 @@  static inline void lock_sock(struct sock *sk)
 	lock_sock_nested(sk, 0);
 }
 
+bool try_lock_sock_nested(struct sock *sk, int subclass);
+
+static inline bool try_lock_sock(struct sock *sk)
+{
+	return try_lock_sock_nested(sk, 0);
+}
+
 void release_sock(struct sock *sk);
 
 /* BH context may only use the following locking interface. */
diff --git a/net/core/sock.c b/net/core/sock.c
index 72d14b221784..40fb772e2d52 100644
--- a/net/core/sock.c
+++ b/net/core/sock.c
@@ -2782,6 +2782,26 @@  void lock_sock_nested(struct sock *sk, int subclass)
 }
 EXPORT_SYMBOL(lock_sock_nested);
 
+bool try_lock_sock_nested(struct sock *sk, int subclass)
+{
+	spin_lock_bh(&sk->sk_lock.slock);
+	if (sk->sk_lock.owned) {
+		spin_unlock_bh(&sk->sk_lock.slock);
+		return false;
+	}
+
+	sk->sk_lock.owned = 1;
+	spin_unlock(&sk->sk_lock.slock);
+
+	/* The sk_lock has mutex_lock() semantics here: */
+
+	mutex_acquire(&sk->sk_lock.dep_map, subclass, 0, _RET_IP_);
+	local_bh_enable();
+
+	return true;
+}
+EXPORT_SYMBOL(try_lock_sock_nested);
+
 void release_sock(struct sock *sk)
 {
 	spin_lock_bh(&sk->sk_lock.slock);