xref: /linux/net/socket.c (revision f364db381c9d38c96de3148ac584f859c550fad5)
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  * NET		An implementation of the SOCKET network access protocol.
4  *
5  * Version:	@(#)socket.c	1.1.93	18/02/95
6  *
7  * Authors:	Orest Zborowski, <obz@Kodak.COM>
8  *		Ross Biro
9  *		Fred N. van Kempen, <waltje@uWalt.NL.Mugnet.ORG>
10  *
11  * Fixes:
12  *		Anonymous	:	NOTSOCK/BADF cleanup. Error fix in
13  *					shutdown()
14  *		Alan Cox	:	verify_area() fixes
15  *		Alan Cox	:	Removed DDI
16  *		Jonathan Kamens	:	SOCK_DGRAM reconnect bug
17  *		Alan Cox	:	Moved a load of checks to the very
18  *					top level.
19  *		Alan Cox	:	Move address structures to/from user
20  *					mode above the protocol layers.
21  *		Rob Janssen	:	Allow 0 length sends.
22  *		Alan Cox	:	Asynchronous I/O support (cribbed from the
23  *					tty drivers).
24  *		Niibe Yutaka	:	Asynchronous I/O for writes (4.4BSD style)
25  *		Jeff Uphoff	:	Made max number of sockets command-line
26  *					configurable.
27  *		Matti Aarnio	:	Made the number of sockets dynamic,
28  *					to be allocated when needed, and mr.
29  *					Uphoff's max is used as max to be
30  *					allowed to allocate.
31  *		Linus		:	Argh. removed all the socket allocation
32  *					altogether: it's in the inode now.
33  *		Alan Cox	:	Made sock_alloc()/sock_release() public
34  *					for NetROM and future kernel nfsd type
35  *					stuff.
36  *		Alan Cox	:	sendmsg/recvmsg basics.
37  *		Tom Dyas	:	Export net symbols.
38  *		Marcin Dalecki	:	Fixed problems with CONFIG_NET="n".
39  *		Alan Cox	:	Added thread locking to sys_* calls
40  *					for sockets. May have errors at the
41  *					moment.
42  *		Kevin Buhr	:	Fixed the dumb errors in the above.
43  *		Andi Kleen	:	Some small cleanups, optimizations,
44  *					and fixed a copy_from_user() bug.
45  *		Tigran Aivazian	:	sys_send(args) calls sys_sendto(args, NULL, 0)
46  *		Tigran Aivazian	:	Made listen(2) backlog sanity checks
47  *					protocol-independent
48  *
49  *	This module is effectively the top level interface to the BSD socket
50  *	paradigm.
51  *
52  *	Based upon Swansea University Computer Society NET3.039
53  */
54 
55 #include <linux/bpf-cgroup.h>
56 #include <linux/ethtool.h>
57 #include <linux/mm.h>
58 #include <linux/socket.h>
59 #include <linux/file.h>
60 #include <linux/splice.h>
61 #include <linux/net.h>
62 #include <linux/interrupt.h>
63 #include <linux/thread_info.h>
64 #include <linux/rcupdate.h>
65 #include <linux/netdevice.h>
66 #include <linux/proc_fs.h>
67 #include <linux/seq_file.h>
68 #include <linux/mutex.h>
69 #include <linux/if_bridge.h>
70 #include <linux/if_vlan.h>
71 #include <linux/ptp_classify.h>
72 #include <linux/init.h>
73 #include <linux/poll.h>
74 #include <linux/cache.h>
75 #include <linux/module.h>
76 #include <linux/highmem.h>
77 #include <linux/mount.h>
78 #include <linux/pseudo_fs.h>
79 #include <linux/security.h>
80 #include <linux/uio.h>
81 #include <linux/syscalls.h>
82 #include <linux/compat.h>
83 #include <linux/kmod.h>
84 #include <linux/audit.h>
85 #include <linux/wireless.h>
86 #include <linux/nsproxy.h>
87 #include <linux/magic.h>
88 #include <linux/slab.h>
89 #include <linux/xattr.h>
90 #include <linux/nospec.h>
91 #include <linux/indirect_call_wrapper.h>
92 #include <linux/io_uring/net.h>
93 
94 #include <linux/uaccess.h>
95 #include <asm/unistd.h>
96 
97 #include <net/compat.h>
98 #include <net/wext.h>
99 #include <net/cls_cgroup.h>
100 
101 #include <net/sock.h>
102 #include <linux/netfilter.h>
103 
104 #include <linux/if_tun.h>
105 #include <linux/ipv6_route.h>
106 #include <linux/route.h>
107 #include <linux/termios.h>
108 #include <linux/sockios.h>
109 #include <net/busy_poll.h>
110 #include <linux/errqueue.h>
111 #include <linux/ptp_clock_kernel.h>
112 #include <trace/events/sock.h>
113 
114 #include "core/dev.h"
115 
116 #ifdef CONFIG_NET_RX_BUSY_POLL
117 unsigned int sysctl_net_busy_read __read_mostly;
118 unsigned int sysctl_net_busy_poll __read_mostly;
119 #endif
120 
121 static ssize_t sock_read_iter(struct kiocb *iocb, struct iov_iter *to);
122 static ssize_t sock_write_iter(struct kiocb *iocb, struct iov_iter *from);
123 static int sock_mmap(struct file *file, struct vm_area_struct *vma);
124 
125 static int sock_close(struct inode *inode, struct file *file);
126 static __poll_t sock_poll(struct file *file,
127 			      struct poll_table_struct *wait);
128 static long sock_ioctl(struct file *file, unsigned int cmd, unsigned long arg);
129 #ifdef CONFIG_COMPAT
130 static long compat_sock_ioctl(struct file *file,
131 			      unsigned int cmd, unsigned long arg);
132 #endif
133 static int sock_fasync(int fd, struct file *filp, int on);
134 static ssize_t sock_splice_read(struct file *file, loff_t *ppos,
135 				struct pipe_inode_info *pipe, size_t len,
136 				unsigned int flags);
137 static void sock_splice_eof(struct file *file);
138 
139 #ifdef CONFIG_PROC_FS
140 static void sock_show_fdinfo(struct seq_file *m, struct file *f)
141 {
142 	struct socket *sock = f->private_data;
143 	const struct proto_ops *ops = READ_ONCE(sock->ops);
144 
145 	if (ops->show_fdinfo)
146 		ops->show_fdinfo(m, sock);
147 }
148 #else
149 #define sock_show_fdinfo NULL
150 #endif
151 
152 /*
153  *	Socket files have a set of 'special' operations as well as the generic file ones. These don't appear
154  *	in the operation structures but are done directly via the socketcall() multiplexor.
155  */
156 
157 static const struct file_operations socket_file_ops = {
158 	.owner =	THIS_MODULE,
159 	.read_iter =	sock_read_iter,
160 	.write_iter =	sock_write_iter,
161 	.poll =		sock_poll,
162 	.unlocked_ioctl = sock_ioctl,
163 #ifdef CONFIG_COMPAT
164 	.compat_ioctl = compat_sock_ioctl,
165 #endif
166 	.uring_cmd =    io_uring_cmd_sock,
167 	.mmap =		sock_mmap,
168 	.release =	sock_close,
169 	.fasync =	sock_fasync,
170 	.splice_write = splice_to_socket,
171 	.splice_read =	sock_splice_read,
172 	.splice_eof =	sock_splice_eof,
173 	.show_fdinfo =	sock_show_fdinfo,
174 };
175 
176 static const char * const pf_family_names[] = {
177 	[PF_UNSPEC]	= "PF_UNSPEC",
178 	[PF_UNIX]	= "PF_UNIX/PF_LOCAL",
179 	[PF_INET]	= "PF_INET",
180 	[PF_AX25]	= "PF_AX25",
181 	[PF_IPX]	= "PF_IPX",
182 	[PF_APPLETALK]	= "PF_APPLETALK",
183 	[PF_NETROM]	= "PF_NETROM",
184 	[PF_BRIDGE]	= "PF_BRIDGE",
185 	[PF_ATMPVC]	= "PF_ATMPVC",
186 	[PF_X25]	= "PF_X25",
187 	[PF_INET6]	= "PF_INET6",
188 	[PF_ROSE]	= "PF_ROSE",
189 	[PF_DECnet]	= "PF_DECnet",
190 	[PF_NETBEUI]	= "PF_NETBEUI",
191 	[PF_SECURITY]	= "PF_SECURITY",
192 	[PF_KEY]	= "PF_KEY",
193 	[PF_NETLINK]	= "PF_NETLINK/PF_ROUTE",
194 	[PF_PACKET]	= "PF_PACKET",
195 	[PF_ASH]	= "PF_ASH",
196 	[PF_ECONET]	= "PF_ECONET",
197 	[PF_ATMSVC]	= "PF_ATMSVC",
198 	[PF_RDS]	= "PF_RDS",
199 	[PF_SNA]	= "PF_SNA",
200 	[PF_IRDA]	= "PF_IRDA",
201 	[PF_PPPOX]	= "PF_PPPOX",
202 	[PF_WANPIPE]	= "PF_WANPIPE",
203 	[PF_LLC]	= "PF_LLC",
204 	[PF_IB]		= "PF_IB",
205 	[PF_MPLS]	= "PF_MPLS",
206 	[PF_CAN]	= "PF_CAN",
207 	[PF_TIPC]	= "PF_TIPC",
208 	[PF_BLUETOOTH]	= "PF_BLUETOOTH",
209 	[PF_IUCV]	= "PF_IUCV",
210 	[PF_RXRPC]	= "PF_RXRPC",
211 	[PF_ISDN]	= "PF_ISDN",
212 	[PF_PHONET]	= "PF_PHONET",
213 	[PF_IEEE802154]	= "PF_IEEE802154",
214 	[PF_CAIF]	= "PF_CAIF",
215 	[PF_ALG]	= "PF_ALG",
216 	[PF_NFC]	= "PF_NFC",
217 	[PF_VSOCK]	= "PF_VSOCK",
218 	[PF_KCM]	= "PF_KCM",
219 	[PF_QIPCRTR]	= "PF_QIPCRTR",
220 	[PF_SMC]	= "PF_SMC",
221 	[PF_XDP]	= "PF_XDP",
222 	[PF_MCTP]	= "PF_MCTP",
223 };
224 
225 /*
226  *	The protocol list. Each protocol is registered in here.
227  */
228 
229 static DEFINE_SPINLOCK(net_family_lock);
230 static const struct net_proto_family __rcu *net_families[NPROTO] __read_mostly;
231 
232 /*
233  * Support routines.
234  * Move socket addresses back and forth across the kernel/user
235  * divide and look after the messy bits.
236  */
237 
238 /**
239  *	move_addr_to_kernel	-	copy a socket address into kernel space
240  *	@uaddr: Address in user space
241  *	@kaddr: Address in kernel space
242  *	@ulen: Length in user space
243  *
244  *	The address is copied into kernel space. If the provided address is
245  *	too long an error code of -EINVAL is returned. If the copy gives
246  *	invalid addresses -EFAULT is returned. On a success 0 is returned.
247  */
248 
249 int move_addr_to_kernel(void __user *uaddr, int ulen, struct sockaddr_storage *kaddr)
250 {
251 	if (ulen < 0 || ulen > sizeof(struct sockaddr_storage))
252 		return -EINVAL;
253 	if (ulen == 0)
254 		return 0;
255 	if (copy_from_user(kaddr, uaddr, ulen))
256 		return -EFAULT;
257 	return audit_sockaddr(ulen, kaddr);
258 }
259 
260 /**
261  *	move_addr_to_user	-	copy an address to user space
262  *	@kaddr: kernel space address
263  *	@klen: length of address in kernel
264  *	@uaddr: user space address
265  *	@ulen: pointer to user length field
266  *
267  *	The value pointed to by ulen on entry is the buffer length available.
268  *	This is overwritten with the buffer space used. -EINVAL is returned
269  *	if an overlong buffer is specified or a negative buffer size. -EFAULT
270  *	is returned if either the buffer or the length field are not
271  *	accessible.
272  *	After copying the data up to the limit the user specifies, the true
273  *	length of the data is written over the length limit the user
274  *	specified. Zero is returned for a success.
275  */
276 
277 static int move_addr_to_user(struct sockaddr_storage *kaddr, int klen,
278 			     void __user *uaddr, int __user *ulen)
279 {
280 	int len;
281 
282 	BUG_ON(klen > sizeof(struct sockaddr_storage));
283 
284 	scoped_user_rw_access_size(ulen, 4, efault_end) {
285 		unsafe_get_user(len, ulen, efault_end);
286 
287 		if (len > klen)
288 			len = klen;
289 		/*
290 		 *      "fromlen shall refer to the value before truncation.."
291 		 *                      1003.1g
292 		 */
293 		if (len >= 0)
294 			unsafe_put_user(klen, ulen, efault_end);
295 	}
296 
297 	if (len) {
298 		if (len < 0)
299 			return -EINVAL;
300 		if (audit_sockaddr(klen, kaddr))
301 			return -ENOMEM;
302 		if (copy_to_user(uaddr, kaddr, len))
303 			return -EFAULT;
304 	}
305 	return 0;
306 
307 efault_end:
308 	return -EFAULT;
309 }
310 
311 static struct kmem_cache *sock_inode_cachep __ro_after_init;
312 
313 static struct inode *sock_alloc_inode(struct super_block *sb)
314 {
315 	struct socket_alloc *ei;
316 
317 	ei = alloc_inode_sb(sb, sock_inode_cachep, GFP_KERNEL);
318 	if (!ei)
319 		return NULL;
320 	init_waitqueue_head(&ei->socket.wq.wait);
321 	ei->socket.wq.fasync_list = NULL;
322 	ei->socket.wq.flags = 0;
323 
324 	ei->socket.state = SS_UNCONNECTED;
325 	ei->socket.flags = 0;
326 	ei->socket.ops = NULL;
327 	ei->socket.sk = NULL;
328 	ei->socket.file = NULL;
329 
330 	return &ei->vfs_inode;
331 }
332 
333 static void sock_free_inode(struct inode *inode)
334 {
335 	struct socket_alloc *ei;
336 
337 	ei = container_of(inode, struct socket_alloc, vfs_inode);
338 	kmem_cache_free(sock_inode_cachep, ei);
339 }
340 
341 static void init_once(void *foo)
342 {
343 	struct socket_alloc *ei = (struct socket_alloc *)foo;
344 
345 	inode_init_once(&ei->vfs_inode);
346 }
347 
348 static void init_inodecache(void)
349 {
350 	sock_inode_cachep = kmem_cache_create("sock_inode_cache",
351 					      sizeof(struct socket_alloc),
352 					      0,
353 					      (SLAB_HWCACHE_ALIGN |
354 					       SLAB_RECLAIM_ACCOUNT |
355 					       SLAB_ACCOUNT),
356 					      init_once);
357 	BUG_ON(sock_inode_cachep == NULL);
358 }
359 
360 static const struct super_operations sockfs_ops = {
361 	.alloc_inode	= sock_alloc_inode,
362 	.free_inode	= sock_free_inode,
363 	.statfs		= simple_statfs,
364 };
365 
366 /*
367  * sockfs_dname() is called from d_path().
368  */
369 static char *sockfs_dname(struct dentry *dentry, char *buffer, int buflen)
370 {
371 	return dynamic_dname(buffer, buflen, "socket:[%lu]",
372 				d_inode(dentry)->i_ino);
373 }
374 
375 static const struct dentry_operations sockfs_dentry_operations = {
376 	.d_dname  = sockfs_dname,
377 };
378 
379 static int sockfs_xattr_get(const struct xattr_handler *handler,
380 			    struct dentry *dentry, struct inode *inode,
381 			    const char *suffix, void *value, size_t size)
382 {
383 	if (value) {
384 		if (dentry->d_name.len + 1 > size)
385 			return -ERANGE;
386 		memcpy(value, dentry->d_name.name, dentry->d_name.len + 1);
387 	}
388 	return dentry->d_name.len + 1;
389 }
390 
391 #define XATTR_SOCKPROTONAME_SUFFIX "sockprotoname"
392 #define XATTR_NAME_SOCKPROTONAME (XATTR_SYSTEM_PREFIX XATTR_SOCKPROTONAME_SUFFIX)
393 #define XATTR_NAME_SOCKPROTONAME_LEN (sizeof(XATTR_NAME_SOCKPROTONAME)-1)
394 
395 static const struct xattr_handler sockfs_xattr_handler = {
396 	.name = XATTR_NAME_SOCKPROTONAME,
397 	.get = sockfs_xattr_get,
398 };
399 
400 static int sockfs_security_xattr_set(const struct xattr_handler *handler,
401 				     struct mnt_idmap *idmap,
402 				     struct dentry *dentry, struct inode *inode,
403 				     const char *suffix, const void *value,
404 				     size_t size, int flags)
405 {
406 	/* Handled by LSM. */
407 	return -EAGAIN;
408 }
409 
410 static const struct xattr_handler sockfs_security_xattr_handler = {
411 	.prefix = XATTR_SECURITY_PREFIX,
412 	.set = sockfs_security_xattr_set,
413 };
414 
415 static const struct xattr_handler * const sockfs_xattr_handlers[] = {
416 	&sockfs_xattr_handler,
417 	&sockfs_security_xattr_handler,
418 	NULL
419 };
420 
421 static int sockfs_init_fs_context(struct fs_context *fc)
422 {
423 	struct pseudo_fs_context *ctx = init_pseudo(fc, SOCKFS_MAGIC);
424 	if (!ctx)
425 		return -ENOMEM;
426 	ctx->ops = &sockfs_ops;
427 	ctx->dops = &sockfs_dentry_operations;
428 	ctx->xattr = sockfs_xattr_handlers;
429 	return 0;
430 }
431 
432 static struct vfsmount *sock_mnt __read_mostly;
433 
434 static struct file_system_type sock_fs_type = {
435 	.name =		"sockfs",
436 	.init_fs_context = sockfs_init_fs_context,
437 	.kill_sb =	kill_anon_super,
438 };
439 
440 /*
441  *	Obtains the first available file descriptor and sets it up for use.
442  *
443  *	These functions create file structures and maps them to fd space
444  *	of the current process. On success it returns file descriptor
445  *	and file struct implicitly stored in sock->file.
446  *	Note that another thread may close file descriptor before we return
447  *	from this function. We use the fact that now we do not refer
448  *	to socket after mapping. If one day we will need it, this
449  *	function will increment ref. count on file by 1.
450  *
451  *	In any case returned fd MAY BE not valid!
452  *	This race condition is unavoidable
453  *	with shared fd spaces, we cannot solve it inside kernel,
454  *	but we take care of internal coherence yet.
455  */
456 
457 /**
458  *	sock_alloc_file - Bind a &socket to a &file
459  *	@sock: socket
460  *	@flags: file status flags
461  *	@dname: protocol name
462  *
463  *	Returns the &file bound with @sock, implicitly storing it
464  *	in sock->file. If dname is %NULL, sets to "".
465  *
466  *	On failure @sock is released, and an ERR pointer is returned.
467  *
468  *	This function uses GFP_KERNEL internally.
469  */
470 
471 struct file *sock_alloc_file(struct socket *sock, int flags, const char *dname)
472 {
473 	struct file *file;
474 
475 	if (!dname)
476 		dname = sock->sk ? sock->sk->sk_prot_creator->name : "";
477 
478 	file = alloc_file_pseudo(SOCK_INODE(sock), sock_mnt, dname,
479 				O_RDWR | (flags & O_NONBLOCK),
480 				&socket_file_ops);
481 	if (IS_ERR(file)) {
482 		sock_release(sock);
483 		return file;
484 	}
485 
486 	file->f_mode |= FMODE_NOWAIT;
487 	sock->file = file;
488 	file->private_data = sock;
489 	stream_open(SOCK_INODE(sock), file);
490 	/*
491 	 * Disable permission and pre-content events, but enable legacy
492 	 * inotify events for legacy users.
493 	 */
494 	file_set_fsnotify_mode(file, FMODE_NONOTIFY_PERM);
495 	return file;
496 }
497 EXPORT_SYMBOL(sock_alloc_file);
498 
499 static int sock_map_fd(struct socket *sock, int flags)
500 {
501 	struct file *newfile;
502 	int fd = get_unused_fd_flags(flags);
503 	if (unlikely(fd < 0)) {
504 		sock_release(sock);
505 		return fd;
506 	}
507 
508 	newfile = sock_alloc_file(sock, flags, NULL);
509 	if (!IS_ERR(newfile)) {
510 		fd_install(fd, newfile);
511 		return fd;
512 	}
513 
514 	put_unused_fd(fd);
515 	return PTR_ERR(newfile);
516 }
517 
518 /**
519  *	sock_from_file - Return the &socket bounded to @file.
520  *	@file: file
521  *
522  *	On failure returns %NULL.
523  */
524 
525 struct socket *sock_from_file(struct file *file)
526 {
527 	if (likely(file->f_op == &socket_file_ops))
528 		return file->private_data;	/* set in sock_alloc_file */
529 
530 	return NULL;
531 }
532 EXPORT_SYMBOL(sock_from_file);
533 
534 /**
535  *	sockfd_lookup - Go from a file number to its socket slot
536  *	@fd: file handle
537  *	@err: pointer to an error code return
538  *
539  *	The file handle passed in is locked and the socket it is bound
540  *	to is returned. If an error occurs the err pointer is overwritten
541  *	with a negative errno code and NULL is returned. The function checks
542  *	for both invalid handles and passing a handle which is not a socket.
543  *
544  *	On a success the socket object pointer is returned.
545  */
546 
547 struct socket *sockfd_lookup(int fd, int *err)
548 {
549 	struct file *file;
550 	struct socket *sock;
551 
552 	file = fget(fd);
553 	if (!file) {
554 		*err = -EBADF;
555 		return NULL;
556 	}
557 
558 	sock = sock_from_file(file);
559 	if (!sock) {
560 		*err = -ENOTSOCK;
561 		fput(file);
562 	}
563 	return sock;
564 }
565 EXPORT_SYMBOL(sockfd_lookup);
566 
567 static ssize_t sockfs_listxattr(struct dentry *dentry, char *buffer,
568 				size_t size)
569 {
570 	ssize_t len;
571 	ssize_t used = 0;
572 
573 	len = security_inode_listsecurity(d_inode(dentry), buffer, size);
574 	if (len < 0)
575 		return len;
576 	used += len;
577 	if (buffer) {
578 		if (size < used)
579 			return -ERANGE;
580 		buffer += len;
581 	}
582 
583 	len = (XATTR_NAME_SOCKPROTONAME_LEN + 1);
584 	used += len;
585 	if (buffer) {
586 		if (size < used)
587 			return -ERANGE;
588 		memcpy(buffer, XATTR_NAME_SOCKPROTONAME, len);
589 		buffer += len;
590 	}
591 
592 	return used;
593 }
594 
595 static int sockfs_setattr(struct mnt_idmap *idmap,
596 			  struct dentry *dentry, struct iattr *iattr)
597 {
598 	int err = simple_setattr(&nop_mnt_idmap, dentry, iattr);
599 
600 	if (!err && (iattr->ia_valid & ATTR_UID)) {
601 		struct socket *sock = SOCKET_I(d_inode(dentry));
602 
603 		if (sock->sk) {
604 			/* Paired with READ_ONCE() in sk_uid() */
605 			WRITE_ONCE(sock->sk->sk_uid, iattr->ia_uid);
606 		} else {
607 			err = -ENOENT;
608 		}
609 	}
610 
611 	return err;
612 }
613 
614 static const struct inode_operations sockfs_inode_ops = {
615 	.listxattr = sockfs_listxattr,
616 	.setattr = sockfs_setattr,
617 };
618 
619 /**
620  *	sock_alloc - allocate a socket
621  *
622  *	Allocate a new inode and socket object. The two are bound together
623  *	and initialised. The socket is then returned. If we are out of inodes
624  *	NULL is returned. This functions uses GFP_KERNEL internally.
625  */
626 
627 struct socket *sock_alloc(void)
628 {
629 	struct inode *inode;
630 	struct socket *sock;
631 
632 	inode = new_inode_pseudo(sock_mnt->mnt_sb);
633 	if (!inode)
634 		return NULL;
635 
636 	sock = SOCKET_I(inode);
637 
638 	inode->i_ino = get_next_ino();
639 	inode->i_mode = S_IFSOCK | S_IRWXUGO;
640 	inode->i_uid = current_fsuid();
641 	inode->i_gid = current_fsgid();
642 	inode->i_op = &sockfs_inode_ops;
643 
644 	return sock;
645 }
646 EXPORT_SYMBOL(sock_alloc);
647 
648 static void __sock_release(struct socket *sock, struct inode *inode)
649 {
650 	const struct proto_ops *ops = READ_ONCE(sock->ops);
651 
652 	if (ops) {
653 		struct module *owner = ops->owner;
654 
655 		if (inode)
656 			inode_lock(inode);
657 		ops->release(sock);
658 		sock->sk = NULL;
659 		if (inode)
660 			inode_unlock(inode);
661 		sock->ops = NULL;
662 		module_put(owner);
663 	}
664 
665 	if (sock->wq.fasync_list)
666 		pr_err("%s: fasync list not empty!\n", __func__);
667 
668 	if (!sock->file) {
669 		iput(SOCK_INODE(sock));
670 		return;
671 	}
672 	WRITE_ONCE(sock->file, NULL);
673 }
674 
675 /**
676  *	sock_release - close a socket
677  *	@sock: socket to close
678  *
679  *	The socket is released from the protocol stack if it has a release
680  *	callback, and the inode is then released if the socket is bound to
681  *	an inode not a file.
682  */
683 void sock_release(struct socket *sock)
684 {
685 	__sock_release(sock, NULL);
686 }
687 EXPORT_SYMBOL(sock_release);
688 
689 void __sock_tx_timestamp(__u32 tsflags, __u8 *tx_flags)
690 {
691 	u8 flags = *tx_flags;
692 
693 	if (tsflags & SOF_TIMESTAMPING_TX_HARDWARE)
694 		flags |= SKBTX_HW_TSTAMP_NOBPF;
695 
696 	if (tsflags & SOF_TIMESTAMPING_TX_SOFTWARE)
697 		flags |= SKBTX_SW_TSTAMP;
698 
699 	if (tsflags & SOF_TIMESTAMPING_TX_SCHED)
700 		flags |= SKBTX_SCHED_TSTAMP;
701 
702 	if (tsflags & SOF_TIMESTAMPING_TX_COMPLETION)
703 		flags |= SKBTX_COMPLETION_TSTAMP;
704 
705 	*tx_flags = flags;
706 }
707 EXPORT_SYMBOL(__sock_tx_timestamp);
708 
709 INDIRECT_CALLABLE_DECLARE(int inet_sendmsg(struct socket *, struct msghdr *,
710 					   size_t));
711 INDIRECT_CALLABLE_DECLARE(int inet6_sendmsg(struct socket *, struct msghdr *,
712 					    size_t));
713 
714 static noinline void call_trace_sock_send_length(struct sock *sk, int ret,
715 						 int flags)
716 {
717 	trace_sock_send_length(sk, ret, 0);
718 }
719 
720 static inline int sock_sendmsg_nosec(struct socket *sock, struct msghdr *msg)
721 {
722 	int ret = INDIRECT_CALL_INET(READ_ONCE(sock->ops)->sendmsg, inet6_sendmsg,
723 				     inet_sendmsg, sock, msg,
724 				     msg_data_left(msg));
725 	BUG_ON(ret == -EIOCBQUEUED);
726 
727 	if (trace_sock_send_length_enabled())
728 		call_trace_sock_send_length(sock->sk, ret, 0);
729 	return ret;
730 }
731 
732 static int __sock_sendmsg(struct socket *sock, struct msghdr *msg)
733 {
734 	int err = security_socket_sendmsg(sock, msg,
735 					  msg_data_left(msg));
736 
737 	return err ?: sock_sendmsg_nosec(sock, msg);
738 }
739 
740 /**
741  *	sock_sendmsg - send a message through @sock
742  *	@sock: socket
743  *	@msg: message to send
744  *
745  *	Sends @msg through @sock, passing through LSM.
746  *	Returns the number of bytes sent, or an error code.
747  */
748 int sock_sendmsg(struct socket *sock, struct msghdr *msg)
749 {
750 	struct sockaddr_storage *save_addr = (struct sockaddr_storage *)msg->msg_name;
751 	struct sockaddr_storage address;
752 	int save_len = msg->msg_namelen;
753 	int ret;
754 
755 	if (msg->msg_name) {
756 		memcpy(&address, msg->msg_name, msg->msg_namelen);
757 		msg->msg_name = &address;
758 	}
759 
760 	ret = __sock_sendmsg(sock, msg);
761 	msg->msg_name = save_addr;
762 	msg->msg_namelen = save_len;
763 
764 	return ret;
765 }
766 EXPORT_SYMBOL(sock_sendmsg);
767 
768 /**
769  *	kernel_sendmsg - send a message through @sock (kernel-space)
770  *	@sock: socket
771  *	@msg: message header
772  *	@vec: kernel vec
773  *	@num: vec array length
774  *	@size: total message data size
775  *
776  *	Builds the message data with @vec and sends it through @sock.
777  *	Returns the number of bytes sent, or an error code.
778  */
779 
780 int kernel_sendmsg(struct socket *sock, struct msghdr *msg,
781 		   struct kvec *vec, size_t num, size_t size)
782 {
783 	iov_iter_kvec(&msg->msg_iter, ITER_SOURCE, vec, num, size);
784 	return sock_sendmsg(sock, msg);
785 }
786 EXPORT_SYMBOL(kernel_sendmsg);
787 
788 static bool skb_is_err_queue(const struct sk_buff *skb)
789 {
790 	/* pkt_type of skbs enqueued on the error queue are set to
791 	 * PACKET_OUTGOING in skb_set_err_queue(). This is only safe to do
792 	 * in recvmsg, since skbs received on a local socket will never
793 	 * have a pkt_type of PACKET_OUTGOING.
794 	 */
795 	return skb->pkt_type == PACKET_OUTGOING;
796 }
797 
798 /* On transmit, software and hardware timestamps are returned independently.
799  * As the two skb clones share the hardware timestamp, which may be updated
800  * before the software timestamp is received, a hardware TX timestamp may be
801  * returned only if there is no software TX timestamp. Ignore false software
802  * timestamps, which may be made in the __sock_recv_timestamp() call when the
803  * option SO_TIMESTAMP_OLD(NS) is enabled on the socket, even when the skb has a
804  * hardware timestamp.
805  */
806 static bool skb_is_swtx_tstamp(const struct sk_buff *skb, int false_tstamp)
807 {
808 	return skb->tstamp && !false_tstamp && skb_is_err_queue(skb);
809 }
810 
811 static ktime_t get_timestamp(struct sock *sk, struct sk_buff *skb, int *if_index)
812 {
813 	bool cycles = READ_ONCE(sk->sk_tsflags) & SOF_TIMESTAMPING_BIND_PHC;
814 	struct skb_shared_hwtstamps *shhwtstamps = skb_hwtstamps(skb);
815 	struct net_device *orig_dev;
816 	ktime_t hwtstamp;
817 
818 	rcu_read_lock();
819 	orig_dev = dev_get_by_napi_id(skb_napi_id(skb));
820 	if (orig_dev) {
821 		*if_index = orig_dev->ifindex;
822 		hwtstamp = netdev_get_tstamp(orig_dev, shhwtstamps, cycles);
823 	} else {
824 		hwtstamp = shhwtstamps->hwtstamp;
825 	}
826 	rcu_read_unlock();
827 
828 	return hwtstamp;
829 }
830 
831 static void put_ts_pktinfo(struct msghdr *msg, struct sk_buff *skb,
832 			   int if_index)
833 {
834 	struct scm_ts_pktinfo ts_pktinfo;
835 	struct net_device *orig_dev;
836 
837 	if (!skb_mac_header_was_set(skb))
838 		return;
839 
840 	memset(&ts_pktinfo, 0, sizeof(ts_pktinfo));
841 
842 	if (!if_index) {
843 		rcu_read_lock();
844 		orig_dev = dev_get_by_napi_id(skb_napi_id(skb));
845 		if (orig_dev)
846 			if_index = orig_dev->ifindex;
847 		rcu_read_unlock();
848 	}
849 	ts_pktinfo.if_index = if_index;
850 
851 	ts_pktinfo.pkt_length = skb->len - skb_mac_offset(skb);
852 	put_cmsg(msg, SOL_SOCKET, SCM_TIMESTAMPING_PKTINFO,
853 		 sizeof(ts_pktinfo), &ts_pktinfo);
854 }
855 
856 bool skb_has_tx_timestamp(struct sk_buff *skb, const struct sock *sk)
857 {
858 	const struct sock_exterr_skb *serr = SKB_EXT_ERR(skb);
859 	u32 tsflags = READ_ONCE(sk->sk_tsflags);
860 
861 	if (serr->ee.ee_errno != ENOMSG ||
862 	   serr->ee.ee_origin != SO_EE_ORIGIN_TIMESTAMPING)
863 		return false;
864 
865 	/* software time stamp available and wanted */
866 	if ((tsflags & SOF_TIMESTAMPING_SOFTWARE) && skb->tstamp)
867 		return true;
868 	/* hardware time stamps available and wanted */
869 	return (tsflags & SOF_TIMESTAMPING_RAW_HARDWARE) &&
870 		skb_hwtstamps(skb)->hwtstamp;
871 }
872 
873 int skb_get_tx_timestamp(struct sk_buff *skb, struct sock *sk,
874 			  struct timespec64 *ts)
875 {
876 	u32 tsflags = READ_ONCE(sk->sk_tsflags);
877 	ktime_t hwtstamp;
878 	int if_index = 0;
879 
880 	if ((tsflags & SOF_TIMESTAMPING_SOFTWARE) &&
881 	    ktime_to_timespec64_cond(skb->tstamp, ts))
882 		return SOF_TIMESTAMPING_TX_SOFTWARE;
883 
884 	if (!(tsflags & SOF_TIMESTAMPING_RAW_HARDWARE) ||
885 	    skb_is_swtx_tstamp(skb, false))
886 		return -ENOENT;
887 
888 	if (skb_shinfo(skb)->tx_flags & SKBTX_HW_TSTAMP_NETDEV)
889 		hwtstamp = get_timestamp(sk, skb, &if_index);
890 	else
891 		hwtstamp = skb_hwtstamps(skb)->hwtstamp;
892 
893 	if (tsflags & SOF_TIMESTAMPING_BIND_PHC)
894 		hwtstamp = ptp_convert_timestamp(&hwtstamp,
895 						READ_ONCE(sk->sk_bind_phc));
896 	if (!ktime_to_timespec64_cond(hwtstamp, ts))
897 		return -ENOENT;
898 
899 	return SOF_TIMESTAMPING_TX_HARDWARE;
900 }
901 
902 /*
903  * called from sock_recv_timestamp() if sock_flag(sk, SOCK_RCVTSTAMP)
904  */
905 void __sock_recv_timestamp(struct msghdr *msg, struct sock *sk,
906 	struct sk_buff *skb)
907 {
908 	int need_software_tstamp = sock_flag(sk, SOCK_RCVTSTAMP);
909 	int new_tstamp = sock_flag(sk, SOCK_TSTAMP_NEW);
910 	struct skb_shared_hwtstamps *shhwtstamps =
911 		skb_hwtstamps(skb);
912 	struct scm_timestamping_internal tss;
913 	int if_index, false_tstamp = 0;
914 	ktime_t hwtstamp;
915 	u32 tsflags;
916 
917 	/* Race occurred between timestamp enabling and packet
918 	   receiving.  Fill in the current time for now. */
919 	if (need_software_tstamp && skb->tstamp == 0) {
920 		__net_timestamp(skb);
921 		false_tstamp = 1;
922 	}
923 
924 	if (need_software_tstamp) {
925 		if (!sock_flag(sk, SOCK_RCVTSTAMPNS)) {
926 			if (new_tstamp) {
927 				struct __kernel_sock_timeval tv;
928 
929 				skb_get_new_timestamp(skb, &tv);
930 				put_cmsg(msg, SOL_SOCKET, SO_TIMESTAMP_NEW,
931 					 sizeof(tv), &tv);
932 			} else {
933 				struct __kernel_old_timeval tv;
934 
935 				skb_get_timestamp(skb, &tv);
936 				put_cmsg(msg, SOL_SOCKET, SO_TIMESTAMP_OLD,
937 					 sizeof(tv), &tv);
938 			}
939 		} else {
940 			if (new_tstamp) {
941 				struct __kernel_timespec ts;
942 
943 				skb_get_new_timestampns(skb, &ts);
944 				put_cmsg(msg, SOL_SOCKET, SO_TIMESTAMPNS_NEW,
945 					 sizeof(ts), &ts);
946 			} else {
947 				struct __kernel_old_timespec ts;
948 
949 				skb_get_timestampns(skb, &ts);
950 				put_cmsg(msg, SOL_SOCKET, SO_TIMESTAMPNS_OLD,
951 					 sizeof(ts), &ts);
952 			}
953 		}
954 	}
955 
956 	memset(&tss, 0, sizeof(tss));
957 	tsflags = READ_ONCE(sk->sk_tsflags);
958 	if (tsflags & SOF_TIMESTAMPING_SOFTWARE &&
959 	    (tsflags & SOF_TIMESTAMPING_RX_SOFTWARE ||
960 	    skb_is_err_queue(skb) ||
961 	    !(tsflags & SOF_TIMESTAMPING_OPT_RX_FILTER)))
962 		tss.ts[0] = skb->tstamp;
963 
964 	if (shhwtstamps &&
965 	    (tsflags & SOF_TIMESTAMPING_RAW_HARDWARE &&
966 	     (tsflags & SOF_TIMESTAMPING_RX_HARDWARE ||
967 	      skb_is_err_queue(skb) ||
968 	      !(tsflags & SOF_TIMESTAMPING_OPT_RX_FILTER))) &&
969 	    !skb_is_swtx_tstamp(skb, false_tstamp)) {
970 		if_index = 0;
971 		if (skb_shinfo(skb)->tx_flags & SKBTX_HW_TSTAMP_NETDEV)
972 			hwtstamp = get_timestamp(sk, skb, &if_index);
973 		else
974 			hwtstamp = shhwtstamps->hwtstamp;
975 
976 		if (tsflags & SOF_TIMESTAMPING_BIND_PHC)
977 			hwtstamp = ptp_convert_timestamp(&hwtstamp,
978 							 READ_ONCE(sk->sk_bind_phc));
979 
980 		if (hwtstamp) {
981 			tss.ts[2] = hwtstamp;
982 
983 			if ((tsflags & SOF_TIMESTAMPING_OPT_PKTINFO) &&
984 			    !skb_is_err_queue(skb))
985 				put_ts_pktinfo(msg, skb, if_index);
986 		}
987 	}
988 	if (tss.ts[0] | tss.ts[2]) {
989 		if (sock_flag(sk, SOCK_TSTAMP_NEW))
990 			put_cmsg_scm_timestamping64(msg, &tss);
991 		else
992 			put_cmsg_scm_timestamping(msg, &tss);
993 
994 		if (skb_is_err_queue(skb) && skb->len &&
995 		    SKB_EXT_ERR(skb)->opt_stats)
996 			put_cmsg(msg, SOL_SOCKET, SCM_TIMESTAMPING_OPT_STATS,
997 				 skb->len, skb->data);
998 	}
999 }
1000 EXPORT_SYMBOL_GPL(__sock_recv_timestamp);
1001 
1002 #ifdef CONFIG_WIRELESS
1003 void __sock_recv_wifi_status(struct msghdr *msg, struct sock *sk,
1004 	struct sk_buff *skb)
1005 {
1006 	int ack;
1007 
1008 	if (!sock_flag(sk, SOCK_WIFI_STATUS))
1009 		return;
1010 	if (!skb->wifi_acked_valid)
1011 		return;
1012 
1013 	ack = skb->wifi_acked;
1014 
1015 	put_cmsg(msg, SOL_SOCKET, SCM_WIFI_STATUS, sizeof(ack), &ack);
1016 }
1017 EXPORT_SYMBOL_GPL(__sock_recv_wifi_status);
1018 #endif
1019 
1020 static inline void sock_recv_drops(struct msghdr *msg, struct sock *sk,
1021 				   struct sk_buff *skb)
1022 {
1023 	if (sock_flag(sk, SOCK_RXQ_OVFL) && skb && SOCK_SKB_CB(skb)->dropcount)
1024 		put_cmsg(msg, SOL_SOCKET, SO_RXQ_OVFL,
1025 			sizeof(__u32), &SOCK_SKB_CB(skb)->dropcount);
1026 }
1027 
1028 static void sock_recv_mark(struct msghdr *msg, struct sock *sk,
1029 			   struct sk_buff *skb)
1030 {
1031 	if (sock_flag(sk, SOCK_RCVMARK) && skb) {
1032 		/* We must use a bounce buffer for CONFIG_HARDENED_USERCOPY=y */
1033 		__u32 mark = skb->mark;
1034 
1035 		put_cmsg(msg, SOL_SOCKET, SO_MARK, sizeof(__u32), &mark);
1036 	}
1037 }
1038 
1039 static void sock_recv_priority(struct msghdr *msg, struct sock *sk,
1040 			       struct sk_buff *skb)
1041 {
1042 	if (sock_flag(sk, SOCK_RCVPRIORITY) && skb) {
1043 		__u32 priority = skb->priority;
1044 
1045 		put_cmsg(msg, SOL_SOCKET, SO_PRIORITY, sizeof(__u32), &priority);
1046 	}
1047 }
1048 
1049 void __sock_recv_cmsgs(struct msghdr *msg, struct sock *sk,
1050 		       struct sk_buff *skb)
1051 {
1052 	sock_recv_timestamp(msg, sk, skb);
1053 	sock_recv_drops(msg, sk, skb);
1054 	sock_recv_mark(msg, sk, skb);
1055 	sock_recv_priority(msg, sk, skb);
1056 }
1057 EXPORT_SYMBOL_GPL(__sock_recv_cmsgs);
1058 
1059 INDIRECT_CALLABLE_DECLARE(int inet_recvmsg(struct socket *, struct msghdr *,
1060 					   size_t, int));
1061 INDIRECT_CALLABLE_DECLARE(int inet6_recvmsg(struct socket *, struct msghdr *,
1062 					    size_t, int));
1063 
1064 static noinline void call_trace_sock_recv_length(struct sock *sk, int ret, int flags)
1065 {
1066 	trace_sock_recv_length(sk, ret, flags);
1067 }
1068 
1069 static inline int sock_recvmsg_nosec(struct socket *sock, struct msghdr *msg,
1070 				     int flags)
1071 {
1072 	int ret = INDIRECT_CALL_INET(READ_ONCE(sock->ops)->recvmsg,
1073 				     inet6_recvmsg,
1074 				     inet_recvmsg, sock, msg,
1075 				     msg_data_left(msg), flags);
1076 	if (trace_sock_recv_length_enabled())
1077 		call_trace_sock_recv_length(sock->sk, ret, flags);
1078 	return ret;
1079 }
1080 
1081 /**
1082  *	sock_recvmsg - receive a message from @sock
1083  *	@sock: socket
1084  *	@msg: message to receive
1085  *	@flags: message flags
1086  *
1087  *	Receives @msg from @sock, passing through LSM. Returns the total number
1088  *	of bytes received, or an error.
1089  */
1090 int sock_recvmsg(struct socket *sock, struct msghdr *msg, int flags)
1091 {
1092 	int err = security_socket_recvmsg(sock, msg, msg_data_left(msg), flags);
1093 
1094 	return err ?: sock_recvmsg_nosec(sock, msg, flags);
1095 }
1096 EXPORT_SYMBOL(sock_recvmsg);
1097 
1098 /**
1099  *	kernel_recvmsg - Receive a message from a socket (kernel space)
1100  *	@sock: The socket to receive the message from
1101  *	@msg: Received message
1102  *	@vec: Input s/g array for message data
1103  *	@num: Size of input s/g array
1104  *	@size: Number of bytes to read
1105  *	@flags: Message flags (MSG_DONTWAIT, etc...)
1106  *
1107  *	On return the msg structure contains the scatter/gather array passed in the
1108  *	vec argument. The array is modified so that it consists of the unfilled
1109  *	portion of the original array.
1110  *
1111  *	The returned value is the total number of bytes received, or an error.
1112  */
1113 
1114 int kernel_recvmsg(struct socket *sock, struct msghdr *msg,
1115 		   struct kvec *vec, size_t num, size_t size, int flags)
1116 {
1117 	msg->msg_control_is_user = false;
1118 	iov_iter_kvec(&msg->msg_iter, ITER_DEST, vec, num, size);
1119 	return sock_recvmsg(sock, msg, flags);
1120 }
1121 EXPORT_SYMBOL(kernel_recvmsg);
1122 
1123 static ssize_t sock_splice_read(struct file *file, loff_t *ppos,
1124 				struct pipe_inode_info *pipe, size_t len,
1125 				unsigned int flags)
1126 {
1127 	struct socket *sock = file->private_data;
1128 	const struct proto_ops *ops;
1129 
1130 	ops = READ_ONCE(sock->ops);
1131 	if (unlikely(!ops->splice_read))
1132 		return copy_splice_read(file, ppos, pipe, len, flags);
1133 
1134 	return ops->splice_read(sock, ppos, pipe, len, flags);
1135 }
1136 
1137 static void sock_splice_eof(struct file *file)
1138 {
1139 	struct socket *sock = file->private_data;
1140 	const struct proto_ops *ops;
1141 
1142 	ops = READ_ONCE(sock->ops);
1143 	if (ops->splice_eof)
1144 		ops->splice_eof(sock);
1145 }
1146 
1147 static ssize_t sock_read_iter(struct kiocb *iocb, struct iov_iter *to)
1148 {
1149 	struct file *file = iocb->ki_filp;
1150 	struct socket *sock = file->private_data;
1151 	struct msghdr msg = {.msg_iter = *to,
1152 			     .msg_iocb = iocb};
1153 	ssize_t res;
1154 
1155 	if (file->f_flags & O_NONBLOCK || (iocb->ki_flags & IOCB_NOWAIT))
1156 		msg.msg_flags = MSG_DONTWAIT;
1157 
1158 	if (iocb->ki_pos != 0)
1159 		return -ESPIPE;
1160 
1161 	if (!iov_iter_count(to))	/* Match SYS5 behaviour */
1162 		return 0;
1163 
1164 	res = sock_recvmsg(sock, &msg, msg.msg_flags);
1165 	*to = msg.msg_iter;
1166 	return res;
1167 }
1168 
1169 static ssize_t sock_write_iter(struct kiocb *iocb, struct iov_iter *from)
1170 {
1171 	struct file *file = iocb->ki_filp;
1172 	struct socket *sock = file->private_data;
1173 	struct msghdr msg = {.msg_iter = *from,
1174 			     .msg_iocb = iocb};
1175 	ssize_t res;
1176 
1177 	if (iocb->ki_pos != 0)
1178 		return -ESPIPE;
1179 
1180 	if (file->f_flags & O_NONBLOCK || (iocb->ki_flags & IOCB_NOWAIT))
1181 		msg.msg_flags = MSG_DONTWAIT;
1182 
1183 	if (sock->type == SOCK_SEQPACKET)
1184 		msg.msg_flags |= MSG_EOR;
1185 
1186 	if (iocb->ki_flags & IOCB_NOSIGNAL)
1187 		msg.msg_flags |= MSG_NOSIGNAL;
1188 
1189 	res = __sock_sendmsg(sock, &msg);
1190 	*from = msg.msg_iter;
1191 	return res;
1192 }
1193 
1194 /*
1195  * Atomic setting of ioctl hooks to avoid race
1196  * with module unload.
1197  */
1198 
1199 static DEFINE_MUTEX(br_ioctl_mutex);
1200 static int (*br_ioctl_hook)(struct net *net, unsigned int cmd,
1201 			    void __user *uarg);
1202 
1203 void brioctl_set(int (*hook)(struct net *net, unsigned int cmd,
1204 			     void __user *uarg))
1205 {
1206 	mutex_lock(&br_ioctl_mutex);
1207 	br_ioctl_hook = hook;
1208 	mutex_unlock(&br_ioctl_mutex);
1209 }
1210 EXPORT_SYMBOL(brioctl_set);
1211 
1212 int br_ioctl_call(struct net *net, unsigned int cmd, void __user *uarg)
1213 {
1214 	int err = -ENOPKG;
1215 
1216 	if (!br_ioctl_hook)
1217 		request_module("bridge");
1218 
1219 	mutex_lock(&br_ioctl_mutex);
1220 	if (br_ioctl_hook)
1221 		err = br_ioctl_hook(net, cmd, uarg);
1222 	mutex_unlock(&br_ioctl_mutex);
1223 
1224 	return err;
1225 }
1226 
1227 static DEFINE_MUTEX(vlan_ioctl_mutex);
1228 static int (*vlan_ioctl_hook) (struct net *, void __user *arg);
1229 
1230 void vlan_ioctl_set(int (*hook) (struct net *, void __user *))
1231 {
1232 	mutex_lock(&vlan_ioctl_mutex);
1233 	vlan_ioctl_hook = hook;
1234 	mutex_unlock(&vlan_ioctl_mutex);
1235 }
1236 EXPORT_SYMBOL(vlan_ioctl_set);
1237 
1238 static long sock_do_ioctl(struct net *net, struct socket *sock,
1239 			  unsigned int cmd, unsigned long arg)
1240 {
1241 	const struct proto_ops *ops = READ_ONCE(sock->ops);
1242 	struct ifreq ifr;
1243 	bool need_copyout;
1244 	int err;
1245 	void __user *argp = (void __user *)arg;
1246 	void __user *data;
1247 
1248 	err = ops->ioctl(sock, cmd, arg);
1249 
1250 	/*
1251 	 * If this ioctl is unknown try to hand it down
1252 	 * to the NIC driver.
1253 	 */
1254 	if (err != -ENOIOCTLCMD)
1255 		return err;
1256 
1257 	if (!is_socket_ioctl_cmd(cmd))
1258 		return -ENOTTY;
1259 
1260 	if (get_user_ifreq(&ifr, &data, argp))
1261 		return -EFAULT;
1262 	err = dev_ioctl(net, cmd, &ifr, data, &need_copyout);
1263 	if (!err && need_copyout)
1264 		if (put_user_ifreq(&ifr, argp))
1265 			return -EFAULT;
1266 
1267 	return err;
1268 }
1269 
1270 /*
1271  *	With an ioctl, arg may well be a user mode pointer, but we don't know
1272  *	what to do with it - that's up to the protocol still.
1273  */
1274 
1275 static long sock_ioctl(struct file *file, unsigned cmd, unsigned long arg)
1276 {
1277 	const struct proto_ops  *ops;
1278 	struct socket *sock;
1279 	struct sock *sk;
1280 	void __user *argp = (void __user *)arg;
1281 	int pid, err;
1282 	struct net *net;
1283 
1284 	sock = file->private_data;
1285 	ops = READ_ONCE(sock->ops);
1286 	sk = sock->sk;
1287 	net = sock_net(sk);
1288 	if (unlikely(cmd >= SIOCDEVPRIVATE && cmd <= (SIOCDEVPRIVATE + 15))) {
1289 		struct ifreq ifr;
1290 		void __user *data;
1291 		bool need_copyout;
1292 		if (get_user_ifreq(&ifr, &data, argp))
1293 			return -EFAULT;
1294 		err = dev_ioctl(net, cmd, &ifr, data, &need_copyout);
1295 		if (!err && need_copyout)
1296 			if (put_user_ifreq(&ifr, argp))
1297 				return -EFAULT;
1298 	} else
1299 #ifdef CONFIG_WEXT_CORE
1300 	if (cmd >= SIOCIWFIRST && cmd <= SIOCIWLAST) {
1301 		err = wext_handle_ioctl(net, cmd, argp);
1302 	} else
1303 #endif
1304 		switch (cmd) {
1305 		case FIOSETOWN:
1306 		case SIOCSPGRP:
1307 			err = -EFAULT;
1308 			if (get_user(pid, (int __user *)argp))
1309 				break;
1310 			err = f_setown(sock->file, pid, 1);
1311 			break;
1312 		case FIOGETOWN:
1313 		case SIOCGPGRP:
1314 			err = put_user(f_getown(sock->file),
1315 				       (int __user *)argp);
1316 			break;
1317 		case SIOCGIFBR:
1318 		case SIOCSIFBR:
1319 		case SIOCBRADDBR:
1320 		case SIOCBRDELBR:
1321 		case SIOCBRADDIF:
1322 		case SIOCBRDELIF:
1323 			err = br_ioctl_call(net, cmd, argp);
1324 			break;
1325 		case SIOCGIFVLAN:
1326 		case SIOCSIFVLAN:
1327 			err = -ENOPKG;
1328 			if (!vlan_ioctl_hook)
1329 				request_module("8021q");
1330 
1331 			mutex_lock(&vlan_ioctl_mutex);
1332 			if (vlan_ioctl_hook)
1333 				err = vlan_ioctl_hook(net, argp);
1334 			mutex_unlock(&vlan_ioctl_mutex);
1335 			break;
1336 		case SIOCGSKNS:
1337 			err = -EPERM;
1338 			if (!ns_capable(net->user_ns, CAP_NET_ADMIN))
1339 				break;
1340 
1341 			err = open_related_ns(&net->ns, get_net_ns);
1342 			break;
1343 		case SIOCGSTAMP_OLD:
1344 		case SIOCGSTAMPNS_OLD:
1345 			if (!ops->gettstamp) {
1346 				err = -ENOIOCTLCMD;
1347 				break;
1348 			}
1349 			err = ops->gettstamp(sock, argp,
1350 					     cmd == SIOCGSTAMP_OLD,
1351 					     !IS_ENABLED(CONFIG_64BIT));
1352 			break;
1353 		case SIOCGSTAMP_NEW:
1354 		case SIOCGSTAMPNS_NEW:
1355 			if (!ops->gettstamp) {
1356 				err = -ENOIOCTLCMD;
1357 				break;
1358 			}
1359 			err = ops->gettstamp(sock, argp,
1360 					     cmd == SIOCGSTAMP_NEW,
1361 					     false);
1362 			break;
1363 
1364 		case SIOCGIFCONF:
1365 			err = dev_ifconf(net, argp);
1366 			break;
1367 
1368 		default:
1369 			err = sock_do_ioctl(net, sock, cmd, arg);
1370 			break;
1371 		}
1372 	return err;
1373 }
1374 
1375 /**
1376  *	sock_create_lite - creates a socket
1377  *	@family: protocol family (AF_INET, ...)
1378  *	@type: communication type (SOCK_STREAM, ...)
1379  *	@protocol: protocol (0, ...)
1380  *	@res: new socket
1381  *
1382  *	Creates a new socket and assigns it to @res, passing through LSM.
1383  *	The new socket initialization is not complete, see kernel_accept().
1384  *	Returns 0 or an error. On failure @res is set to %NULL.
1385  *	This function internally uses GFP_KERNEL.
1386  */
1387 
1388 int sock_create_lite(int family, int type, int protocol, struct socket **res)
1389 {
1390 	int err;
1391 	struct socket *sock = NULL;
1392 
1393 	err = security_socket_create(family, type, protocol, 1);
1394 	if (err)
1395 		goto out;
1396 
1397 	sock = sock_alloc();
1398 	if (!sock) {
1399 		err = -ENOMEM;
1400 		goto out;
1401 	}
1402 
1403 	sock->type = type;
1404 	err = security_socket_post_create(sock, family, type, protocol, 1);
1405 	if (err)
1406 		goto out_release;
1407 
1408 out:
1409 	*res = sock;
1410 	return err;
1411 out_release:
1412 	sock_release(sock);
1413 	sock = NULL;
1414 	goto out;
1415 }
1416 EXPORT_SYMBOL(sock_create_lite);
1417 
1418 /* No kernel lock held - perfect */
1419 static __poll_t sock_poll(struct file *file, poll_table *wait)
1420 {
1421 	struct socket *sock = file->private_data;
1422 	const struct proto_ops *ops = READ_ONCE(sock->ops);
1423 	__poll_t events = poll_requested_events(wait), flag = 0;
1424 
1425 	if (!ops->poll)
1426 		return 0;
1427 
1428 	if (sk_can_busy_loop(sock->sk)) {
1429 		/* poll once if requested by the syscall */
1430 		if (events & POLL_BUSY_LOOP)
1431 			sk_busy_loop(sock->sk, 1);
1432 
1433 		/* if this socket can poll_ll, tell the system call */
1434 		flag = POLL_BUSY_LOOP;
1435 	}
1436 
1437 	return ops->poll(file, sock, wait) | flag;
1438 }
1439 
1440 static int sock_mmap(struct file *file, struct vm_area_struct *vma)
1441 {
1442 	struct socket *sock = file->private_data;
1443 
1444 	return READ_ONCE(sock->ops)->mmap(file, sock, vma);
1445 }
1446 
1447 static int sock_close(struct inode *inode, struct file *filp)
1448 {
1449 	__sock_release(SOCKET_I(inode), inode);
1450 	return 0;
1451 }
1452 
1453 /*
1454  *	Update the socket async list
1455  *
1456  *	Fasync_list locking strategy.
1457  *
1458  *	1. fasync_list is modified only under process context socket lock
1459  *	   i.e. under semaphore.
1460  *	2. fasync_list is used under read_lock(&sk->sk_callback_lock)
1461  *	   or under socket lock
1462  */
1463 
1464 static int sock_fasync(int fd, struct file *filp, int on)
1465 {
1466 	struct socket *sock = filp->private_data;
1467 	struct sock *sk = sock->sk;
1468 	struct socket_wq *wq = &sock->wq;
1469 
1470 	if (sk == NULL)
1471 		return -EINVAL;
1472 
1473 	lock_sock(sk);
1474 	fasync_helper(fd, filp, on, &wq->fasync_list);
1475 
1476 	if (!wq->fasync_list)
1477 		sock_reset_flag(sk, SOCK_FASYNC);
1478 	else
1479 		sock_set_flag(sk, SOCK_FASYNC);
1480 
1481 	release_sock(sk);
1482 	return 0;
1483 }
1484 
1485 /* This function may be called only under rcu_lock */
1486 
1487 int sock_wake_async(struct socket_wq *wq, int how, int band)
1488 {
1489 	if (!wq || !wq->fasync_list)
1490 		return -1;
1491 
1492 	switch (how) {
1493 	case SOCK_WAKE_WAITD:
1494 		if (test_bit(SOCKWQ_ASYNC_WAITDATA, &wq->flags))
1495 			break;
1496 		goto call_kill;
1497 	case SOCK_WAKE_SPACE:
1498 		if (!test_and_clear_bit(SOCKWQ_ASYNC_NOSPACE, &wq->flags))
1499 			break;
1500 		fallthrough;
1501 	case SOCK_WAKE_IO:
1502 call_kill:
1503 		kill_fasync(&wq->fasync_list, SIGIO, band);
1504 		break;
1505 	case SOCK_WAKE_URG:
1506 		kill_fasync(&wq->fasync_list, SIGURG, band);
1507 	}
1508 
1509 	return 0;
1510 }
1511 EXPORT_SYMBOL(sock_wake_async);
1512 
1513 /**
1514  *	__sock_create - creates a socket
1515  *	@net: net namespace
1516  *	@family: protocol family (AF_INET, ...)
1517  *	@type: communication type (SOCK_STREAM, ...)
1518  *	@protocol: protocol (0, ...)
1519  *	@res: new socket
1520  *	@kern: boolean for kernel space sockets
1521  *
1522  *	Creates a new socket and assigns it to @res, passing through LSM.
1523  *	Returns 0 or an error. On failure @res is set to %NULL. @kern must
1524  *	be set to true if the socket resides in kernel space.
1525  *	This function internally uses GFP_KERNEL.
1526  */
1527 
1528 int __sock_create(struct net *net, int family, int type, int protocol,
1529 			 struct socket **res, int kern)
1530 {
1531 	int err;
1532 	struct socket *sock;
1533 	const struct net_proto_family *pf;
1534 
1535 	/*
1536 	 *      Check protocol is in range
1537 	 */
1538 	if (family < 0 || family >= NPROTO)
1539 		return -EAFNOSUPPORT;
1540 	if (type < 0 || type >= SOCK_MAX)
1541 		return -EINVAL;
1542 
1543 	/* Compatibility.
1544 
1545 	   This uglymoron is moved from INET layer to here to avoid
1546 	   deadlock in module load.
1547 	 */
1548 	if (family == PF_INET && type == SOCK_PACKET) {
1549 		pr_info_once("%s uses obsolete (PF_INET,SOCK_PACKET)\n",
1550 			     current->comm);
1551 		family = PF_PACKET;
1552 	}
1553 
1554 	err = security_socket_create(family, type, protocol, kern);
1555 	if (err)
1556 		return err;
1557 
1558 	/*
1559 	 *	Allocate the socket and allow the family to set things up. if
1560 	 *	the protocol is 0, the family is instructed to select an appropriate
1561 	 *	default.
1562 	 */
1563 	sock = sock_alloc();
1564 	if (!sock) {
1565 		net_warn_ratelimited("socket: no more sockets\n");
1566 		return -ENFILE;	/* Not exactly a match, but its the
1567 				   closest posix thing */
1568 	}
1569 
1570 	sock->type = type;
1571 
1572 #ifdef CONFIG_MODULES
1573 	/* Attempt to load a protocol module if the find failed.
1574 	 *
1575 	 * 12/09/1996 Marcin: But! this makes REALLY only sense, if the user
1576 	 * requested real, full-featured networking support upon configuration.
1577 	 * Otherwise module support will break!
1578 	 */
1579 	if (rcu_access_pointer(net_families[family]) == NULL)
1580 		request_module("net-pf-%d", family);
1581 #endif
1582 
1583 	rcu_read_lock();
1584 	pf = rcu_dereference(net_families[family]);
1585 	err = -EAFNOSUPPORT;
1586 	if (!pf)
1587 		goto out_release;
1588 
1589 	/*
1590 	 * We will call the ->create function, that possibly is in a loadable
1591 	 * module, so we have to bump that loadable module refcnt first.
1592 	 */
1593 	if (!try_module_get(pf->owner))
1594 		goto out_release;
1595 
1596 	/* Now protected by module ref count */
1597 	rcu_read_unlock();
1598 
1599 	err = pf->create(net, sock, protocol, kern);
1600 	if (err < 0) {
1601 		/* ->create should release the allocated sock->sk object on error
1602 		 * and make sure sock->sk is set to NULL to avoid use-after-free
1603 		 */
1604 		DEBUG_NET_WARN_ONCE(sock->sk,
1605 				    "%ps must clear sock->sk on failure, family: %d, type: %d, protocol: %d\n",
1606 				    pf->create, family, type, protocol);
1607 		goto out_module_put;
1608 	}
1609 
1610 	/*
1611 	 * Now to bump the refcnt of the [loadable] module that owns this
1612 	 * socket at sock_release time we decrement its refcnt.
1613 	 */
1614 	if (!try_module_get(sock->ops->owner))
1615 		goto out_module_busy;
1616 
1617 	/*
1618 	 * Now that we're done with the ->create function, the [loadable]
1619 	 * module can have its refcnt decremented
1620 	 */
1621 	module_put(pf->owner);
1622 	err = security_socket_post_create(sock, family, type, protocol, kern);
1623 	if (err)
1624 		goto out_sock_release;
1625 	*res = sock;
1626 
1627 	return 0;
1628 
1629 out_module_busy:
1630 	err = -EAFNOSUPPORT;
1631 out_module_put:
1632 	sock->ops = NULL;
1633 	module_put(pf->owner);
1634 out_sock_release:
1635 	sock_release(sock);
1636 	return err;
1637 
1638 out_release:
1639 	rcu_read_unlock();
1640 	goto out_sock_release;
1641 }
1642 EXPORT_SYMBOL(__sock_create);
1643 
1644 /**
1645  *	sock_create - creates a socket
1646  *	@family: protocol family (AF_INET, ...)
1647  *	@type: communication type (SOCK_STREAM, ...)
1648  *	@protocol: protocol (0, ...)
1649  *	@res: new socket
1650  *
1651  *	A wrapper around __sock_create().
1652  *	Returns 0 or an error. This function internally uses GFP_KERNEL.
1653  */
1654 
1655 int sock_create(int family, int type, int protocol, struct socket **res)
1656 {
1657 	return __sock_create(current->nsproxy->net_ns, family, type, protocol, res, 0);
1658 }
1659 EXPORT_SYMBOL(sock_create);
1660 
1661 /**
1662  *	sock_create_kern - creates a socket (kernel space)
1663  *	@net: net namespace
1664  *	@family: protocol family (AF_INET, ...)
1665  *	@type: communication type (SOCK_STREAM, ...)
1666  *	@protocol: protocol (0, ...)
1667  *	@res: new socket
1668  *
1669  *	A wrapper around __sock_create().
1670  *	Returns 0 or an error. This function internally uses GFP_KERNEL.
1671  */
1672 
1673 int sock_create_kern(struct net *net, int family, int type, int protocol, struct socket **res)
1674 {
1675 	return __sock_create(net, family, type, protocol, res, 1);
1676 }
1677 EXPORT_SYMBOL(sock_create_kern);
1678 
1679 static struct socket *__sys_socket_create(int family, int type, int protocol)
1680 {
1681 	struct socket *sock;
1682 	int retval;
1683 
1684 	/* Check the SOCK_* constants for consistency.  */
1685 	BUILD_BUG_ON(SOCK_CLOEXEC != O_CLOEXEC);
1686 	BUILD_BUG_ON((SOCK_MAX | SOCK_TYPE_MASK) != SOCK_TYPE_MASK);
1687 	BUILD_BUG_ON(SOCK_CLOEXEC & SOCK_TYPE_MASK);
1688 	BUILD_BUG_ON(SOCK_NONBLOCK & SOCK_TYPE_MASK);
1689 
1690 	if ((type & ~SOCK_TYPE_MASK) & ~(SOCK_CLOEXEC | SOCK_NONBLOCK))
1691 		return ERR_PTR(-EINVAL);
1692 	type &= SOCK_TYPE_MASK;
1693 
1694 	retval = sock_create(family, type, protocol, &sock);
1695 	if (retval < 0)
1696 		return ERR_PTR(retval);
1697 
1698 	return sock;
1699 }
1700 
1701 struct file *__sys_socket_file(int family, int type, int protocol)
1702 {
1703 	struct socket *sock;
1704 	int flags;
1705 
1706 	sock = __sys_socket_create(family, type, protocol);
1707 	if (IS_ERR(sock))
1708 		return ERR_CAST(sock);
1709 
1710 	flags = type & ~SOCK_TYPE_MASK;
1711 	if (SOCK_NONBLOCK != O_NONBLOCK && (flags & SOCK_NONBLOCK))
1712 		flags = (flags & ~SOCK_NONBLOCK) | O_NONBLOCK;
1713 
1714 	return sock_alloc_file(sock, flags, NULL);
1715 }
1716 
1717 /*	A hook for bpf progs to attach to and update socket protocol.
1718  *
1719  *	A static noinline declaration here could cause the compiler to
1720  *	optimize away the function. A global noinline declaration will
1721  *	keep the definition, but may optimize away the callsite.
1722  *	Therefore, __weak is needed to ensure that the call is still
1723  *	emitted, by telling the compiler that we don't know what the
1724  *	function might eventually be.
1725  */
1726 
1727 __bpf_hook_start();
1728 
1729 __weak noinline int update_socket_protocol(int family, int type, int protocol)
1730 {
1731 	return protocol;
1732 }
1733 
1734 __bpf_hook_end();
1735 
1736 int __sys_socket(int family, int type, int protocol)
1737 {
1738 	struct socket *sock;
1739 	int flags;
1740 
1741 	sock = __sys_socket_create(family, type,
1742 				   update_socket_protocol(family, type, protocol));
1743 	if (IS_ERR(sock))
1744 		return PTR_ERR(sock);
1745 
1746 	flags = type & ~SOCK_TYPE_MASK;
1747 	if (SOCK_NONBLOCK != O_NONBLOCK && (flags & SOCK_NONBLOCK))
1748 		flags = (flags & ~SOCK_NONBLOCK) | O_NONBLOCK;
1749 
1750 	return sock_map_fd(sock, flags & (O_CLOEXEC | O_NONBLOCK));
1751 }
1752 
1753 SYSCALL_DEFINE3(socket, int, family, int, type, int, protocol)
1754 {
1755 	return __sys_socket(family, type, protocol);
1756 }
1757 
1758 /*
1759  *	Create a pair of connected sockets.
1760  */
1761 
1762 int __sys_socketpair(int family, int type, int protocol, int __user *usockvec)
1763 {
1764 	struct socket *sock1, *sock2;
1765 	int fd1, fd2, err;
1766 	struct file *newfile1, *newfile2;
1767 	int flags;
1768 
1769 	flags = type & ~SOCK_TYPE_MASK;
1770 	if (flags & ~(SOCK_CLOEXEC | SOCK_NONBLOCK))
1771 		return -EINVAL;
1772 	type &= SOCK_TYPE_MASK;
1773 
1774 	if (SOCK_NONBLOCK != O_NONBLOCK && (flags & SOCK_NONBLOCK))
1775 		flags = (flags & ~SOCK_NONBLOCK) | O_NONBLOCK;
1776 
1777 	/*
1778 	 * reserve descriptors and make sure we won't fail
1779 	 * to return them to userland.
1780 	 */
1781 	fd1 = get_unused_fd_flags(flags);
1782 	if (unlikely(fd1 < 0))
1783 		return fd1;
1784 
1785 	fd2 = get_unused_fd_flags(flags);
1786 	if (unlikely(fd2 < 0)) {
1787 		put_unused_fd(fd1);
1788 		return fd2;
1789 	}
1790 
1791 	err = put_user(fd1, &usockvec[0]);
1792 	if (err)
1793 		goto out;
1794 
1795 	err = put_user(fd2, &usockvec[1]);
1796 	if (err)
1797 		goto out;
1798 
1799 	/*
1800 	 * Obtain the first socket and check if the underlying protocol
1801 	 * supports the socketpair call.
1802 	 */
1803 
1804 	err = sock_create(family, type, protocol, &sock1);
1805 	if (unlikely(err < 0))
1806 		goto out;
1807 
1808 	err = sock_create(family, type, protocol, &sock2);
1809 	if (unlikely(err < 0)) {
1810 		sock_release(sock1);
1811 		goto out;
1812 	}
1813 
1814 	err = security_socket_socketpair(sock1, sock2);
1815 	if (unlikely(err)) {
1816 		sock_release(sock2);
1817 		sock_release(sock1);
1818 		goto out;
1819 	}
1820 
1821 	err = READ_ONCE(sock1->ops)->socketpair(sock1, sock2);
1822 	if (unlikely(err < 0)) {
1823 		sock_release(sock2);
1824 		sock_release(sock1);
1825 		goto out;
1826 	}
1827 
1828 	newfile1 = sock_alloc_file(sock1, flags, NULL);
1829 	if (IS_ERR(newfile1)) {
1830 		err = PTR_ERR(newfile1);
1831 		sock_release(sock2);
1832 		goto out;
1833 	}
1834 
1835 	newfile2 = sock_alloc_file(sock2, flags, NULL);
1836 	if (IS_ERR(newfile2)) {
1837 		err = PTR_ERR(newfile2);
1838 		fput(newfile1);
1839 		goto out;
1840 	}
1841 
1842 	audit_fd_pair(fd1, fd2);
1843 
1844 	fd_install(fd1, newfile1);
1845 	fd_install(fd2, newfile2);
1846 	return 0;
1847 
1848 out:
1849 	put_unused_fd(fd2);
1850 	put_unused_fd(fd1);
1851 	return err;
1852 }
1853 
1854 SYSCALL_DEFINE4(socketpair, int, family, int, type, int, protocol,
1855 		int __user *, usockvec)
1856 {
1857 	return __sys_socketpair(family, type, protocol, usockvec);
1858 }
1859 
1860 int __sys_bind_socket(struct socket *sock, struct sockaddr_storage *address,
1861 		      int addrlen)
1862 {
1863 	int err;
1864 
1865 	err = security_socket_bind(sock, (struct sockaddr *)address,
1866 				   addrlen);
1867 	if (!err)
1868 		err = READ_ONCE(sock->ops)->bind(sock,
1869 						 (struct sockaddr_unsized *)address,
1870 						 addrlen);
1871 	return err;
1872 }
1873 
1874 /*
1875  *	Bind a name to a socket. Nothing much to do here since it's
1876  *	the protocol's responsibility to handle the local address.
1877  *
1878  *	We move the socket address to kernel space before we call
1879  *	the protocol layer (having also checked the address is ok).
1880  */
1881 
1882 int __sys_bind(int fd, struct sockaddr __user *umyaddr, int addrlen)
1883 {
1884 	struct socket *sock;
1885 	struct sockaddr_storage address;
1886 	CLASS(fd, f)(fd);
1887 	int err;
1888 
1889 	if (fd_empty(f))
1890 		return -EBADF;
1891 	sock = sock_from_file(fd_file(f));
1892 	if (unlikely(!sock))
1893 		return -ENOTSOCK;
1894 
1895 	err = move_addr_to_kernel(umyaddr, addrlen, &address);
1896 	if (unlikely(err))
1897 		return err;
1898 
1899 	return __sys_bind_socket(sock, &address, addrlen);
1900 }
1901 
1902 SYSCALL_DEFINE3(bind, int, fd, struct sockaddr __user *, umyaddr, int, addrlen)
1903 {
1904 	return __sys_bind(fd, umyaddr, addrlen);
1905 }
1906 
1907 /*
1908  *	Perform a listen. Basically, we allow the protocol to do anything
1909  *	necessary for a listen, and if that works, we mark the socket as
1910  *	ready for listening.
1911  */
1912 int __sys_listen_socket(struct socket *sock, int backlog)
1913 {
1914 	int somaxconn, err;
1915 
1916 	somaxconn = READ_ONCE(sock_net(sock->sk)->core.sysctl_somaxconn);
1917 	if ((unsigned int)backlog > somaxconn)
1918 		backlog = somaxconn;
1919 
1920 	err = security_socket_listen(sock, backlog);
1921 	if (!err)
1922 		err = READ_ONCE(sock->ops)->listen(sock, backlog);
1923 	return err;
1924 }
1925 
1926 int __sys_listen(int fd, int backlog)
1927 {
1928 	CLASS(fd, f)(fd);
1929 	struct socket *sock;
1930 
1931 	if (fd_empty(f))
1932 		return -EBADF;
1933 	sock = sock_from_file(fd_file(f));
1934 	if (unlikely(!sock))
1935 		return -ENOTSOCK;
1936 
1937 	return __sys_listen_socket(sock, backlog);
1938 }
1939 
1940 SYSCALL_DEFINE2(listen, int, fd, int, backlog)
1941 {
1942 	return __sys_listen(fd, backlog);
1943 }
1944 
1945 struct file *do_accept(struct file *file, struct proto_accept_arg *arg,
1946 		       struct sockaddr __user *upeer_sockaddr,
1947 		       int __user *upeer_addrlen, int flags)
1948 {
1949 	struct socket *sock, *newsock;
1950 	struct file *newfile;
1951 	int err, len;
1952 	struct sockaddr_storage address;
1953 	const struct proto_ops *ops;
1954 
1955 	sock = sock_from_file(file);
1956 	if (!sock)
1957 		return ERR_PTR(-ENOTSOCK);
1958 
1959 	newsock = sock_alloc();
1960 	if (!newsock)
1961 		return ERR_PTR(-ENFILE);
1962 	ops = READ_ONCE(sock->ops);
1963 
1964 	newsock->type = sock->type;
1965 	newsock->ops = ops;
1966 
1967 	/*
1968 	 * We don't need try_module_get here, as the listening socket (sock)
1969 	 * has the protocol module (sock->ops->owner) held.
1970 	 */
1971 	__module_get(ops->owner);
1972 
1973 	newfile = sock_alloc_file(newsock, flags, sock->sk->sk_prot_creator->name);
1974 	if (IS_ERR(newfile))
1975 		return newfile;
1976 
1977 	err = security_socket_accept(sock, newsock);
1978 	if (err)
1979 		goto out_fd;
1980 
1981 	arg->flags |= sock->file->f_flags;
1982 	err = ops->accept(sock, newsock, arg);
1983 	if (err < 0)
1984 		goto out_fd;
1985 
1986 	if (upeer_sockaddr) {
1987 		len = ops->getname(newsock, (struct sockaddr *)&address, 2);
1988 		if (len < 0) {
1989 			err = -ECONNABORTED;
1990 			goto out_fd;
1991 		}
1992 		err = move_addr_to_user(&address,
1993 					len, upeer_sockaddr, upeer_addrlen);
1994 		if (err < 0)
1995 			goto out_fd;
1996 	}
1997 
1998 	/* File flags are not inherited via accept() unlike another OSes. */
1999 	return newfile;
2000 out_fd:
2001 	fput(newfile);
2002 	return ERR_PTR(err);
2003 }
2004 
2005 static int __sys_accept4_file(struct file *file, struct sockaddr __user *upeer_sockaddr,
2006 			      int __user *upeer_addrlen, int flags)
2007 {
2008 	struct proto_accept_arg arg = { };
2009 
2010 	if (flags & ~(SOCK_CLOEXEC | SOCK_NONBLOCK))
2011 		return -EINVAL;
2012 
2013 	if (SOCK_NONBLOCK != O_NONBLOCK && (flags & SOCK_NONBLOCK))
2014 		flags = (flags & ~SOCK_NONBLOCK) | O_NONBLOCK;
2015 
2016 	return FD_ADD(flags, do_accept(file, &arg, upeer_sockaddr, upeer_addrlen, flags));
2017 }
2018 
2019 /*
2020  *	For accept, we attempt to create a new socket, set up the link
2021  *	with the client, wake up the client, then return the new
2022  *	connected fd. We collect the address of the connector in kernel
2023  *	space and move it to user at the very end. This is unclean because
2024  *	we open the socket then return an error.
2025  *
2026  *	1003.1g adds the ability to recvmsg() to query connection pending
2027  *	status to recvmsg. We need to add that support in a way thats
2028  *	clean when we restructure accept also.
2029  */
2030 
2031 int __sys_accept4(int fd, struct sockaddr __user *upeer_sockaddr,
2032 		  int __user *upeer_addrlen, int flags)
2033 {
2034 	CLASS(fd, f)(fd);
2035 
2036 	if (fd_empty(f))
2037 		return -EBADF;
2038 	return __sys_accept4_file(fd_file(f), upeer_sockaddr,
2039 					 upeer_addrlen, flags);
2040 }
2041 
2042 SYSCALL_DEFINE4(accept4, int, fd, struct sockaddr __user *, upeer_sockaddr,
2043 		int __user *, upeer_addrlen, int, flags)
2044 {
2045 	return __sys_accept4(fd, upeer_sockaddr, upeer_addrlen, flags);
2046 }
2047 
2048 SYSCALL_DEFINE3(accept, int, fd, struct sockaddr __user *, upeer_sockaddr,
2049 		int __user *, upeer_addrlen)
2050 {
2051 	return __sys_accept4(fd, upeer_sockaddr, upeer_addrlen, 0);
2052 }
2053 
2054 /*
2055  *	Attempt to connect to a socket with the server address.  The address
2056  *	is in user space so we verify it is OK and move it to kernel space.
2057  *
2058  *	For 1003.1g we need to add clean support for a bind to AF_UNSPEC to
2059  *	break bindings
2060  *
2061  *	NOTE: 1003.1g draft 6.3 is broken with respect to AX.25/NetROM and
2062  *	other SEQPACKET protocols that take time to connect() as it doesn't
2063  *	include the -EINPROGRESS status for such sockets.
2064  */
2065 
2066 int __sys_connect_file(struct file *file, struct sockaddr_storage *address,
2067 		       int addrlen, int file_flags)
2068 {
2069 	struct socket *sock;
2070 	int err;
2071 
2072 	sock = sock_from_file(file);
2073 	if (!sock) {
2074 		err = -ENOTSOCK;
2075 		goto out;
2076 	}
2077 
2078 	err =
2079 	    security_socket_connect(sock, (struct sockaddr *)address, addrlen);
2080 	if (err)
2081 		goto out;
2082 
2083 	err = READ_ONCE(sock->ops)->connect(sock, (struct sockaddr_unsized *)address,
2084 					    addrlen, sock->file->f_flags | file_flags);
2085 out:
2086 	return err;
2087 }
2088 
2089 int __sys_connect(int fd, struct sockaddr __user *uservaddr, int addrlen)
2090 {
2091 	struct sockaddr_storage address;
2092 	CLASS(fd, f)(fd);
2093 	int ret;
2094 
2095 	if (fd_empty(f))
2096 		return -EBADF;
2097 
2098 	ret = move_addr_to_kernel(uservaddr, addrlen, &address);
2099 	if (ret)
2100 		return ret;
2101 
2102 	return __sys_connect_file(fd_file(f), &address, addrlen, 0);
2103 }
2104 
2105 SYSCALL_DEFINE3(connect, int, fd, struct sockaddr __user *, uservaddr,
2106 		int, addrlen)
2107 {
2108 	return __sys_connect(fd, uservaddr, addrlen);
2109 }
2110 
2111 int do_getsockname(struct socket *sock, int peer,
2112 		   struct sockaddr __user *usockaddr, int __user *usockaddr_len)
2113 {
2114 	struct sockaddr_storage address;
2115 	int err;
2116 
2117 	if (peer)
2118 		err = security_socket_getpeername(sock);
2119 	else
2120 		err = security_socket_getsockname(sock);
2121 	if (err)
2122 		return err;
2123 	err = READ_ONCE(sock->ops)->getname(sock, (struct sockaddr *)&address, peer);
2124 	if (err < 0)
2125 		return err;
2126 	/* "err" is actually length in this case */
2127 	return move_addr_to_user(&address, err, usockaddr, usockaddr_len);
2128 }
2129 
2130 /*
2131  *	Get the remote or local address ('name') of a socket object. Move the
2132  *	obtained name to user space.
2133  */
2134 int __sys_getsockname(int fd, struct sockaddr __user *usockaddr,
2135 		      int __user *usockaddr_len, int peer)
2136 {
2137 	struct socket *sock;
2138 	CLASS(fd, f)(fd);
2139 
2140 	if (fd_empty(f))
2141 		return -EBADF;
2142 	sock = sock_from_file(fd_file(f));
2143 	if (unlikely(!sock))
2144 		return -ENOTSOCK;
2145 	return do_getsockname(sock, peer, usockaddr, usockaddr_len);
2146 }
2147 
2148 SYSCALL_DEFINE3(getsockname, int, fd, struct sockaddr __user *, usockaddr,
2149 		int __user *, usockaddr_len)
2150 {
2151 	return __sys_getsockname(fd, usockaddr, usockaddr_len, 0);
2152 }
2153 
2154 SYSCALL_DEFINE3(getpeername, int, fd, struct sockaddr __user *, usockaddr,
2155 		int __user *, usockaddr_len)
2156 {
2157 	return __sys_getsockname(fd, usockaddr, usockaddr_len, 1);
2158 }
2159 
2160 /*
2161  *	Send a datagram to a given address. We move the address into kernel
2162  *	space and check the user space data area is readable before invoking
2163  *	the protocol.
2164  */
2165 int __sys_sendto(int fd, void __user *buff, size_t len, unsigned int flags,
2166 		 struct sockaddr __user *addr,  int addr_len)
2167 {
2168 	struct socket *sock;
2169 	struct sockaddr_storage address;
2170 	int err;
2171 	struct msghdr msg;
2172 
2173 	err = import_ubuf(ITER_SOURCE, buff, len, &msg.msg_iter);
2174 	if (unlikely(err))
2175 		return err;
2176 
2177 	CLASS(fd, f)(fd);
2178 	if (fd_empty(f))
2179 		return -EBADF;
2180 	sock = sock_from_file(fd_file(f));
2181 	if (unlikely(!sock))
2182 		return -ENOTSOCK;
2183 
2184 	msg.msg_name = NULL;
2185 	msg.msg_control = NULL;
2186 	msg.msg_controllen = 0;
2187 	msg.msg_namelen = 0;
2188 	msg.msg_ubuf = NULL;
2189 	if (addr) {
2190 		err = move_addr_to_kernel(addr, addr_len, &address);
2191 		if (err < 0)
2192 			return err;
2193 		msg.msg_name = (struct sockaddr *)&address;
2194 		msg.msg_namelen = addr_len;
2195 	}
2196 	flags &= ~MSG_INTERNAL_SENDMSG_FLAGS;
2197 	if (sock->file->f_flags & O_NONBLOCK)
2198 		flags |= MSG_DONTWAIT;
2199 	msg.msg_flags = flags;
2200 	return __sock_sendmsg(sock, &msg);
2201 }
2202 
2203 SYSCALL_DEFINE6(sendto, int, fd, void __user *, buff, size_t, len,
2204 		unsigned int, flags, struct sockaddr __user *, addr,
2205 		int, addr_len)
2206 {
2207 	return __sys_sendto(fd, buff, len, flags, addr, addr_len);
2208 }
2209 
2210 /*
2211  *	Send a datagram down a socket.
2212  */
2213 
2214 SYSCALL_DEFINE4(send, int, fd, void __user *, buff, size_t, len,
2215 		unsigned int, flags)
2216 {
2217 	return __sys_sendto(fd, buff, len, flags, NULL, 0);
2218 }
2219 
2220 /*
2221  *	Receive a frame from the socket and optionally record the address of the
2222  *	sender. We verify the buffers are writable and if needed move the
2223  *	sender address from kernel to user space.
2224  */
2225 int __sys_recvfrom(int fd, void __user *ubuf, size_t size, unsigned int flags,
2226 		   struct sockaddr __user *addr, int __user *addr_len)
2227 {
2228 	struct sockaddr_storage address;
2229 	struct msghdr msg = {
2230 		/* Save some cycles and don't copy the address if not needed */
2231 		.msg_name = addr ? (struct sockaddr *)&address : NULL,
2232 	};
2233 	struct socket *sock;
2234 	int err, err2;
2235 
2236 	err = import_ubuf(ITER_DEST, ubuf, size, &msg.msg_iter);
2237 	if (unlikely(err))
2238 		return err;
2239 
2240 	CLASS(fd, f)(fd);
2241 
2242 	if (fd_empty(f))
2243 		return -EBADF;
2244 	sock = sock_from_file(fd_file(f));
2245 	if (unlikely(!sock))
2246 		return -ENOTSOCK;
2247 
2248 	if (sock->file->f_flags & O_NONBLOCK)
2249 		flags |= MSG_DONTWAIT;
2250 	err = sock_recvmsg(sock, &msg, flags);
2251 
2252 	if (err >= 0 && addr != NULL) {
2253 		err2 = move_addr_to_user(&address,
2254 					 msg.msg_namelen, addr, addr_len);
2255 		if (err2 < 0)
2256 			err = err2;
2257 	}
2258 	return err;
2259 }
2260 
2261 SYSCALL_DEFINE6(recvfrom, int, fd, void __user *, ubuf, size_t, size,
2262 		unsigned int, flags, struct sockaddr __user *, addr,
2263 		int __user *, addr_len)
2264 {
2265 	return __sys_recvfrom(fd, ubuf, size, flags, addr, addr_len);
2266 }
2267 
2268 /*
2269  *	Receive a datagram from a socket.
2270  */
2271 
2272 SYSCALL_DEFINE4(recv, int, fd, void __user *, ubuf, size_t, size,
2273 		unsigned int, flags)
2274 {
2275 	return __sys_recvfrom(fd, ubuf, size, flags, NULL, NULL);
2276 }
2277 
2278 static bool sock_use_custom_sol_socket(const struct socket *sock)
2279 {
2280 	return test_bit(SOCK_CUSTOM_SOCKOPT, &sock->flags);
2281 }
2282 
2283 int do_sock_setsockopt(struct socket *sock, bool compat, int level,
2284 		       int optname, sockptr_t optval, int optlen)
2285 {
2286 	const struct proto_ops *ops;
2287 	char *kernel_optval = NULL;
2288 	int err;
2289 
2290 	if (optlen < 0)
2291 		return -EINVAL;
2292 
2293 	err = security_socket_setsockopt(sock, level, optname);
2294 	if (err)
2295 		goto out_put;
2296 
2297 	if (!compat)
2298 		err = BPF_CGROUP_RUN_PROG_SETSOCKOPT(sock->sk, &level, &optname,
2299 						     optval, &optlen,
2300 						     &kernel_optval);
2301 	if (err < 0)
2302 		goto out_put;
2303 	if (err > 0) {
2304 		err = 0;
2305 		goto out_put;
2306 	}
2307 
2308 	if (kernel_optval)
2309 		optval = KERNEL_SOCKPTR(kernel_optval);
2310 	ops = READ_ONCE(sock->ops);
2311 	if (level == SOL_SOCKET && !sock_use_custom_sol_socket(sock))
2312 		err = sock_setsockopt(sock, level, optname, optval, optlen);
2313 	else if (unlikely(!ops->setsockopt))
2314 		err = -EOPNOTSUPP;
2315 	else
2316 		err = ops->setsockopt(sock, level, optname, optval,
2317 					    optlen);
2318 	kfree(kernel_optval);
2319 out_put:
2320 	return err;
2321 }
2322 EXPORT_SYMBOL(do_sock_setsockopt);
2323 
2324 /* Set a socket option. Because we don't know the option lengths we have
2325  * to pass the user mode parameter for the protocols to sort out.
2326  */
2327 int __sys_setsockopt(int fd, int level, int optname, char __user *user_optval,
2328 		     int optlen)
2329 {
2330 	sockptr_t optval = USER_SOCKPTR(user_optval);
2331 	bool compat = in_compat_syscall();
2332 	struct socket *sock;
2333 	CLASS(fd, f)(fd);
2334 
2335 	if (fd_empty(f))
2336 		return -EBADF;
2337 	sock = sock_from_file(fd_file(f));
2338 	if (unlikely(!sock))
2339 		return -ENOTSOCK;
2340 
2341 	return do_sock_setsockopt(sock, compat, level, optname, optval, optlen);
2342 }
2343 
2344 SYSCALL_DEFINE5(setsockopt, int, fd, int, level, int, optname,
2345 		char __user *, optval, int, optlen)
2346 {
2347 	return __sys_setsockopt(fd, level, optname, optval, optlen);
2348 }
2349 
2350 INDIRECT_CALLABLE_DECLARE(bool tcp_bpf_bypass_getsockopt(int level,
2351 							 int optname));
2352 
2353 /*
2354  * Initialize a sockopt_t from sockptr optval/optlen, setting up iov_iter
2355  * for both input and output directions.
2356  * It is important to remember that both iov points to the same data, but,
2357  * .iter_in is read-only and .iter_out is write-only by the protocol callbacks
2358  */
2359 static int sockptr_to_sockopt(sockopt_t *opt, sockptr_t optval,
2360 			      sockptr_t optlen, struct kvec *kvec)
2361 {
2362 	int koptlen;
2363 
2364 	if (copy_from_sockptr(&koptlen, optlen, sizeof(int)))
2365 		return -EFAULT;
2366 
2367 	if (koptlen < 0)
2368 		return -EINVAL;
2369 
2370 	if (optval.is_kernel) {
2371 		kvec->iov_base = optval.kernel;
2372 		kvec->iov_len = koptlen;
2373 		iov_iter_kvec(&opt->iter_out, ITER_DEST, kvec, 1, koptlen);
2374 		iov_iter_kvec(&opt->iter_in, ITER_SOURCE, kvec, 1, koptlen);
2375 	} else {
2376 		iov_iter_ubuf(&opt->iter_out, ITER_DEST, optval.user, koptlen);
2377 		iov_iter_ubuf(&opt->iter_in, ITER_SOURCE, optval.user,
2378 			      koptlen);
2379 	}
2380 	opt->optlen = koptlen;
2381 
2382 	return 0;
2383 }
2384 
2385 int do_sock_getsockopt(struct socket *sock, bool compat, int level,
2386 		       int optname, sockptr_t optval, sockptr_t optlen)
2387 {
2388 	int max_optlen __maybe_unused = 0;
2389 	const struct proto_ops *ops;
2390 	struct kvec kvec;
2391 	sockopt_t opt;
2392 	int err;
2393 
2394 	err = security_socket_getsockopt(sock, level, optname);
2395 	if (err)
2396 		return err;
2397 
2398 	if (!compat)
2399 		copy_from_sockptr(&max_optlen, optlen, sizeof(int));
2400 
2401 	ops = READ_ONCE(sock->ops);
2402 	if (level == SOL_SOCKET) {
2403 		err = sk_getsockopt(sock->sk, level, optname, optval, optlen);
2404 	} else if (ops->getsockopt_iter) {
2405 		err = sockptr_to_sockopt(&opt, optval, optlen, &kvec);
2406 		if (err)
2407 			return err;
2408 
2409 		err = ops->getsockopt_iter(sock, level, optname, &opt);
2410 
2411 		/* Always write back optlen, even on failure. Some protocols
2412 		 * (e.g. CAN raw) return -ERANGE and set optlen to the
2413 		 * required buffer size so userspace can discover it.
2414 		 */
2415 		if (copy_to_sockptr(optlen, &opt.optlen, sizeof(int)))
2416 			return -EFAULT;
2417 	} else if (ops->getsockopt) {
2418 		if (WARN_ONCE(optval.is_kernel || optlen.is_kernel,
2419 			      "Invalid argument type"))
2420 			return -EOPNOTSUPP;
2421 
2422 		err = ops->getsockopt(sock, level, optname, optval.user,
2423 				      optlen.user);
2424 	} else {
2425 		err = -EOPNOTSUPP;
2426 	}
2427 
2428 	if (!compat)
2429 		err = BPF_CGROUP_RUN_PROG_GETSOCKOPT(sock->sk, level, optname,
2430 						     optval, optlen, max_optlen,
2431 						     err);
2432 
2433 	return err;
2434 }
2435 EXPORT_SYMBOL(do_sock_getsockopt);
2436 
2437 /*
2438  *	Get a socket option. Because we don't know the option lengths we have
2439  *	to pass a user mode parameter for the protocols to sort out.
2440  */
2441 int __sys_getsockopt(int fd, int level, int optname, char __user *optval,
2442 		int __user *optlen)
2443 {
2444 	struct socket *sock;
2445 	CLASS(fd, f)(fd);
2446 
2447 	if (fd_empty(f))
2448 		return -EBADF;
2449 	sock = sock_from_file(fd_file(f));
2450 	if (unlikely(!sock))
2451 		return -ENOTSOCK;
2452 
2453 	return do_sock_getsockopt(sock, in_compat_syscall(), level, optname,
2454 				 USER_SOCKPTR(optval), USER_SOCKPTR(optlen));
2455 }
2456 
2457 SYSCALL_DEFINE5(getsockopt, int, fd, int, level, int, optname,
2458 		char __user *, optval, int __user *, optlen)
2459 {
2460 	return __sys_getsockopt(fd, level, optname, optval, optlen);
2461 }
2462 
2463 /*
2464  *	Shutdown a socket.
2465  */
2466 
2467 int __sys_shutdown_sock(struct socket *sock, int how)
2468 {
2469 	int err;
2470 
2471 	err = security_socket_shutdown(sock, how);
2472 	if (!err)
2473 		err = READ_ONCE(sock->ops)->shutdown(sock, how);
2474 
2475 	return err;
2476 }
2477 
2478 int __sys_shutdown(int fd, int how)
2479 {
2480 	struct socket *sock;
2481 	CLASS(fd, f)(fd);
2482 
2483 	if (fd_empty(f))
2484 		return -EBADF;
2485 	sock = sock_from_file(fd_file(f));
2486 	if (unlikely(!sock))
2487 		return -ENOTSOCK;
2488 
2489 	return __sys_shutdown_sock(sock, how);
2490 }
2491 
2492 SYSCALL_DEFINE2(shutdown, int, fd, int, how)
2493 {
2494 	return __sys_shutdown(fd, how);
2495 }
2496 
2497 /* A couple of helpful macros for getting the address of the 32/64 bit
2498  * fields which are the same type (int / unsigned) on our platforms.
2499  */
2500 #define COMPAT_MSG(msg, member)	((MSG_CMSG_COMPAT & flags) ? &msg##_compat->member : &msg->member)
2501 #define COMPAT_NAMELEN(msg)	COMPAT_MSG(msg, msg_namelen)
2502 #define COMPAT_FLAGS(msg)	COMPAT_MSG(msg, msg_flags)
2503 
2504 struct used_address {
2505 	struct sockaddr_storage name;
2506 	unsigned int name_len;
2507 };
2508 
2509 int __copy_msghdr(struct msghdr *kmsg,
2510 		  struct user_msghdr *msg,
2511 		  struct sockaddr __user **save_addr)
2512 {
2513 	ssize_t err;
2514 
2515 	kmsg->msg_control_is_user = true;
2516 	kmsg->msg_get_inq = 0;
2517 	kmsg->msg_control_user = msg->msg_control;
2518 	kmsg->msg_controllen = msg->msg_controllen;
2519 	kmsg->msg_flags = msg->msg_flags;
2520 
2521 	kmsg->msg_namelen = msg->msg_namelen;
2522 	if (!msg->msg_name)
2523 		kmsg->msg_namelen = 0;
2524 
2525 	if (kmsg->msg_namelen < 0)
2526 		return -EINVAL;
2527 
2528 	if (kmsg->msg_namelen > sizeof(struct sockaddr_storage))
2529 		kmsg->msg_namelen = sizeof(struct sockaddr_storage);
2530 
2531 	if (save_addr)
2532 		*save_addr = msg->msg_name;
2533 
2534 	if (msg->msg_name && kmsg->msg_namelen) {
2535 		if (!save_addr) {
2536 			err = move_addr_to_kernel(msg->msg_name,
2537 						  kmsg->msg_namelen,
2538 						  kmsg->msg_name);
2539 			if (err < 0)
2540 				return err;
2541 		}
2542 	} else {
2543 		kmsg->msg_name = NULL;
2544 		kmsg->msg_namelen = 0;
2545 	}
2546 
2547 	if (msg->msg_iovlen > UIO_MAXIOV)
2548 		return -EMSGSIZE;
2549 
2550 	kmsg->msg_iocb = NULL;
2551 	kmsg->msg_ubuf = NULL;
2552 	return 0;
2553 }
2554 
2555 static int copy_msghdr_from_user(struct msghdr *kmsg,
2556 				 struct user_msghdr __user *umsg,
2557 				 struct sockaddr __user **save_addr,
2558 				 struct iovec **iov)
2559 {
2560 	struct user_msghdr msg;
2561 	ssize_t err;
2562 
2563 	if (copy_from_user(&msg, umsg, sizeof(*umsg)))
2564 		return -EFAULT;
2565 
2566 	err = __copy_msghdr(kmsg, &msg, save_addr);
2567 	if (err)
2568 		return err;
2569 
2570 	err = import_iovec(save_addr ? ITER_DEST : ITER_SOURCE,
2571 			    msg.msg_iov, msg.msg_iovlen,
2572 			    UIO_FASTIOV, iov, &kmsg->msg_iter);
2573 	return err < 0 ? err : 0;
2574 }
2575 
2576 static int ____sys_sendmsg(struct socket *sock, struct msghdr *msg_sys,
2577 			   unsigned int flags, struct used_address *used_address,
2578 			   unsigned int allowed_msghdr_flags)
2579 {
2580 	unsigned char ctl[sizeof(struct cmsghdr) + 20]
2581 				__aligned(sizeof(__kernel_size_t));
2582 	/* 20 is size of ipv6_pktinfo */
2583 	unsigned char *ctl_buf = ctl;
2584 	int ctl_len;
2585 	ssize_t err;
2586 
2587 	err = -ENOBUFS;
2588 
2589 	if (msg_sys->msg_controllen > INT_MAX)
2590 		goto out;
2591 	flags |= (msg_sys->msg_flags & allowed_msghdr_flags);
2592 	ctl_len = msg_sys->msg_controllen;
2593 	if ((MSG_CMSG_COMPAT & flags) && ctl_len) {
2594 		err =
2595 		    cmsghdr_from_user_compat_to_kern(msg_sys, sock->sk, ctl,
2596 						     sizeof(ctl));
2597 		if (err)
2598 			goto out;
2599 		ctl_buf = msg_sys->msg_control;
2600 		ctl_len = msg_sys->msg_controllen;
2601 	} else if (ctl_len) {
2602 		BUILD_BUG_ON(sizeof(struct cmsghdr) !=
2603 			     CMSG_ALIGN(sizeof(struct cmsghdr)));
2604 		if (ctl_len > sizeof(ctl)) {
2605 			ctl_buf = sock_kmalloc(sock->sk, ctl_len, GFP_KERNEL);
2606 			if (ctl_buf == NULL)
2607 				goto out;
2608 		}
2609 		err = -EFAULT;
2610 		if (copy_from_user(ctl_buf, msg_sys->msg_control_user, ctl_len))
2611 			goto out_freectl;
2612 		msg_sys->msg_control = ctl_buf;
2613 		msg_sys->msg_control_is_user = false;
2614 	}
2615 	flags &= ~MSG_INTERNAL_SENDMSG_FLAGS;
2616 	msg_sys->msg_flags = flags;
2617 
2618 	if (sock->file->f_flags & O_NONBLOCK)
2619 		msg_sys->msg_flags |= MSG_DONTWAIT;
2620 	/*
2621 	 * If this is sendmmsg() and current destination address is same as
2622 	 * previously succeeded address, omit asking LSM's decision.
2623 	 * used_address->name_len is initialized to UINT_MAX so that the first
2624 	 * destination address never matches.
2625 	 */
2626 	if (used_address && msg_sys->msg_name &&
2627 	    used_address->name_len == msg_sys->msg_namelen &&
2628 	    !memcmp(&used_address->name, msg_sys->msg_name,
2629 		    used_address->name_len)) {
2630 		err = sock_sendmsg_nosec(sock, msg_sys);
2631 		goto out_freectl;
2632 	}
2633 	err = __sock_sendmsg(sock, msg_sys);
2634 	/*
2635 	 * If this is sendmmsg() and sending to current destination address was
2636 	 * successful, remember it.
2637 	 */
2638 	if (used_address && err >= 0) {
2639 		used_address->name_len = msg_sys->msg_namelen;
2640 		if (msg_sys->msg_name)
2641 			memcpy(&used_address->name, msg_sys->msg_name,
2642 			       used_address->name_len);
2643 	}
2644 
2645 out_freectl:
2646 	if (ctl_buf != ctl)
2647 		sock_kfree_s(sock->sk, ctl_buf, ctl_len);
2648 out:
2649 	return err;
2650 }
2651 
2652 static int sendmsg_copy_msghdr(struct msghdr *msg,
2653 			       struct user_msghdr __user *umsg, unsigned flags,
2654 			       struct iovec **iov)
2655 {
2656 	int err;
2657 
2658 	if (flags & MSG_CMSG_COMPAT) {
2659 		struct compat_msghdr __user *msg_compat;
2660 
2661 		msg_compat = (struct compat_msghdr __user *) umsg;
2662 		err = get_compat_msghdr(msg, msg_compat, NULL, iov);
2663 	} else {
2664 		err = copy_msghdr_from_user(msg, umsg, NULL, iov);
2665 	}
2666 	if (err < 0)
2667 		return err;
2668 
2669 	return 0;
2670 }
2671 
2672 static int ___sys_sendmsg(struct socket *sock, struct user_msghdr __user *msg,
2673 			 struct msghdr *msg_sys, unsigned int flags,
2674 			 struct used_address *used_address,
2675 			 unsigned int allowed_msghdr_flags)
2676 {
2677 	struct sockaddr_storage address;
2678 	struct iovec iovstack[UIO_FASTIOV], *iov = iovstack;
2679 	ssize_t err;
2680 
2681 	msg_sys->msg_name = &address;
2682 
2683 	err = sendmsg_copy_msghdr(msg_sys, msg, flags, &iov);
2684 	if (err < 0)
2685 		return err;
2686 
2687 	err = ____sys_sendmsg(sock, msg_sys, flags, used_address,
2688 				allowed_msghdr_flags);
2689 	kfree(iov);
2690 	return err;
2691 }
2692 
2693 /*
2694  *	BSD sendmsg interface
2695  */
2696 long __sys_sendmsg_sock(struct socket *sock, struct msghdr *msg,
2697 			unsigned int flags)
2698 {
2699 	return ____sys_sendmsg(sock, msg, flags, NULL, 0);
2700 }
2701 
2702 long __sys_sendmsg(int fd, struct user_msghdr __user *msg, unsigned int flags,
2703 		   bool forbid_cmsg_compat)
2704 {
2705 	struct msghdr msg_sys;
2706 	struct socket *sock;
2707 
2708 	if (forbid_cmsg_compat && (flags & MSG_CMSG_COMPAT))
2709 		return -EINVAL;
2710 
2711 	CLASS(fd, f)(fd);
2712 
2713 	if (fd_empty(f))
2714 		return -EBADF;
2715 	sock = sock_from_file(fd_file(f));
2716 	if (unlikely(!sock))
2717 		return -ENOTSOCK;
2718 
2719 	return ___sys_sendmsg(sock, msg, &msg_sys, flags, NULL, 0);
2720 }
2721 
2722 SYSCALL_DEFINE3(sendmsg, int, fd, struct user_msghdr __user *, msg, unsigned int, flags)
2723 {
2724 	return __sys_sendmsg(fd, msg, flags, true);
2725 }
2726 
2727 /*
2728  *	Linux sendmmsg interface
2729  */
2730 
2731 int __sys_sendmmsg(int fd, struct mmsghdr __user *mmsg, unsigned int vlen,
2732 		   unsigned int flags, bool forbid_cmsg_compat)
2733 {
2734 	int err, datagrams;
2735 	struct socket *sock;
2736 	struct mmsghdr __user *entry;
2737 	struct compat_mmsghdr __user *compat_entry;
2738 	struct msghdr msg_sys;
2739 	struct used_address used_address;
2740 	unsigned int oflags = flags;
2741 
2742 	if (forbid_cmsg_compat && (flags & MSG_CMSG_COMPAT))
2743 		return -EINVAL;
2744 
2745 	if (vlen > UIO_MAXIOV)
2746 		vlen = UIO_MAXIOV;
2747 
2748 	datagrams = 0;
2749 
2750 	CLASS(fd, f)(fd);
2751 
2752 	if (fd_empty(f))
2753 		return -EBADF;
2754 	sock = sock_from_file(fd_file(f));
2755 	if (unlikely(!sock))
2756 		return -ENOTSOCK;
2757 
2758 	used_address.name_len = UINT_MAX;
2759 	entry = mmsg;
2760 	compat_entry = (struct compat_mmsghdr __user *)mmsg;
2761 	err = 0;
2762 	flags |= MSG_BATCH;
2763 
2764 	while (datagrams < vlen) {
2765 		if (datagrams == vlen - 1)
2766 			flags = oflags;
2767 
2768 		if (MSG_CMSG_COMPAT & flags) {
2769 			err = ___sys_sendmsg(sock, (struct user_msghdr __user *)compat_entry,
2770 					     &msg_sys, flags, &used_address, MSG_EOR);
2771 			if (err < 0)
2772 				break;
2773 			err = __put_user(err, &compat_entry->msg_len);
2774 			++compat_entry;
2775 		} else {
2776 			err = ___sys_sendmsg(sock,
2777 					     (struct user_msghdr __user *)entry,
2778 					     &msg_sys, flags, &used_address, MSG_EOR);
2779 			if (err < 0)
2780 				break;
2781 			err = put_user(err, &entry->msg_len);
2782 			++entry;
2783 		}
2784 
2785 		if (err)
2786 			break;
2787 		++datagrams;
2788 		if (msg_data_left(&msg_sys))
2789 			break;
2790 		cond_resched();
2791 	}
2792 
2793 	/* We only return an error if no datagrams were able to be sent */
2794 	if (datagrams != 0)
2795 		return datagrams;
2796 
2797 	return err;
2798 }
2799 
2800 SYSCALL_DEFINE4(sendmmsg, int, fd, struct mmsghdr __user *, mmsg,
2801 		unsigned int, vlen, unsigned int, flags)
2802 {
2803 	return __sys_sendmmsg(fd, mmsg, vlen, flags, true);
2804 }
2805 
2806 static int recvmsg_copy_msghdr(struct msghdr *msg,
2807 			       struct user_msghdr __user *umsg, unsigned flags,
2808 			       struct sockaddr __user **uaddr,
2809 			       struct iovec **iov)
2810 {
2811 	ssize_t err;
2812 
2813 	if (MSG_CMSG_COMPAT & flags) {
2814 		struct compat_msghdr __user *msg_compat;
2815 
2816 		msg_compat = (struct compat_msghdr __user *) umsg;
2817 		err = get_compat_msghdr(msg, msg_compat, uaddr, iov);
2818 	} else {
2819 		err = copy_msghdr_from_user(msg, umsg, uaddr, iov);
2820 	}
2821 	if (err < 0)
2822 		return err;
2823 
2824 	return 0;
2825 }
2826 
2827 static int ____sys_recvmsg(struct socket *sock, struct msghdr *msg_sys,
2828 			   struct user_msghdr __user *msg,
2829 			   struct sockaddr __user *uaddr,
2830 			   unsigned int flags, int nosec)
2831 {
2832 	struct compat_msghdr __user *msg_compat =
2833 					(struct compat_msghdr __user *) msg;
2834 	int __user *uaddr_len = COMPAT_NAMELEN(msg);
2835 	struct sockaddr_storage addr;
2836 	unsigned long cmsg_ptr;
2837 	int len;
2838 	ssize_t err;
2839 
2840 	msg_sys->msg_name = &addr;
2841 	cmsg_ptr = (unsigned long)msg_sys->msg_control;
2842 	msg_sys->msg_flags = flags & (MSG_CMSG_CLOEXEC|MSG_CMSG_COMPAT);
2843 
2844 	/* We assume all kernel code knows the size of sockaddr_storage */
2845 	msg_sys->msg_namelen = 0;
2846 
2847 	if (sock->file->f_flags & O_NONBLOCK)
2848 		flags |= MSG_DONTWAIT;
2849 
2850 	if (unlikely(nosec))
2851 		err = sock_recvmsg_nosec(sock, msg_sys, flags);
2852 	else
2853 		err = sock_recvmsg(sock, msg_sys, flags);
2854 
2855 	if (err < 0)
2856 		goto out;
2857 	len = err;
2858 
2859 	if (uaddr != NULL) {
2860 		err = move_addr_to_user(&addr,
2861 					msg_sys->msg_namelen, uaddr,
2862 					uaddr_len);
2863 		if (err < 0)
2864 			goto out;
2865 	}
2866 	err = __put_user((msg_sys->msg_flags & ~MSG_CMSG_COMPAT),
2867 			 COMPAT_FLAGS(msg));
2868 	if (err)
2869 		goto out;
2870 	if (MSG_CMSG_COMPAT & flags)
2871 		err = __put_user((unsigned long)msg_sys->msg_control - cmsg_ptr,
2872 				 &msg_compat->msg_controllen);
2873 	else
2874 		err = __put_user((unsigned long)msg_sys->msg_control - cmsg_ptr,
2875 				 &msg->msg_controllen);
2876 	if (err)
2877 		goto out;
2878 	err = len;
2879 out:
2880 	return err;
2881 }
2882 
2883 static int ___sys_recvmsg(struct socket *sock, struct user_msghdr __user *msg,
2884 			 struct msghdr *msg_sys, unsigned int flags, int nosec)
2885 {
2886 	struct iovec iovstack[UIO_FASTIOV], *iov = iovstack;
2887 	/* user mode address pointers */
2888 	struct sockaddr __user *uaddr;
2889 	ssize_t err;
2890 
2891 	err = recvmsg_copy_msghdr(msg_sys, msg, flags, &uaddr, &iov);
2892 	if (err < 0)
2893 		return err;
2894 
2895 	err = ____sys_recvmsg(sock, msg_sys, msg, uaddr, flags, nosec);
2896 	kfree(iov);
2897 	return err;
2898 }
2899 
2900 /*
2901  *	BSD recvmsg interface
2902  */
2903 
2904 long __sys_recvmsg_sock(struct socket *sock, struct msghdr *msg,
2905 			struct user_msghdr __user *umsg,
2906 			struct sockaddr __user *uaddr, unsigned int flags)
2907 {
2908 	return ____sys_recvmsg(sock, msg, umsg, uaddr, flags, 0);
2909 }
2910 
2911 long __sys_recvmsg(int fd, struct user_msghdr __user *msg, unsigned int flags,
2912 		   bool forbid_cmsg_compat)
2913 {
2914 	struct msghdr msg_sys;
2915 	struct socket *sock;
2916 
2917 	if (forbid_cmsg_compat && (flags & MSG_CMSG_COMPAT))
2918 		return -EINVAL;
2919 
2920 	CLASS(fd, f)(fd);
2921 
2922 	if (fd_empty(f))
2923 		return -EBADF;
2924 	sock = sock_from_file(fd_file(f));
2925 	if (unlikely(!sock))
2926 		return -ENOTSOCK;
2927 
2928 	return ___sys_recvmsg(sock, msg, &msg_sys, flags, 0);
2929 }
2930 
2931 SYSCALL_DEFINE3(recvmsg, int, fd, struct user_msghdr __user *, msg,
2932 		unsigned int, flags)
2933 {
2934 	return __sys_recvmsg(fd, msg, flags, true);
2935 }
2936 
2937 /*
2938  *     Linux recvmmsg interface
2939  */
2940 
2941 static int do_recvmmsg(int fd, struct mmsghdr __user *mmsg,
2942 			  unsigned int vlen, unsigned int flags,
2943 			  struct timespec64 *timeout)
2944 {
2945 	int err = 0, datagrams;
2946 	struct socket *sock;
2947 	struct mmsghdr __user *entry;
2948 	struct compat_mmsghdr __user *compat_entry;
2949 	struct msghdr msg_sys;
2950 	struct timespec64 end_time;
2951 	struct timespec64 timeout64;
2952 
2953 	if (timeout &&
2954 	    poll_select_set_timeout(&end_time, timeout->tv_sec,
2955 				    timeout->tv_nsec))
2956 		return -EINVAL;
2957 
2958 	datagrams = 0;
2959 
2960 	CLASS(fd, f)(fd);
2961 
2962 	if (fd_empty(f))
2963 		return -EBADF;
2964 	sock = sock_from_file(fd_file(f));
2965 	if (unlikely(!sock))
2966 		return -ENOTSOCK;
2967 
2968 	if (likely(!(flags & MSG_ERRQUEUE))) {
2969 		err = sock_error(sock->sk);
2970 		if (err)
2971 			return err;
2972 	}
2973 
2974 	entry = mmsg;
2975 	compat_entry = (struct compat_mmsghdr __user *)mmsg;
2976 
2977 	while (datagrams < vlen) {
2978 		/*
2979 		 * No need to ask LSM for more than the first datagram.
2980 		 */
2981 		if (MSG_CMSG_COMPAT & flags) {
2982 			err = ___sys_recvmsg(sock, (struct user_msghdr __user *)compat_entry,
2983 					     &msg_sys, flags & ~MSG_WAITFORONE,
2984 					     datagrams);
2985 			if (err < 0)
2986 				break;
2987 			err = __put_user(err, &compat_entry->msg_len);
2988 			++compat_entry;
2989 		} else {
2990 			err = ___sys_recvmsg(sock,
2991 					     (struct user_msghdr __user *)entry,
2992 					     &msg_sys, flags & ~MSG_WAITFORONE,
2993 					     datagrams);
2994 			if (err < 0)
2995 				break;
2996 			err = put_user(err, &entry->msg_len);
2997 			++entry;
2998 		}
2999 
3000 		if (err)
3001 			break;
3002 		++datagrams;
3003 
3004 		/* MSG_WAITFORONE turns on MSG_DONTWAIT after one packet */
3005 		if (flags & MSG_WAITFORONE)
3006 			flags |= MSG_DONTWAIT;
3007 
3008 		if (timeout) {
3009 			ktime_get_ts64(&timeout64);
3010 			*timeout = timespec64_sub(end_time, timeout64);
3011 			if (timeout->tv_sec < 0) {
3012 				timeout->tv_sec = timeout->tv_nsec = 0;
3013 				break;
3014 			}
3015 
3016 			/* Timeout, return less than vlen datagrams */
3017 			if (timeout->tv_nsec == 0 && timeout->tv_sec == 0)
3018 				break;
3019 		}
3020 
3021 		/* Out of band data, return right away */
3022 		if (msg_sys.msg_flags & MSG_OOB)
3023 			break;
3024 		cond_resched();
3025 	}
3026 
3027 	if (err == 0)
3028 		return datagrams;
3029 
3030 	if (datagrams == 0)
3031 		return err;
3032 
3033 	/*
3034 	 * We may return less entries than requested (vlen) if the
3035 	 * sock is non block and there aren't enough datagrams...
3036 	 */
3037 	if (err != -EAGAIN) {
3038 		/*
3039 		 * ... or  if recvmsg returns an error after we
3040 		 * received some datagrams, where we record the
3041 		 * error to return on the next call or if the
3042 		 * app asks about it using getsockopt(SO_ERROR).
3043 		 */
3044 		WRITE_ONCE(sock->sk->sk_err, -err);
3045 	}
3046 	return datagrams;
3047 }
3048 
3049 int __sys_recvmmsg(int fd, struct mmsghdr __user *mmsg,
3050 		   unsigned int vlen, unsigned int flags,
3051 		   struct __kernel_timespec __user *timeout,
3052 		   struct old_timespec32 __user *timeout32)
3053 {
3054 	int datagrams;
3055 	struct timespec64 timeout_sys;
3056 
3057 	if (timeout && get_timespec64(&timeout_sys, timeout))
3058 		return -EFAULT;
3059 
3060 	if (timeout32 && get_old_timespec32(&timeout_sys, timeout32))
3061 		return -EFAULT;
3062 
3063 	if (!timeout && !timeout32)
3064 		return do_recvmmsg(fd, mmsg, vlen, flags, NULL);
3065 
3066 	datagrams = do_recvmmsg(fd, mmsg, vlen, flags, &timeout_sys);
3067 
3068 	if (datagrams <= 0)
3069 		return datagrams;
3070 
3071 	if (timeout && put_timespec64(&timeout_sys, timeout))
3072 		datagrams = -EFAULT;
3073 
3074 	if (timeout32 && put_old_timespec32(&timeout_sys, timeout32))
3075 		datagrams = -EFAULT;
3076 
3077 	return datagrams;
3078 }
3079 
3080 SYSCALL_DEFINE5(recvmmsg, int, fd, struct mmsghdr __user *, mmsg,
3081 		unsigned int, vlen, unsigned int, flags,
3082 		struct __kernel_timespec __user *, timeout)
3083 {
3084 	if (flags & MSG_CMSG_COMPAT)
3085 		return -EINVAL;
3086 
3087 	return __sys_recvmmsg(fd, mmsg, vlen, flags, timeout, NULL);
3088 }
3089 
3090 #ifdef CONFIG_COMPAT_32BIT_TIME
3091 SYSCALL_DEFINE5(recvmmsg_time32, int, fd, struct mmsghdr __user *, mmsg,
3092 		unsigned int, vlen, unsigned int, flags,
3093 		struct old_timespec32 __user *, timeout)
3094 {
3095 	if (flags & MSG_CMSG_COMPAT)
3096 		return -EINVAL;
3097 
3098 	return __sys_recvmmsg(fd, mmsg, vlen, flags, NULL, timeout);
3099 }
3100 #endif
3101 
3102 #ifdef __ARCH_WANT_SYS_SOCKETCALL
3103 /* Argument list sizes for sys_socketcall */
3104 #define AL(x) ((x) * sizeof(unsigned long))
3105 static const unsigned char nargs[21] = {
3106 	AL(0), AL(3), AL(3), AL(3), AL(2), AL(3),
3107 	AL(3), AL(3), AL(4), AL(4), AL(4), AL(6),
3108 	AL(6), AL(2), AL(5), AL(5), AL(3), AL(3),
3109 	AL(4), AL(5), AL(4)
3110 };
3111 
3112 #undef AL
3113 
3114 /*
3115  *	System call vectors.
3116  *
3117  *	Argument checking cleaned up. Saved 20% in size.
3118  *  This function doesn't need to set the kernel lock because
3119  *  it is set by the callees.
3120  */
3121 
3122 SYSCALL_DEFINE2(socketcall, int, call, unsigned long __user *, args)
3123 {
3124 	unsigned long a[AUDITSC_ARGS];
3125 	unsigned long a0, a1;
3126 	int err;
3127 	unsigned int len;
3128 
3129 	if (call < 1 || call > SYS_SENDMMSG)
3130 		return -EINVAL;
3131 	call = array_index_nospec(call, SYS_SENDMMSG + 1);
3132 
3133 	len = nargs[call];
3134 	if (len > sizeof(a))
3135 		return -EINVAL;
3136 
3137 	/* copy_from_user should be SMP safe. */
3138 	if (copy_from_user(a, args, len))
3139 		return -EFAULT;
3140 
3141 	err = audit_socketcall(nargs[call] / sizeof(unsigned long), a);
3142 	if (err)
3143 		return err;
3144 
3145 	a0 = a[0];
3146 	a1 = a[1];
3147 
3148 	switch (call) {
3149 	case SYS_SOCKET:
3150 		err = __sys_socket(a0, a1, a[2]);
3151 		break;
3152 	case SYS_BIND:
3153 		err = __sys_bind(a0, (struct sockaddr __user *)a1, a[2]);
3154 		break;
3155 	case SYS_CONNECT:
3156 		err = __sys_connect(a0, (struct sockaddr __user *)a1, a[2]);
3157 		break;
3158 	case SYS_LISTEN:
3159 		err = __sys_listen(a0, a1);
3160 		break;
3161 	case SYS_ACCEPT:
3162 		err = __sys_accept4(a0, (struct sockaddr __user *)a1,
3163 				    (int __user *)a[2], 0);
3164 		break;
3165 	case SYS_GETSOCKNAME:
3166 		err =
3167 		    __sys_getsockname(a0, (struct sockaddr __user *)a1,
3168 				      (int __user *)a[2], 0);
3169 		break;
3170 	case SYS_GETPEERNAME:
3171 		err =
3172 		    __sys_getsockname(a0, (struct sockaddr __user *)a1,
3173 				      (int __user *)a[2], 1);
3174 		break;
3175 	case SYS_SOCKETPAIR:
3176 		err = __sys_socketpair(a0, a1, a[2], (int __user *)a[3]);
3177 		break;
3178 	case SYS_SEND:
3179 		err = __sys_sendto(a0, (void __user *)a1, a[2], a[3],
3180 				   NULL, 0);
3181 		break;
3182 	case SYS_SENDTO:
3183 		err = __sys_sendto(a0, (void __user *)a1, a[2], a[3],
3184 				   (struct sockaddr __user *)a[4], a[5]);
3185 		break;
3186 	case SYS_RECV:
3187 		err = __sys_recvfrom(a0, (void __user *)a1, a[2], a[3],
3188 				     NULL, NULL);
3189 		break;
3190 	case SYS_RECVFROM:
3191 		err = __sys_recvfrom(a0, (void __user *)a1, a[2], a[3],
3192 				     (struct sockaddr __user *)a[4],
3193 				     (int __user *)a[5]);
3194 		break;
3195 	case SYS_SHUTDOWN:
3196 		err = __sys_shutdown(a0, a1);
3197 		break;
3198 	case SYS_SETSOCKOPT:
3199 		err = __sys_setsockopt(a0, a1, a[2], (char __user *)a[3],
3200 				       a[4]);
3201 		break;
3202 	case SYS_GETSOCKOPT:
3203 		err =
3204 		    __sys_getsockopt(a0, a1, a[2], (char __user *)a[3],
3205 				     (int __user *)a[4]);
3206 		break;
3207 	case SYS_SENDMSG:
3208 		err = __sys_sendmsg(a0, (struct user_msghdr __user *)a1,
3209 				    a[2], true);
3210 		break;
3211 	case SYS_SENDMMSG:
3212 		err = __sys_sendmmsg(a0, (struct mmsghdr __user *)a1, a[2],
3213 				     a[3], true);
3214 		break;
3215 	case SYS_RECVMSG:
3216 		err = __sys_recvmsg(a0, (struct user_msghdr __user *)a1,
3217 				    a[2], true);
3218 		break;
3219 	case SYS_RECVMMSG:
3220 		if (IS_ENABLED(CONFIG_64BIT))
3221 			err = __sys_recvmmsg(a0, (struct mmsghdr __user *)a1,
3222 					     a[2], a[3],
3223 					     (struct __kernel_timespec __user *)a[4],
3224 					     NULL);
3225 		else
3226 			err = __sys_recvmmsg(a0, (struct mmsghdr __user *)a1,
3227 					     a[2], a[3], NULL,
3228 					     (struct old_timespec32 __user *)a[4]);
3229 		break;
3230 	case SYS_ACCEPT4:
3231 		err = __sys_accept4(a0, (struct sockaddr __user *)a1,
3232 				    (int __user *)a[2], a[3]);
3233 		break;
3234 	default:
3235 		err = -EINVAL;
3236 		break;
3237 	}
3238 	return err;
3239 }
3240 
3241 #endif				/* __ARCH_WANT_SYS_SOCKETCALL */
3242 
3243 /**
3244  *	sock_register - add a socket protocol handler
3245  *	@ops: description of protocol
3246  *
3247  *	This function is called by a protocol handler that wants to
3248  *	advertise its address family, and have it linked into the
3249  *	socket interface. The value ops->family corresponds to the
3250  *	socket system call protocol family.
3251  */
3252 int sock_register(const struct net_proto_family *ops)
3253 {
3254 	int err;
3255 
3256 	if (ops->family >= NPROTO) {
3257 		pr_crit("protocol %d >= NPROTO(%d)\n", ops->family, NPROTO);
3258 		return -ENOBUFS;
3259 	}
3260 
3261 	spin_lock(&net_family_lock);
3262 	if (rcu_dereference_protected(net_families[ops->family],
3263 				      lockdep_is_held(&net_family_lock)))
3264 		err = -EEXIST;
3265 	else {
3266 		rcu_assign_pointer(net_families[ops->family], ops);
3267 		err = 0;
3268 	}
3269 	spin_unlock(&net_family_lock);
3270 
3271 	pr_info("NET: Registered %s protocol family\n", pf_family_names[ops->family]);
3272 	return err;
3273 }
3274 EXPORT_SYMBOL(sock_register);
3275 
3276 /**
3277  *	sock_unregister - remove a protocol handler
3278  *	@family: protocol family to remove
3279  *
3280  *	This function is called by a protocol handler that wants to
3281  *	remove its address family, and have it unlinked from the
3282  *	new socket creation.
3283  *
3284  *	If protocol handler is a module, then it can use module reference
3285  *	counts to protect against new references. If protocol handler is not
3286  *	a module then it needs to provide its own protection in
3287  *	the ops->create routine.
3288  */
3289 void sock_unregister(int family)
3290 {
3291 	BUG_ON(family < 0 || family >= NPROTO);
3292 
3293 	spin_lock(&net_family_lock);
3294 	RCU_INIT_POINTER(net_families[family], NULL);
3295 	spin_unlock(&net_family_lock);
3296 
3297 	synchronize_rcu();
3298 
3299 	pr_info("NET: Unregistered %s protocol family\n", pf_family_names[family]);
3300 }
3301 EXPORT_SYMBOL(sock_unregister);
3302 
3303 bool sock_is_registered(int family)
3304 {
3305 	return family < NPROTO && rcu_access_pointer(net_families[family]);
3306 }
3307 
3308 static int __init sock_init(void)
3309 {
3310 	int err;
3311 	/*
3312 	 *      Initialize the network sysctl infrastructure.
3313 	 */
3314 	err = net_sysctl_init();
3315 	if (err)
3316 		goto out;
3317 
3318 	/*
3319 	 *      Initialize skbuff SLAB cache
3320 	 */
3321 	skb_init();
3322 
3323 	/*
3324 	 *      Initialize the protocols module.
3325 	 */
3326 
3327 	init_inodecache();
3328 
3329 	err = register_filesystem(&sock_fs_type);
3330 	if (err)
3331 		goto out;
3332 	sock_mnt = kern_mount(&sock_fs_type);
3333 	if (IS_ERR(sock_mnt)) {
3334 		err = PTR_ERR(sock_mnt);
3335 		goto out_mount;
3336 	}
3337 
3338 	/* The real protocol initialization is performed in later initcalls.
3339 	 */
3340 
3341 #ifdef CONFIG_NETFILTER
3342 	err = netfilter_init();
3343 	if (err)
3344 		goto out;
3345 #endif
3346 
3347 	ptp_classifier_init();
3348 
3349 out:
3350 	return err;
3351 
3352 out_mount:
3353 	unregister_filesystem(&sock_fs_type);
3354 	goto out;
3355 }
3356 
3357 core_initcall(sock_init);	/* early initcall */
3358 
3359 #ifdef CONFIG_PROC_FS
3360 void socket_seq_show(struct seq_file *seq)
3361 {
3362 	seq_printf(seq, "sockets: used %d\n",
3363 		   sock_inuse_get(seq->private));
3364 }
3365 #endif				/* CONFIG_PROC_FS */
3366 
3367 /* Handle the fact that while struct ifreq has the same *layout* on
3368  * 32/64 for everything but ifreq::ifru_ifmap and ifreq::ifru_data,
3369  * which are handled elsewhere, it still has different *size* due to
3370  * ifreq::ifru_ifmap (which is 16 bytes on 32 bit, 24 bytes on 64-bit,
3371  * resulting in struct ifreq being 32 and 40 bytes respectively).
3372  * As a result, if the struct happens to be at the end of a page and
3373  * the next page isn't readable/writable, we get a fault. To prevent
3374  * that, copy back and forth to the full size.
3375  */
3376 int get_user_ifreq(struct ifreq *ifr, void __user **ifrdata, void __user *arg)
3377 {
3378 	if (in_compat_syscall()) {
3379 		struct compat_ifreq *ifr32 = (struct compat_ifreq *)ifr;
3380 
3381 		memset(ifr, 0, sizeof(*ifr));
3382 		if (copy_from_user(ifr32, arg, sizeof(*ifr32)))
3383 			return -EFAULT;
3384 
3385 		if (ifrdata)
3386 			*ifrdata = compat_ptr(ifr32->ifr_data);
3387 
3388 		return 0;
3389 	}
3390 
3391 	if (copy_from_user(ifr, arg, sizeof(*ifr)))
3392 		return -EFAULT;
3393 
3394 	if (ifrdata)
3395 		*ifrdata = ifr->ifr_data;
3396 
3397 	return 0;
3398 }
3399 EXPORT_SYMBOL(get_user_ifreq);
3400 
3401 int put_user_ifreq(struct ifreq *ifr, void __user *arg)
3402 {
3403 	size_t size = sizeof(*ifr);
3404 
3405 	if (in_compat_syscall())
3406 		size = sizeof(struct compat_ifreq);
3407 
3408 	if (copy_to_user(arg, ifr, size))
3409 		return -EFAULT;
3410 
3411 	return 0;
3412 }
3413 EXPORT_SYMBOL(put_user_ifreq);
3414 
3415 #ifdef CONFIG_COMPAT
3416 static int compat_siocwandev(struct net *net, struct compat_ifreq __user *uifr32)
3417 {
3418 	compat_uptr_t uptr32;
3419 	struct ifreq ifr;
3420 	void __user *saved;
3421 	int err;
3422 
3423 	if (get_user_ifreq(&ifr, NULL, uifr32))
3424 		return -EFAULT;
3425 
3426 	if (get_user(uptr32, &uifr32->ifr_settings.ifs_ifsu))
3427 		return -EFAULT;
3428 
3429 	saved = ifr.ifr_settings.ifs_ifsu.raw_hdlc;
3430 	ifr.ifr_settings.ifs_ifsu.raw_hdlc = compat_ptr(uptr32);
3431 
3432 	err = dev_ioctl(net, SIOCWANDEV, &ifr, NULL, NULL);
3433 	if (!err) {
3434 		ifr.ifr_settings.ifs_ifsu.raw_hdlc = saved;
3435 		if (put_user_ifreq(&ifr, uifr32))
3436 			err = -EFAULT;
3437 	}
3438 	return err;
3439 }
3440 
3441 /* Handle ioctls that use ifreq::ifr_data and just need struct ifreq converted */
3442 static int compat_ifr_data_ioctl(struct net *net, unsigned int cmd,
3443 				 struct compat_ifreq __user *u_ifreq32)
3444 {
3445 	struct ifreq ifreq;
3446 	void __user *data;
3447 
3448 	if (!is_socket_ioctl_cmd(cmd))
3449 		return -ENOTTY;
3450 	if (get_user_ifreq(&ifreq, &data, u_ifreq32))
3451 		return -EFAULT;
3452 	ifreq.ifr_data = data;
3453 
3454 	return dev_ioctl(net, cmd, &ifreq, data, NULL);
3455 }
3456 
3457 static int compat_sock_ioctl_trans(struct file *file, struct socket *sock,
3458 			 unsigned int cmd, unsigned long arg)
3459 {
3460 	void __user *argp = compat_ptr(arg);
3461 	struct sock *sk = sock->sk;
3462 	struct net *net = sock_net(sk);
3463 	const struct proto_ops *ops;
3464 
3465 	if (cmd >= SIOCDEVPRIVATE && cmd <= (SIOCDEVPRIVATE + 15))
3466 		return sock_ioctl(file, cmd, (unsigned long)argp);
3467 
3468 	switch (cmd) {
3469 	case SIOCWANDEV:
3470 		return compat_siocwandev(net, argp);
3471 	case SIOCGSTAMP_OLD:
3472 	case SIOCGSTAMPNS_OLD:
3473 		ops = READ_ONCE(sock->ops);
3474 		if (!ops->gettstamp)
3475 			return -ENOIOCTLCMD;
3476 		return ops->gettstamp(sock, argp, cmd == SIOCGSTAMP_OLD,
3477 				      !COMPAT_USE_64BIT_TIME);
3478 
3479 	case SIOCETHTOOL:
3480 	case SIOCBONDSLAVEINFOQUERY:
3481 	case SIOCBONDINFOQUERY:
3482 	case SIOCSHWTSTAMP:
3483 	case SIOCGHWTSTAMP:
3484 		return compat_ifr_data_ioctl(net, cmd, argp);
3485 
3486 	case FIOSETOWN:
3487 	case SIOCSPGRP:
3488 	case FIOGETOWN:
3489 	case SIOCGPGRP:
3490 	case SIOCBRADDBR:
3491 	case SIOCBRDELBR:
3492 	case SIOCBRADDIF:
3493 	case SIOCBRDELIF:
3494 	case SIOCGIFVLAN:
3495 	case SIOCSIFVLAN:
3496 	case SIOCGSKNS:
3497 	case SIOCGSTAMP_NEW:
3498 	case SIOCGSTAMPNS_NEW:
3499 	case SIOCGIFCONF:
3500 	case SIOCSIFBR:
3501 	case SIOCGIFBR:
3502 		return sock_ioctl(file, cmd, arg);
3503 
3504 	case SIOCGIFFLAGS:
3505 	case SIOCSIFFLAGS:
3506 	case SIOCGIFMAP:
3507 	case SIOCSIFMAP:
3508 	case SIOCGIFMETRIC:
3509 	case SIOCSIFMETRIC:
3510 	case SIOCGIFMTU:
3511 	case SIOCSIFMTU:
3512 	case SIOCGIFMEM:
3513 	case SIOCSIFMEM:
3514 	case SIOCGIFHWADDR:
3515 	case SIOCSIFHWADDR:
3516 	case SIOCADDMULTI:
3517 	case SIOCDELMULTI:
3518 	case SIOCGIFINDEX:
3519 	case SIOCGIFADDR:
3520 	case SIOCSIFADDR:
3521 	case SIOCSIFHWBROADCAST:
3522 	case SIOCDIFADDR:
3523 	case SIOCGIFBRDADDR:
3524 	case SIOCSIFBRDADDR:
3525 	case SIOCGIFDSTADDR:
3526 	case SIOCSIFDSTADDR:
3527 	case SIOCGIFNETMASK:
3528 	case SIOCSIFNETMASK:
3529 	case SIOCSIFPFLAGS:
3530 	case SIOCGIFPFLAGS:
3531 	case SIOCGIFTXQLEN:
3532 	case SIOCSIFTXQLEN:
3533 	case SIOCGIFNAME:
3534 	case SIOCSIFNAME:
3535 	case SIOCGMIIPHY:
3536 	case SIOCGMIIREG:
3537 	case SIOCSMIIREG:
3538 	case SIOCBONDENSLAVE:
3539 	case SIOCBONDRELEASE:
3540 	case SIOCBONDSETHWADDR:
3541 	case SIOCBONDCHANGEACTIVE:
3542 	case SIOCSARP:
3543 	case SIOCGARP:
3544 	case SIOCDARP:
3545 	case SIOCOUTQ:
3546 	case SIOCOUTQNSD:
3547 	case SIOCATMARK:
3548 		return sock_do_ioctl(net, sock, cmd, arg);
3549 	}
3550 
3551 	return -ENOIOCTLCMD;
3552 }
3553 
3554 static long compat_sock_ioctl(struct file *file, unsigned int cmd,
3555 			      unsigned long arg)
3556 {
3557 	struct socket *sock = file->private_data;
3558 	const struct proto_ops *ops = READ_ONCE(sock->ops);
3559 	int ret = -ENOIOCTLCMD;
3560 	struct sock *sk;
3561 	struct net *net;
3562 
3563 	sk = sock->sk;
3564 	net = sock_net(sk);
3565 
3566 	if (ops->compat_ioctl)
3567 		ret = ops->compat_ioctl(sock, cmd, arg);
3568 
3569 	if (ret == -ENOIOCTLCMD &&
3570 	    (cmd >= SIOCIWFIRST && cmd <= SIOCIWLAST))
3571 		ret = compat_wext_handle_ioctl(net, cmd, arg);
3572 
3573 	if (ret == -ENOIOCTLCMD)
3574 		ret = compat_sock_ioctl_trans(file, sock, cmd, arg);
3575 
3576 	return ret;
3577 }
3578 #endif
3579 
3580 /**
3581  *	kernel_bind - bind an address to a socket (kernel space)
3582  *	@sock: socket
3583  *	@addr: address
3584  *	@addrlen: length of address
3585  *
3586  *	Returns 0 or an error.
3587  */
3588 
3589 int kernel_bind(struct socket *sock, struct sockaddr_unsized *addr, int addrlen)
3590 {
3591 	struct sockaddr_storage address;
3592 
3593 	memcpy(&address, addr, addrlen);
3594 
3595 	return READ_ONCE(sock->ops)->bind(sock, (struct sockaddr_unsized *)&address,
3596 					  addrlen);
3597 }
3598 EXPORT_SYMBOL(kernel_bind);
3599 
3600 /**
3601  *	kernel_listen - move socket to listening state (kernel space)
3602  *	@sock: socket
3603  *	@backlog: pending connections queue size
3604  *
3605  *	Returns 0 or an error.
3606  */
3607 
3608 int kernel_listen(struct socket *sock, int backlog)
3609 {
3610 	return READ_ONCE(sock->ops)->listen(sock, backlog);
3611 }
3612 EXPORT_SYMBOL(kernel_listen);
3613 
3614 /**
3615  *	kernel_accept - accept a connection (kernel space)
3616  *	@sock: listening socket
3617  *	@newsock: new connected socket
3618  *	@flags: flags
3619  *
3620  *	@flags must be SOCK_CLOEXEC, SOCK_NONBLOCK or 0.
3621  *	If it fails, @newsock is guaranteed to be %NULL.
3622  *	Returns 0 or an error.
3623  */
3624 
3625 int kernel_accept(struct socket *sock, struct socket **newsock, int flags)
3626 {
3627 	struct sock *sk = sock->sk;
3628 	const struct proto_ops *ops = READ_ONCE(sock->ops);
3629 	struct proto_accept_arg arg = {
3630 		.flags = flags,
3631 		.kern = true,
3632 	};
3633 	int err;
3634 
3635 	err = sock_create_lite(sk->sk_family, sk->sk_type, sk->sk_protocol,
3636 			       newsock);
3637 	if (err < 0)
3638 		goto done;
3639 
3640 	err = ops->accept(sock, *newsock, &arg);
3641 	if (err < 0) {
3642 		sock_release(*newsock);
3643 		*newsock = NULL;
3644 		goto done;
3645 	}
3646 
3647 	(*newsock)->ops = ops;
3648 	__module_get(ops->owner);
3649 
3650 done:
3651 	return err;
3652 }
3653 EXPORT_SYMBOL(kernel_accept);
3654 
3655 /**
3656  *	kernel_connect - connect a socket (kernel space)
3657  *	@sock: socket
3658  *	@addr: address
3659  *	@addrlen: address length
3660  *	@flags: flags (O_NONBLOCK, ...)
3661  *
3662  *	For datagram sockets, @addr is the address to which datagrams are sent
3663  *	by default, and the only address from which datagrams are received.
3664  *	For stream sockets, attempts to connect to @addr.
3665  *	Returns 0 or an error code.
3666  */
3667 
3668 int kernel_connect(struct socket *sock, struct sockaddr_unsized *addr, int addrlen,
3669 		   int flags)
3670 {
3671 	struct sockaddr_storage address;
3672 
3673 	memcpy(&address, addr, addrlen);
3674 
3675 	return READ_ONCE(sock->ops)->connect(sock, (struct sockaddr_unsized *)&address,
3676 					     addrlen, flags);
3677 }
3678 EXPORT_SYMBOL(kernel_connect);
3679 
3680 /**
3681  *	kernel_getsockname - get the address which the socket is bound (kernel space)
3682  *	@sock: socket
3683  *	@addr: address holder
3684  *
3685  * 	Fills the @addr pointer with the address which the socket is bound.
3686  *	Returns the length of the address in bytes or an error code.
3687  */
3688 
3689 int kernel_getsockname(struct socket *sock, struct sockaddr *addr)
3690 {
3691 	return READ_ONCE(sock->ops)->getname(sock, addr, 0);
3692 }
3693 EXPORT_SYMBOL(kernel_getsockname);
3694 
3695 /**
3696  *	kernel_getpeername - get the address which the socket is connected (kernel space)
3697  *	@sock: socket
3698  *	@addr: address holder
3699  *
3700  * 	Fills the @addr pointer with the address which the socket is connected.
3701  *	Returns the length of the address in bytes or an error code.
3702  */
3703 
3704 int kernel_getpeername(struct socket *sock, struct sockaddr *addr)
3705 {
3706 	return READ_ONCE(sock->ops)->getname(sock, addr, 1);
3707 }
3708 EXPORT_SYMBOL(kernel_getpeername);
3709 
3710 /**
3711  *	kernel_sock_shutdown - shut down part of a full-duplex connection (kernel space)
3712  *	@sock: socket
3713  *	@how: connection part
3714  *
3715  *	Returns 0 or an error.
3716  */
3717 
3718 int kernel_sock_shutdown(struct socket *sock, enum sock_shutdown_cmd how)
3719 {
3720 	return READ_ONCE(sock->ops)->shutdown(sock, how);
3721 }
3722 EXPORT_SYMBOL(kernel_sock_shutdown);
3723 
3724 /**
3725  *	kernel_sock_ip_overhead - returns the IP overhead imposed by a socket
3726  *	@sk: socket
3727  *
3728  *	This routine returns the IP overhead imposed by a socket i.e.
3729  *	the length of the underlying IP header, depending on whether
3730  *	this is an IPv4 or IPv6 socket and the length from IP options turned
3731  *	on at the socket. Assumes that the caller has a lock on the socket.
3732  */
3733 
3734 u32 kernel_sock_ip_overhead(struct sock *sk)
3735 {
3736 	struct inet_sock *inet;
3737 	struct ip_options_rcu *opt;
3738 	u32 overhead = 0;
3739 #if IS_ENABLED(CONFIG_IPV6)
3740 	struct ipv6_pinfo *np;
3741 	struct ipv6_txoptions *optv6 = NULL;
3742 #endif /* IS_ENABLED(CONFIG_IPV6) */
3743 
3744 	if (!sk)
3745 		return overhead;
3746 
3747 	switch (sk->sk_family) {
3748 	case AF_INET:
3749 		inet = inet_sk(sk);
3750 		overhead += sizeof(struct iphdr);
3751 		opt = rcu_dereference_protected(inet->inet_opt,
3752 						sock_owned_by_user(sk));
3753 		if (opt)
3754 			overhead += opt->opt.optlen;
3755 		return overhead;
3756 #if IS_ENABLED(CONFIG_IPV6)
3757 	case AF_INET6:
3758 		np = inet6_sk(sk);
3759 		overhead += sizeof(struct ipv6hdr);
3760 		if (np)
3761 			optv6 = rcu_dereference_protected(np->opt,
3762 							  sock_owned_by_user(sk));
3763 		if (optv6)
3764 			overhead += (optv6->opt_flen + optv6->opt_nflen);
3765 		return overhead;
3766 #endif /* IS_ENABLED(CONFIG_IPV6) */
3767 	default: /* Returns 0 overhead if the socket is not ipv4 or ipv6 */
3768 		return overhead;
3769 	}
3770 }
3771 EXPORT_SYMBOL(kernel_sock_ip_overhead);
3772