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