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