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