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