Skip to contentSkip to conversation

net: support SOCK_DONTWAIT for non-blocking accept4

RFC New Eric Wong 1 participant 1 message May 13, 2015

Subsystems (4)
lore
Share & tools
lore

Eric Wong

author
#0 lore raw

RFC 1/1 net: support SOCK_DONTWAIT for non-blocking accept4

It may occasionally be useful to share a listen socket between two or more tasks with different processing models (blocking and non-blocking).

This may happen during a software upgrade when an older process (using blocking I/O) shares the listen socket with a new process which wants to use non-blocking I/O, but still provides a path for the old process to fall back to blocking I/O and avoiding poll() for exclusive wakeup if the upgrade does not work out.

Proposed manpage addtion:

SOCK_DONTWAIT

Enable non-blocking operation on the listen socket for this call only. Unlike SOCK_NONBLOCK, this does not affect the accepted socket, nor does it change the file status flag of the listen socket for other calls.

---
RFC since this seems a bit esoteric, and I'm not sure if it'd be useful to others. I've certainly wished I've had it a few times along with an opposite SOCK_MUSTWAIT flag to ignore O_NONBLOCK on a listen socket.

 include/linux/net.h |  3 +++
 net/socket.c        | 10 ++++++++--
 2 files changed, 11 insertions(+), 2 deletions(-)
include/linux/net.h +3 -0
index 17d8339..9a71654 100644
@@ -76,6 +76,9 @@ enum sock_type {
 #ifndef SOCK_NONBLOCK
 #define SOCK_NONBLOCK	O_NONBLOCK
 #endif
+#ifndef SOCK_DONTWAIT
+#define SOCK_DONTWAIT	MSG_DONTWAIT
+#endif
 
 #endif /* ARCH_HAS_SOCKET_TYPES */
 
net/socket.c +8 -2
index 245330c..52395df 100644
@@ -1294,6 +1294,7 @@ SYSCALL_DEFINE3(socket, int, family, int, type, int, protocol)
 	BUILD_BUG_ON((SOCK_MAX | SOCK_TYPE_MASK) != SOCK_TYPE_MASK);
 	BUILD_BUG_ON(SOCK_CLOEXEC & SOCK_TYPE_MASK);
 	BUILD_BUG_ON(SOCK_NONBLOCK & SOCK_TYPE_MASK);
+	BUILD_BUG_ON(SOCK_DONTWAIT & SOCK_TYPE_MASK);
 
 	flags = type & ~SOCK_TYPE_MASK;
 	if (flags & ~(SOCK_CLOEXEC | SOCK_NONBLOCK))
@@ -1502,8 +1503,9 @@ SYSCALL_DEFINE4(accept4, int, fd, struct sockaddr __user *, upeer_sockaddr,
 	struct file *newfile;
 	int err, len, newfd, fput_needed;
 	struct sockaddr_storage address;
+	int f_flags;
 
-	if (flags & ~(SOCK_CLOEXEC | SOCK_NONBLOCK))
+	if (flags & ~(SOCK_CLOEXEC | SOCK_NONBLOCK | SOCK_DONTWAIT))
 		return -EINVAL;
 
 	if (SOCK_NONBLOCK != O_NONBLOCK && (flags & SOCK_NONBLOCK))
@@ -1513,6 +1515,10 @@ SYSCALL_DEFINE4(accept4, int, fd, struct sockaddr __user *, upeer_sockaddr,
 	if (!sock)
 		goto out;
 
+	f_flags = sock->file->f_flags;
+	if (flags & SOCK_DONTWAIT)
+		f_flags |= O_NONBLOCK;
+
 	err = -ENFILE;
 	newsock = sock_alloc();
 	if (!newsock)
@@ -1545,7 +1551,7 @@ SYSCALL_DEFINE4(accept4, int, fd, struct sockaddr __user *, upeer_sockaddr,
 	if (err)
 		goto out_fd;
 
-	err = sock->ops->accept(sock, newsock, sock->file->f_flags);
+	err = sock->ops->accept(sock, newsock, f_flags);
 	if (err < 0)
 		goto out_fd;
 
Signature · 1 line
EW