xref: /linux/net/socket.c (revision 9d19ca5d0e8b4a3f4b2eaa14e86a25f1c93ff35b)
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. We need to add that support in a way that's
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 int connect_socket(struct socket *sock, struct sockaddr_storage *address,
2107 		   int addrlen, int flags)
2108 {
2109 	int err;
2110 
2111 	err = security_socket_connect(sock, (struct sockaddr *)address,
2112 				      addrlen);
2113 	if (err)
2114 		return err;
2115 
2116 	return READ_ONCE(sock->ops)->connect(sock, (struct sockaddr_unsized *)address,
2117 					     addrlen, flags);
2118 }
2119 
2120 /*
2121  *	Attempt to connect to a socket with the server address.  The address
2122  *	is in user space so we verify it is OK and move it to kernel space.
2123  *
2124  *	For 1003.1g we need to add clean support for a bind to AF_UNSPEC to
2125  *	break bindings
2126  *
2127  *	NOTE: 1003.1g draft 6.3 is broken with respect to AX.25/NetROM and
2128  *	other SEQPACKET protocols that take time to connect() as it doesn't
2129  *	include the -EINPROGRESS status for such sockets.
2130  */
2131 
2132 int __sys_connect_file(struct file *file, struct sockaddr_storage *address,
2133 		       int addrlen, int file_flags)
2134 {
2135 	struct socket *sock;
2136 
2137 	sock = sock_from_file(file);
2138 	if (!sock)
2139 		return -ENOTSOCK;
2140 
2141 	return connect_socket(sock, address, addrlen,
2142 			      sock->file->f_flags | file_flags);
2143 }
2144 
2145 int __sys_connect(int fd, struct sockaddr __user *uservaddr, int addrlen)
2146 {
2147 	struct sockaddr_storage address;
2148 	CLASS(fd, f)(fd);
2149 	int ret;
2150 
2151 	if (fd_empty(f))
2152 		return -EBADF;
2153 
2154 	ret = move_addr_to_kernel(uservaddr, addrlen, &address);
2155 	if (ret)
2156 		return ret;
2157 
2158 	return __sys_connect_file(fd_file(f), &address, addrlen, 0);
2159 }
2160 
2161 SYSCALL_DEFINE3(connect, int, fd, struct sockaddr __user *, uservaddr,
2162 		int, addrlen)
2163 {
2164 	return __sys_connect(fd, uservaddr, addrlen);
2165 }
2166 
2167 int do_getsockname(struct socket *sock, int peer,
2168 		   struct sockaddr __user *usockaddr, int __user *usockaddr_len)
2169 {
2170 	struct sockaddr_storage address;
2171 	int err;
2172 
2173 	if (peer)
2174 		err = security_socket_getpeername(sock);
2175 	else
2176 		err = security_socket_getsockname(sock);
2177 	if (err)
2178 		return err;
2179 	err = READ_ONCE(sock->ops)->getname(sock, (struct sockaddr *)&address, peer);
2180 	if (err < 0)
2181 		return err;
2182 	/* "err" is actually length in this case */
2183 	return move_addr_to_user(&address, err, usockaddr, usockaddr_len);
2184 }
2185 
2186 /*
2187  *	Get the remote or local address ('name') of a socket object. Move the
2188  *	obtained name to user space.
2189  */
2190 int __sys_getsockname(int fd, struct sockaddr __user *usockaddr,
2191 		      int __user *usockaddr_len, int peer)
2192 {
2193 	struct socket *sock;
2194 	CLASS(fd, f)(fd);
2195 
2196 	if (fd_empty(f))
2197 		return -EBADF;
2198 	sock = sock_from_file(fd_file(f));
2199 	if (unlikely(!sock))
2200 		return -ENOTSOCK;
2201 	return do_getsockname(sock, peer, usockaddr, usockaddr_len);
2202 }
2203 
2204 SYSCALL_DEFINE3(getsockname, int, fd, struct sockaddr __user *, usockaddr,
2205 		int __user *, usockaddr_len)
2206 {
2207 	return __sys_getsockname(fd, usockaddr, usockaddr_len, 0);
2208 }
2209 
2210 SYSCALL_DEFINE3(getpeername, int, fd, struct sockaddr __user *, usockaddr,
2211 		int __user *, usockaddr_len)
2212 {
2213 	return __sys_getsockname(fd, usockaddr, usockaddr_len, 1);
2214 }
2215 
2216 /*
2217  *	Send a datagram to a given address. We move the address into kernel
2218  *	space and check the user space data area is readable before invoking
2219  *	the protocol.
2220  */
2221 int __sys_sendto(int fd, void __user *buff, size_t len, unsigned int flags,
2222 		 struct sockaddr __user *addr,  int addr_len)
2223 {
2224 	struct socket *sock;
2225 	struct sockaddr_storage address;
2226 	int err;
2227 	struct msghdr msg;
2228 
2229 	err = import_ubuf(ITER_SOURCE, buff, len, &msg.msg_iter);
2230 	if (unlikely(err))
2231 		return err;
2232 
2233 	CLASS(fd, f)(fd);
2234 	if (fd_empty(f))
2235 		return -EBADF;
2236 	sock = sock_from_file(fd_file(f));
2237 	if (unlikely(!sock))
2238 		return -ENOTSOCK;
2239 
2240 	msg.msg_name = NULL;
2241 	msg.msg_control = NULL;
2242 	msg.msg_controllen = 0;
2243 	msg.msg_namelen = 0;
2244 	msg.msg_ubuf = NULL;
2245 	if (addr) {
2246 		err = move_addr_to_kernel(addr, addr_len, &address);
2247 		if (err < 0)
2248 			return err;
2249 		msg.msg_name = (struct sockaddr *)&address;
2250 		msg.msg_namelen = addr_len;
2251 	}
2252 	flags &= ~MSG_INTERNAL_SENDMSG_FLAGS;
2253 	if (sock->file->f_flags & O_NONBLOCK)
2254 		flags |= MSG_DONTWAIT;
2255 	msg.msg_flags = flags;
2256 	return __sock_sendmsg(sock, &msg);
2257 }
2258 
2259 SYSCALL_DEFINE6(sendto, int, fd, void __user *, buff, size_t, len,
2260 		unsigned int, flags, struct sockaddr __user *, addr,
2261 		int, addr_len)
2262 {
2263 	return __sys_sendto(fd, buff, len, flags, addr, addr_len);
2264 }
2265 
2266 /*
2267  *	Send a datagram down a socket.
2268  */
2269 
2270 SYSCALL_DEFINE4(send, int, fd, void __user *, buff, size_t, len,
2271 		unsigned int, flags)
2272 {
2273 	return __sys_sendto(fd, buff, len, flags, NULL, 0);
2274 }
2275 
2276 /*
2277  *	Receive a frame from the socket and optionally record the address of the
2278  *	sender. We verify the buffers are writable and if needed move the
2279  *	sender address from kernel to user space.
2280  */
2281 int __sys_recvfrom(int fd, void __user *ubuf, size_t size, unsigned int flags,
2282 		   struct sockaddr __user *addr, int __user *addr_len)
2283 {
2284 	struct sockaddr_storage address;
2285 	struct msghdr msg = {
2286 		/* Save some cycles and don't copy the address if not needed */
2287 		.msg_name = addr ? (struct sockaddr *)&address : NULL,
2288 	};
2289 	struct socket *sock;
2290 	int err, err2;
2291 
2292 	err = import_ubuf(ITER_DEST, ubuf, size, &msg.msg_iter);
2293 	if (unlikely(err))
2294 		return err;
2295 
2296 	CLASS(fd, f)(fd);
2297 
2298 	if (fd_empty(f))
2299 		return -EBADF;
2300 	sock = sock_from_file(fd_file(f));
2301 	if (unlikely(!sock))
2302 		return -ENOTSOCK;
2303 
2304 	if (sock->file->f_flags & O_NONBLOCK)
2305 		flags |= MSG_DONTWAIT;
2306 	err = sock_recvmsg(sock, &msg, flags);
2307 
2308 	if (err >= 0 && addr != NULL) {
2309 		err2 = move_addr_to_user(&address,
2310 					 msg.msg_namelen, addr, addr_len);
2311 		if (err2 < 0)
2312 			err = err2;
2313 	}
2314 	return err;
2315 }
2316 
2317 SYSCALL_DEFINE6(recvfrom, int, fd, void __user *, ubuf, size_t, size,
2318 		unsigned int, flags, struct sockaddr __user *, addr,
2319 		int __user *, addr_len)
2320 {
2321 	return __sys_recvfrom(fd, ubuf, size, flags, addr, addr_len);
2322 }
2323 
2324 /*
2325  *	Receive a datagram from a socket.
2326  */
2327 
2328 SYSCALL_DEFINE4(recv, int, fd, void __user *, ubuf, size_t, size,
2329 		unsigned int, flags)
2330 {
2331 	return __sys_recvfrom(fd, ubuf, size, flags, NULL, NULL);
2332 }
2333 
2334 static bool sock_use_custom_sol_socket(const struct socket *sock)
2335 {
2336 	return test_bit(SOCK_CUSTOM_SOCKOPT, &sock->flags);
2337 }
2338 
2339 int do_sock_setsockopt(struct socket *sock, bool compat, int level,
2340 		       int optname, sockptr_t optval, int optlen)
2341 {
2342 	const struct proto_ops *ops;
2343 	char *kernel_optval = NULL;
2344 	int err;
2345 
2346 	if (optlen < 0)
2347 		return -EINVAL;
2348 
2349 	err = security_socket_setsockopt(sock, level, optname);
2350 	if (err)
2351 		goto out_put;
2352 
2353 	if (!compat)
2354 		err = BPF_CGROUP_RUN_PROG_SETSOCKOPT(sock->sk, &level, &optname,
2355 						     optval, &optlen,
2356 						     &kernel_optval);
2357 	if (err < 0)
2358 		goto out_put;
2359 	if (err > 0) {
2360 		err = 0;
2361 		goto out_put;
2362 	}
2363 
2364 	if (kernel_optval)
2365 		optval = KERNEL_SOCKPTR(kernel_optval);
2366 	ops = READ_ONCE(sock->ops);
2367 	if (level == SOL_SOCKET && !sock_use_custom_sol_socket(sock))
2368 		err = sock_setsockopt(sock, level, optname, optval, optlen);
2369 	else if (unlikely(!ops->setsockopt))
2370 		err = -EOPNOTSUPP;
2371 	else
2372 		err = ops->setsockopt(sock, level, optname, optval,
2373 					    optlen);
2374 	kfree(kernel_optval);
2375 out_put:
2376 	return err;
2377 }
2378 EXPORT_SYMBOL(do_sock_setsockopt);
2379 
2380 /* Set a socket option. Because we don't know the option lengths we have
2381  * to pass the user mode parameter for the protocols to sort out.
2382  */
2383 int __sys_setsockopt(int fd, int level, int optname, char __user *user_optval,
2384 		     int optlen)
2385 {
2386 	sockptr_t optval = USER_SOCKPTR(user_optval);
2387 	bool compat = in_compat_syscall();
2388 	struct socket *sock;
2389 	CLASS(fd, f)(fd);
2390 
2391 	if (fd_empty(f))
2392 		return -EBADF;
2393 	sock = sock_from_file(fd_file(f));
2394 	if (unlikely(!sock))
2395 		return -ENOTSOCK;
2396 
2397 	return do_sock_setsockopt(sock, compat, level, optname, optval, optlen);
2398 }
2399 
2400 SYSCALL_DEFINE5(setsockopt, int, fd, int, level, int, optname,
2401 		char __user *, optval, int, optlen)
2402 {
2403 	return __sys_setsockopt(fd, level, optname, optval, optlen);
2404 }
2405 
2406 INDIRECT_CALLABLE_DECLARE(bool tcp_bpf_bypass_getsockopt(int level,
2407 							 int optname));
2408 
2409 /*
2410  * Initialize a sockopt_t from sockptr optval/optlen, setting up iov_iter
2411  * for both input and output directions.
2412  * It is important to remember that both iov points to the same data, but,
2413  * .iter_in is read-only and .iter_out is write-only by the protocol callbacks
2414  */
2415 static int sockptr_to_sockopt(sockopt_t *opt, sockptr_t optval,
2416 			      sockptr_t optlen, struct kvec *kvec)
2417 {
2418 	int koptlen;
2419 
2420 	if (copy_from_sockptr(&koptlen, optlen, sizeof(int)))
2421 		return -EFAULT;
2422 
2423 	if (koptlen < 0)
2424 		return -EINVAL;
2425 
2426 	if (optval.is_kernel) {
2427 		kvec->iov_base = optval.kernel;
2428 		kvec->iov_len = koptlen;
2429 		iov_iter_kvec(&opt->iter_out, ITER_DEST, kvec, 1, koptlen);
2430 		iov_iter_kvec(&opt->iter_in, ITER_SOURCE, kvec, 1, koptlen);
2431 	} else {
2432 		iov_iter_ubuf(&opt->iter_out, ITER_DEST, optval.user, koptlen);
2433 		iov_iter_ubuf(&opt->iter_in, ITER_SOURCE, optval.user,
2434 			      koptlen);
2435 	}
2436 	opt->optlen = koptlen;
2437 
2438 	return 0;
2439 }
2440 
2441 int do_sock_getsockopt(struct socket *sock, bool compat, int level,
2442 		       int optname, sockptr_t optval, sockptr_t optlen)
2443 {
2444 	int max_optlen __maybe_unused = 0;
2445 	const struct proto_ops *ops;
2446 	struct kvec kvec;
2447 	sockopt_t opt;
2448 	int err;
2449 
2450 	err = security_socket_getsockopt(sock, level, optname);
2451 	if (err)
2452 		return err;
2453 
2454 	if (!compat)
2455 		copy_from_sockptr(&max_optlen, optlen, sizeof(int));
2456 
2457 	ops = READ_ONCE(sock->ops);
2458 	if (level == SOL_SOCKET) {
2459 		err = sk_getsockopt(sock->sk, level, optname, optval, optlen);
2460 	} else if (ops->getsockopt_iter) {
2461 		err = sockptr_to_sockopt(&opt, optval, optlen, &kvec);
2462 		if (err)
2463 			return err;
2464 
2465 		err = ops->getsockopt_iter(sock, level, optname, &opt);
2466 
2467 		/* Always write back optlen, even on failure. Some protocols
2468 		 * (e.g. CAN raw) return -ERANGE and set optlen to the
2469 		 * required buffer size so userspace can discover it.
2470 		 */
2471 		if (copy_to_sockptr(optlen, &opt.optlen, sizeof(int)))
2472 			return -EFAULT;
2473 	} else if (ops->getsockopt) {
2474 		if (WARN_ONCE(optval.is_kernel || optlen.is_kernel,
2475 			      "Invalid argument type"))
2476 			return -EOPNOTSUPP;
2477 
2478 		err = ops->getsockopt(sock, level, optname, optval.user,
2479 				      optlen.user);
2480 	} else {
2481 		err = -EOPNOTSUPP;
2482 	}
2483 
2484 	if (!compat)
2485 		err = BPF_CGROUP_RUN_PROG_GETSOCKOPT(sock->sk, level, optname,
2486 						     optval, optlen, max_optlen,
2487 						     err);
2488 
2489 	return err;
2490 }
2491 EXPORT_SYMBOL(do_sock_getsockopt);
2492 
2493 /*
2494  *	Get a socket option. Because we don't know the option lengths we have
2495  *	to pass a user mode parameter for the protocols to sort out.
2496  */
2497 int __sys_getsockopt(int fd, int level, int optname, char __user *optval,
2498 		int __user *optlen)
2499 {
2500 	struct socket *sock;
2501 	CLASS(fd, f)(fd);
2502 
2503 	if (fd_empty(f))
2504 		return -EBADF;
2505 	sock = sock_from_file(fd_file(f));
2506 	if (unlikely(!sock))
2507 		return -ENOTSOCK;
2508 
2509 	return do_sock_getsockopt(sock, in_compat_syscall(), level, optname,
2510 				 USER_SOCKPTR(optval), USER_SOCKPTR(optlen));
2511 }
2512 
2513 SYSCALL_DEFINE5(getsockopt, int, fd, int, level, int, optname,
2514 		char __user *, optval, int __user *, optlen)
2515 {
2516 	return __sys_getsockopt(fd, level, optname, optval, optlen);
2517 }
2518 
2519 /*
2520  *	Shutdown a socket.
2521  */
2522 
2523 int __sys_shutdown_sock(struct socket *sock, int how)
2524 {
2525 	int err;
2526 
2527 	err = security_socket_shutdown(sock, how);
2528 	if (!err)
2529 		err = READ_ONCE(sock->ops)->shutdown(sock, how);
2530 
2531 	return err;
2532 }
2533 
2534 int __sys_shutdown(int fd, int how)
2535 {
2536 	struct socket *sock;
2537 	CLASS(fd, f)(fd);
2538 
2539 	if (fd_empty(f))
2540 		return -EBADF;
2541 	sock = sock_from_file(fd_file(f));
2542 	if (unlikely(!sock))
2543 		return -ENOTSOCK;
2544 
2545 	return __sys_shutdown_sock(sock, how);
2546 }
2547 
2548 SYSCALL_DEFINE2(shutdown, int, fd, int, how)
2549 {
2550 	return __sys_shutdown(fd, how);
2551 }
2552 
2553 /* A couple of helpful macros for getting the address of the 32/64 bit
2554  * fields which are the same type (int / unsigned) on our platforms.
2555  */
2556 #define COMPAT_MSG(msg, member)	((MSG_CMSG_COMPAT & flags) ? &msg##_compat->member : &msg->member)
2557 #define COMPAT_NAMELEN(msg)	COMPAT_MSG(msg, msg_namelen)
2558 #define COMPAT_FLAGS(msg)	COMPAT_MSG(msg, msg_flags)
2559 
2560 struct used_address {
2561 	struct sockaddr_storage name;
2562 	unsigned int name_len;
2563 };
2564 
2565 int __copy_msghdr(struct msghdr *kmsg,
2566 		  struct user_msghdr *msg,
2567 		  struct sockaddr __user **save_addr)
2568 {
2569 	ssize_t err;
2570 
2571 	kmsg->msg_control_is_user = true;
2572 	kmsg->msg_get_inq = 0;
2573 	kmsg->msg_control_user = msg->msg_control;
2574 	kmsg->msg_controllen = msg->msg_controllen;
2575 	kmsg->msg_flags = msg->msg_flags;
2576 
2577 	kmsg->msg_namelen = msg->msg_namelen;
2578 	if (!msg->msg_name)
2579 		kmsg->msg_namelen = 0;
2580 
2581 	if (kmsg->msg_namelen < 0)
2582 		return -EINVAL;
2583 
2584 	if (kmsg->msg_namelen > sizeof(struct sockaddr_storage))
2585 		kmsg->msg_namelen = sizeof(struct sockaddr_storage);
2586 
2587 	if (save_addr)
2588 		*save_addr = msg->msg_name;
2589 
2590 	if (msg->msg_name && kmsg->msg_namelen) {
2591 		if (!save_addr) {
2592 			err = move_addr_to_kernel(msg->msg_name,
2593 						  kmsg->msg_namelen,
2594 						  kmsg->msg_name);
2595 			if (err < 0)
2596 				return err;
2597 		}
2598 	} else {
2599 		kmsg->msg_name = NULL;
2600 		kmsg->msg_namelen = 0;
2601 	}
2602 
2603 	if (msg->msg_iovlen > UIO_MAXIOV)
2604 		return -EMSGSIZE;
2605 
2606 	kmsg->msg_ubuf = NULL;
2607 	return 0;
2608 }
2609 
2610 static int copy_msghdr_from_user(struct msghdr *kmsg,
2611 				 struct user_msghdr __user *umsg,
2612 				 struct sockaddr __user **save_addr,
2613 				 struct iovec **iov)
2614 {
2615 	struct user_msghdr msg;
2616 	ssize_t err;
2617 
2618 	if (copy_from_user(&msg, umsg, sizeof(*umsg)))
2619 		return -EFAULT;
2620 
2621 	err = __copy_msghdr(kmsg, &msg, save_addr);
2622 	if (err)
2623 		return err;
2624 
2625 	err = import_iovec(save_addr ? ITER_DEST : ITER_SOURCE,
2626 			    msg.msg_iov, msg.msg_iovlen,
2627 			    UIO_FASTIOV, iov, &kmsg->msg_iter);
2628 	return err < 0 ? err : 0;
2629 }
2630 
2631 static int ____sys_sendmsg(struct socket *sock, struct msghdr *msg_sys,
2632 			   unsigned int flags, struct used_address *used_address,
2633 			   unsigned int allowed_msghdr_flags)
2634 {
2635 	unsigned char ctl[sizeof(struct cmsghdr) + 20]
2636 				__aligned(sizeof(__kernel_size_t));
2637 	/* 20 is size of ipv6_pktinfo */
2638 	unsigned char *ctl_buf = ctl;
2639 	int ctl_len;
2640 	ssize_t err;
2641 
2642 	err = -ENOBUFS;
2643 
2644 	if (msg_sys->msg_controllen > INT_MAX)
2645 		goto out;
2646 	flags |= (msg_sys->msg_flags & allowed_msghdr_flags);
2647 	ctl_len = msg_sys->msg_controllen;
2648 	if ((MSG_CMSG_COMPAT & flags) && ctl_len) {
2649 		err =
2650 		    cmsghdr_from_user_compat_to_kern(msg_sys, sock->sk, ctl,
2651 						     sizeof(ctl));
2652 		if (err)
2653 			goto out;
2654 		ctl_buf = msg_sys->msg_control;
2655 		ctl_len = msg_sys->msg_controllen;
2656 	} else if (ctl_len) {
2657 		BUILD_BUG_ON(sizeof(struct cmsghdr) !=
2658 			     CMSG_ALIGN(sizeof(struct cmsghdr)));
2659 		if (ctl_len > sizeof(ctl)) {
2660 			ctl_buf = sock_kmalloc(sock->sk, ctl_len, GFP_KERNEL);
2661 			if (ctl_buf == NULL)
2662 				goto out;
2663 		}
2664 		err = -EFAULT;
2665 		if (copy_from_user(ctl_buf, msg_sys->msg_control_user, ctl_len))
2666 			goto out_freectl;
2667 		msg_sys->msg_control = ctl_buf;
2668 		msg_sys->msg_control_is_user = false;
2669 	}
2670 	flags &= ~MSG_INTERNAL_SENDMSG_FLAGS;
2671 	msg_sys->msg_flags = flags;
2672 
2673 	if (sock->file->f_flags & O_NONBLOCK)
2674 		msg_sys->msg_flags |= MSG_DONTWAIT;
2675 	/*
2676 	 * If this is sendmmsg() and current destination address is same as
2677 	 * previously succeeded address, omit asking LSM's decision.
2678 	 * used_address->name_len is initialized to UINT_MAX so that the first
2679 	 * destination address never matches.
2680 	 */
2681 	if (used_address && msg_sys->msg_name &&
2682 	    used_address->name_len == msg_sys->msg_namelen &&
2683 	    !memcmp(&used_address->name, msg_sys->msg_name,
2684 		    used_address->name_len)) {
2685 		err = sock_sendmsg_nosec(sock, msg_sys);
2686 		goto out_freectl;
2687 	}
2688 	err = __sock_sendmsg(sock, msg_sys);
2689 	/*
2690 	 * If this is sendmmsg() and sending to current destination address was
2691 	 * successful, remember it.
2692 	 */
2693 	if (used_address && err >= 0) {
2694 		used_address->name_len = msg_sys->msg_namelen;
2695 		if (msg_sys->msg_name)
2696 			memcpy(&used_address->name, msg_sys->msg_name,
2697 			       used_address->name_len);
2698 	}
2699 
2700 out_freectl:
2701 	if (ctl_buf != ctl)
2702 		sock_kfree_s(sock->sk, ctl_buf, ctl_len);
2703 out:
2704 	return err;
2705 }
2706 
2707 static int sendmsg_copy_msghdr(struct msghdr *msg,
2708 			       struct user_msghdr __user *umsg, unsigned flags,
2709 			       struct iovec **iov)
2710 {
2711 	int err;
2712 
2713 	if (flags & MSG_CMSG_COMPAT) {
2714 		struct compat_msghdr __user *msg_compat;
2715 
2716 		msg_compat = (struct compat_msghdr __user *) umsg;
2717 		err = get_compat_msghdr(msg, msg_compat, NULL, iov);
2718 	} else {
2719 		err = copy_msghdr_from_user(msg, umsg, NULL, iov);
2720 	}
2721 	if (err < 0)
2722 		return err;
2723 
2724 	return 0;
2725 }
2726 
2727 static int ___sys_sendmsg(struct socket *sock, struct user_msghdr __user *msg,
2728 			 struct msghdr *msg_sys, unsigned int flags,
2729 			 struct used_address *used_address,
2730 			 unsigned int allowed_msghdr_flags)
2731 {
2732 	struct sockaddr_storage address;
2733 	struct iovec iovstack[UIO_FASTIOV], *iov = iovstack;
2734 	ssize_t err;
2735 
2736 	msg_sys->msg_name = &address;
2737 
2738 	err = sendmsg_copy_msghdr(msg_sys, msg, flags, &iov);
2739 	if (err < 0)
2740 		return err;
2741 
2742 	err = ____sys_sendmsg(sock, msg_sys, flags, used_address,
2743 				allowed_msghdr_flags);
2744 	kfree(iov);
2745 	return err;
2746 }
2747 
2748 /*
2749  *	BSD sendmsg interface
2750  */
2751 long __sys_sendmsg_sock(struct socket *sock, struct msghdr *msg,
2752 			unsigned int flags)
2753 {
2754 	return ____sys_sendmsg(sock, msg, flags, NULL, 0);
2755 }
2756 
2757 long __sys_sendmsg(int fd, struct user_msghdr __user *msg, unsigned int flags,
2758 		   bool forbid_cmsg_compat)
2759 {
2760 	struct msghdr msg_sys;
2761 	struct socket *sock;
2762 
2763 	if (forbid_cmsg_compat && (flags & MSG_CMSG_COMPAT))
2764 		return -EINVAL;
2765 
2766 	CLASS(fd, f)(fd);
2767 
2768 	if (fd_empty(f))
2769 		return -EBADF;
2770 	sock = sock_from_file(fd_file(f));
2771 	if (unlikely(!sock))
2772 		return -ENOTSOCK;
2773 
2774 	return ___sys_sendmsg(sock, msg, &msg_sys, flags, NULL, 0);
2775 }
2776 
2777 SYSCALL_DEFINE3(sendmsg, int, fd, struct user_msghdr __user *, msg, unsigned int, flags)
2778 {
2779 	return __sys_sendmsg(fd, msg, flags, true);
2780 }
2781 
2782 /*
2783  *	Linux sendmmsg interface
2784  */
2785 
2786 int __sys_sendmmsg(int fd, struct mmsghdr __user *mmsg, unsigned int vlen,
2787 		   unsigned int flags, bool forbid_cmsg_compat)
2788 {
2789 	int err, datagrams;
2790 	struct socket *sock;
2791 	struct mmsghdr __user *entry;
2792 	struct compat_mmsghdr __user *compat_entry;
2793 	struct msghdr msg_sys;
2794 	struct used_address used_address;
2795 	unsigned int oflags = flags;
2796 
2797 	if (forbid_cmsg_compat && (flags & MSG_CMSG_COMPAT))
2798 		return -EINVAL;
2799 
2800 	if (vlen > UIO_MAXIOV)
2801 		vlen = UIO_MAXIOV;
2802 
2803 	datagrams = 0;
2804 
2805 	CLASS(fd, f)(fd);
2806 
2807 	if (fd_empty(f))
2808 		return -EBADF;
2809 	sock = sock_from_file(fd_file(f));
2810 	if (unlikely(!sock))
2811 		return -ENOTSOCK;
2812 
2813 	used_address.name_len = UINT_MAX;
2814 	entry = mmsg;
2815 	compat_entry = (struct compat_mmsghdr __user *)mmsg;
2816 	err = 0;
2817 	flags |= MSG_BATCH;
2818 
2819 	while (datagrams < vlen) {
2820 		if (datagrams == vlen - 1)
2821 			flags = oflags;
2822 
2823 		if (MSG_CMSG_COMPAT & flags) {
2824 			err = ___sys_sendmsg(sock, (struct user_msghdr __user *)compat_entry,
2825 					     &msg_sys, flags, &used_address, MSG_EOR);
2826 			if (err < 0)
2827 				break;
2828 			err = __put_user(err, &compat_entry->msg_len);
2829 			++compat_entry;
2830 		} else {
2831 			err = ___sys_sendmsg(sock,
2832 					     (struct user_msghdr __user *)entry,
2833 					     &msg_sys, flags, &used_address, MSG_EOR);
2834 			if (err < 0)
2835 				break;
2836 			err = put_user(err, &entry->msg_len);
2837 			++entry;
2838 		}
2839 
2840 		if (err)
2841 			break;
2842 		++datagrams;
2843 		if (msg_data_left(&msg_sys))
2844 			break;
2845 		cond_resched();
2846 	}
2847 
2848 	/* We only return an error if no datagrams were able to be sent */
2849 	if (datagrams != 0)
2850 		return datagrams;
2851 
2852 	return err;
2853 }
2854 
2855 SYSCALL_DEFINE4(sendmmsg, int, fd, struct mmsghdr __user *, mmsg,
2856 		unsigned int, vlen, unsigned int, flags)
2857 {
2858 	return __sys_sendmmsg(fd, mmsg, vlen, flags, true);
2859 }
2860 
2861 static int recvmsg_copy_msghdr(struct msghdr *msg,
2862 			       struct user_msghdr __user *umsg, unsigned flags,
2863 			       struct sockaddr __user **uaddr,
2864 			       struct iovec **iov)
2865 {
2866 	ssize_t err;
2867 
2868 	if (MSG_CMSG_COMPAT & flags) {
2869 		struct compat_msghdr __user *msg_compat;
2870 
2871 		msg_compat = (struct compat_msghdr __user *) umsg;
2872 		err = get_compat_msghdr(msg, msg_compat, uaddr, iov);
2873 	} else {
2874 		err = copy_msghdr_from_user(msg, umsg, uaddr, iov);
2875 	}
2876 	if (err < 0)
2877 		return err;
2878 
2879 	return 0;
2880 }
2881 
2882 static int ____sys_recvmsg(struct socket *sock, struct msghdr *msg_sys,
2883 			   struct user_msghdr __user *msg,
2884 			   struct sockaddr __user *uaddr,
2885 			   unsigned int flags, int nosec)
2886 {
2887 	struct compat_msghdr __user *msg_compat =
2888 					(struct compat_msghdr __user *) msg;
2889 	int __user *uaddr_len = COMPAT_NAMELEN(msg);
2890 	struct sockaddr_storage addr;
2891 	unsigned long cmsg_ptr;
2892 	int len;
2893 	ssize_t err;
2894 
2895 	msg_sys->msg_name = &addr;
2896 	cmsg_ptr = (unsigned long)msg_sys->msg_control;
2897 	msg_sys->msg_flags = flags & (MSG_CMSG_CLOEXEC|MSG_CMSG_COMPAT);
2898 
2899 	/* We assume all kernel code knows the size of sockaddr_storage */
2900 	msg_sys->msg_namelen = 0;
2901 
2902 	if (sock->file->f_flags & O_NONBLOCK)
2903 		flags |= MSG_DONTWAIT;
2904 
2905 	if (unlikely(nosec))
2906 		err = sock_recvmsg_nosec(sock, msg_sys, flags);
2907 	else
2908 		err = sock_recvmsg(sock, msg_sys, flags);
2909 
2910 	if (err < 0)
2911 		goto out;
2912 	len = err;
2913 
2914 	if (uaddr != NULL) {
2915 		err = move_addr_to_user(&addr,
2916 					msg_sys->msg_namelen, uaddr,
2917 					uaddr_len);
2918 		if (err < 0)
2919 			goto out;
2920 	}
2921 	err = __put_user((msg_sys->msg_flags & ~MSG_CMSG_COMPAT),
2922 			 COMPAT_FLAGS(msg));
2923 	if (err)
2924 		goto out;
2925 	if (MSG_CMSG_COMPAT & flags)
2926 		err = __put_user((unsigned long)msg_sys->msg_control - cmsg_ptr,
2927 				 &msg_compat->msg_controllen);
2928 	else
2929 		err = __put_user((unsigned long)msg_sys->msg_control - cmsg_ptr,
2930 				 &msg->msg_controllen);
2931 	if (err)
2932 		goto out;
2933 	err = len;
2934 out:
2935 	return err;
2936 }
2937 
2938 static int ___sys_recvmsg(struct socket *sock, struct user_msghdr __user *msg,
2939 			 struct msghdr *msg_sys, unsigned int flags, int nosec)
2940 {
2941 	struct iovec iovstack[UIO_FASTIOV], *iov = iovstack;
2942 	/* user mode address pointers */
2943 	struct sockaddr __user *uaddr;
2944 	ssize_t err;
2945 
2946 	err = recvmsg_copy_msghdr(msg_sys, msg, flags, &uaddr, &iov);
2947 	if (err < 0)
2948 		return err;
2949 
2950 	err = ____sys_recvmsg(sock, msg_sys, msg, uaddr, flags, nosec);
2951 	kfree(iov);
2952 	return err;
2953 }
2954 
2955 /*
2956  *	BSD recvmsg interface
2957  */
2958 
2959 long __sys_recvmsg_sock(struct socket *sock, struct msghdr *msg,
2960 			struct user_msghdr __user *umsg,
2961 			struct sockaddr __user *uaddr, unsigned int flags)
2962 {
2963 	return ____sys_recvmsg(sock, msg, umsg, uaddr, flags, 0);
2964 }
2965 
2966 long __sys_recvmsg(int fd, struct user_msghdr __user *msg, unsigned int flags,
2967 		   bool forbid_cmsg_compat)
2968 {
2969 	struct msghdr msg_sys;
2970 	struct socket *sock;
2971 
2972 	if (forbid_cmsg_compat && (flags & MSG_CMSG_COMPAT))
2973 		return -EINVAL;
2974 
2975 	CLASS(fd, f)(fd);
2976 
2977 	if (fd_empty(f))
2978 		return -EBADF;
2979 	sock = sock_from_file(fd_file(f));
2980 	if (unlikely(!sock))
2981 		return -ENOTSOCK;
2982 
2983 	return ___sys_recvmsg(sock, msg, &msg_sys, flags, 0);
2984 }
2985 
2986 SYSCALL_DEFINE3(recvmsg, int, fd, struct user_msghdr __user *, msg,
2987 		unsigned int, flags)
2988 {
2989 	return __sys_recvmsg(fd, msg, flags, true);
2990 }
2991 
2992 /*
2993  *     Linux recvmmsg interface
2994  */
2995 
2996 static int do_recvmmsg(int fd, struct mmsghdr __user *mmsg,
2997 			  unsigned int vlen, unsigned int flags,
2998 			  struct timespec64 *timeout)
2999 {
3000 	int err = 0, datagrams;
3001 	struct socket *sock;
3002 	struct mmsghdr __user *entry;
3003 	struct compat_mmsghdr __user *compat_entry;
3004 	struct msghdr msg_sys;
3005 	struct timespec64 end_time;
3006 	struct timespec64 timeout64;
3007 
3008 	if (timeout &&
3009 	    poll_select_set_timeout(&end_time, timeout->tv_sec,
3010 				    timeout->tv_nsec))
3011 		return -EINVAL;
3012 
3013 	datagrams = 0;
3014 
3015 	CLASS(fd, f)(fd);
3016 
3017 	if (fd_empty(f))
3018 		return -EBADF;
3019 	sock = sock_from_file(fd_file(f));
3020 	if (unlikely(!sock))
3021 		return -ENOTSOCK;
3022 
3023 	if (likely(!(flags & MSG_ERRQUEUE))) {
3024 		err = sock_error(sock->sk);
3025 		if (err)
3026 			return err;
3027 	}
3028 
3029 	entry = mmsg;
3030 	compat_entry = (struct compat_mmsghdr __user *)mmsg;
3031 
3032 	while (datagrams < vlen) {
3033 		/*
3034 		 * No need to ask LSM for more than the first datagram.
3035 		 */
3036 		if (MSG_CMSG_COMPAT & flags) {
3037 			err = ___sys_recvmsg(sock, (struct user_msghdr __user *)compat_entry,
3038 					     &msg_sys, flags & ~MSG_WAITFORONE,
3039 					     datagrams);
3040 			if (err < 0)
3041 				break;
3042 			err = __put_user(err, &compat_entry->msg_len);
3043 			++compat_entry;
3044 		} else {
3045 			err = ___sys_recvmsg(sock,
3046 					     (struct user_msghdr __user *)entry,
3047 					     &msg_sys, flags & ~MSG_WAITFORONE,
3048 					     datagrams);
3049 			if (err < 0)
3050 				break;
3051 			err = put_user(err, &entry->msg_len);
3052 			++entry;
3053 		}
3054 
3055 		if (err)
3056 			break;
3057 		++datagrams;
3058 
3059 		/* MSG_WAITFORONE turns on MSG_DONTWAIT after one packet */
3060 		if (flags & MSG_WAITFORONE)
3061 			flags |= MSG_DONTWAIT;
3062 
3063 		if (timeout) {
3064 			ktime_get_ts64(&timeout64);
3065 			*timeout = timespec64_sub(end_time, timeout64);
3066 			if (timeout->tv_sec < 0) {
3067 				timeout->tv_sec = timeout->tv_nsec = 0;
3068 				break;
3069 			}
3070 
3071 			/* Timeout, return less than vlen datagrams */
3072 			if (timeout->tv_nsec == 0 && timeout->tv_sec == 0)
3073 				break;
3074 		}
3075 
3076 		/* Out of band data, return right away */
3077 		if (msg_sys.msg_flags & MSG_OOB)
3078 			break;
3079 		cond_resched();
3080 	}
3081 
3082 	if (err == 0)
3083 		return datagrams;
3084 
3085 	if (datagrams == 0)
3086 		return err;
3087 
3088 	/*
3089 	 * We may return less entries than requested (vlen) if the
3090 	 * sock is non block and there aren't enough datagrams...
3091 	 */
3092 	if (err != -EAGAIN) {
3093 		/*
3094 		 * ... or  if recvmsg returns an error after we
3095 		 * received some datagrams, where we record the
3096 		 * error to return on the next call or if the
3097 		 * app asks about it using getsockopt(SO_ERROR).
3098 		 */
3099 		WRITE_ONCE(sock->sk->sk_err, -err);
3100 	}
3101 	return datagrams;
3102 }
3103 
3104 int __sys_recvmmsg(int fd, struct mmsghdr __user *mmsg,
3105 		   unsigned int vlen, unsigned int flags,
3106 		   struct __kernel_timespec __user *timeout,
3107 		   struct old_timespec32 __user *timeout32)
3108 {
3109 	int datagrams;
3110 	struct timespec64 timeout_sys;
3111 
3112 	if (timeout && get_timespec64(&timeout_sys, timeout))
3113 		return -EFAULT;
3114 
3115 	if (timeout32 && get_old_timespec32(&timeout_sys, timeout32))
3116 		return -EFAULT;
3117 
3118 	if (!timeout && !timeout32)
3119 		return do_recvmmsg(fd, mmsg, vlen, flags, NULL);
3120 
3121 	datagrams = do_recvmmsg(fd, mmsg, vlen, flags, &timeout_sys);
3122 
3123 	if (datagrams <= 0)
3124 		return datagrams;
3125 
3126 	if (timeout && put_timespec64(&timeout_sys, timeout))
3127 		datagrams = -EFAULT;
3128 
3129 	if (timeout32 && put_old_timespec32(&timeout_sys, timeout32))
3130 		datagrams = -EFAULT;
3131 
3132 	return datagrams;
3133 }
3134 
3135 SYSCALL_DEFINE5(recvmmsg, int, fd, struct mmsghdr __user *, mmsg,
3136 		unsigned int, vlen, unsigned int, flags,
3137 		struct __kernel_timespec __user *, timeout)
3138 {
3139 	if (flags & MSG_CMSG_COMPAT)
3140 		return -EINVAL;
3141 
3142 	return __sys_recvmmsg(fd, mmsg, vlen, flags, timeout, NULL);
3143 }
3144 
3145 #ifdef CONFIG_COMPAT_32BIT_TIME
3146 SYSCALL_DEFINE5(recvmmsg_time32, int, fd, struct mmsghdr __user *, mmsg,
3147 		unsigned int, vlen, unsigned int, flags,
3148 		struct old_timespec32 __user *, timeout)
3149 {
3150 	if (flags & MSG_CMSG_COMPAT)
3151 		return -EINVAL;
3152 
3153 	return __sys_recvmmsg(fd, mmsg, vlen, flags, NULL, timeout);
3154 }
3155 #endif
3156 
3157 #ifdef __ARCH_WANT_SYS_SOCKETCALL
3158 /* Argument list sizes for sys_socketcall */
3159 #define AL(x) ((x) * sizeof(unsigned long))
3160 static const unsigned char nargs[21] = {
3161 	AL(0), AL(3), AL(3), AL(3), AL(2), AL(3),
3162 	AL(3), AL(3), AL(4), AL(4), AL(4), AL(6),
3163 	AL(6), AL(2), AL(5), AL(5), AL(3), AL(3),
3164 	AL(4), AL(5), AL(4)
3165 };
3166 
3167 #undef AL
3168 
3169 /*
3170  *	System call vectors.
3171  *
3172  *	Argument checking cleaned up. Saved 20% in size.
3173  *  This function doesn't need to set the kernel lock because
3174  *  it is set by the callees.
3175  */
3176 
3177 SYSCALL_DEFINE2(socketcall, int, call, unsigned long __user *, args)
3178 {
3179 	unsigned long a[AUDITSC_ARGS];
3180 	unsigned long a0, a1;
3181 	int err;
3182 	unsigned int len;
3183 
3184 	if (call < 1 || call > SYS_SENDMMSG)
3185 		return -EINVAL;
3186 	call = array_index_nospec(call, SYS_SENDMMSG + 1);
3187 
3188 	len = nargs[call];
3189 	if (len > sizeof(a))
3190 		return -EINVAL;
3191 
3192 	/* copy_from_user should be SMP safe. */
3193 	if (copy_from_user(a, args, len))
3194 		return -EFAULT;
3195 
3196 	err = audit_socketcall(nargs[call] / sizeof(unsigned long), a);
3197 	if (err)
3198 		return err;
3199 
3200 	a0 = a[0];
3201 	a1 = a[1];
3202 
3203 	switch (call) {
3204 	case SYS_SOCKET:
3205 		err = __sys_socket(a0, a1, a[2]);
3206 		break;
3207 	case SYS_BIND:
3208 		err = __sys_bind(a0, (struct sockaddr __user *)a1, a[2]);
3209 		break;
3210 	case SYS_CONNECT:
3211 		err = __sys_connect(a0, (struct sockaddr __user *)a1, a[2]);
3212 		break;
3213 	case SYS_LISTEN:
3214 		err = __sys_listen(a0, a1);
3215 		break;
3216 	case SYS_ACCEPT:
3217 		err = __sys_accept4(a0, (struct sockaddr __user *)a1,
3218 				    (int __user *)a[2], 0);
3219 		break;
3220 	case SYS_GETSOCKNAME:
3221 		err =
3222 		    __sys_getsockname(a0, (struct sockaddr __user *)a1,
3223 				      (int __user *)a[2], 0);
3224 		break;
3225 	case SYS_GETPEERNAME:
3226 		err =
3227 		    __sys_getsockname(a0, (struct sockaddr __user *)a1,
3228 				      (int __user *)a[2], 1);
3229 		break;
3230 	case SYS_SOCKETPAIR:
3231 		err = __sys_socketpair(a0, a1, a[2], (int __user *)a[3]);
3232 		break;
3233 	case SYS_SEND:
3234 		err = __sys_sendto(a0, (void __user *)a1, a[2], a[3],
3235 				   NULL, 0);
3236 		break;
3237 	case SYS_SENDTO:
3238 		err = __sys_sendto(a0, (void __user *)a1, a[2], a[3],
3239 				   (struct sockaddr __user *)a[4], a[5]);
3240 		break;
3241 	case SYS_RECV:
3242 		err = __sys_recvfrom(a0, (void __user *)a1, a[2], a[3],
3243 				     NULL, NULL);
3244 		break;
3245 	case SYS_RECVFROM:
3246 		err = __sys_recvfrom(a0, (void __user *)a1, a[2], a[3],
3247 				     (struct sockaddr __user *)a[4],
3248 				     (int __user *)a[5]);
3249 		break;
3250 	case SYS_SHUTDOWN:
3251 		err = __sys_shutdown(a0, a1);
3252 		break;
3253 	case SYS_SETSOCKOPT:
3254 		err = __sys_setsockopt(a0, a1, a[2], (char __user *)a[3],
3255 				       a[4]);
3256 		break;
3257 	case SYS_GETSOCKOPT:
3258 		err =
3259 		    __sys_getsockopt(a0, a1, a[2], (char __user *)a[3],
3260 				     (int __user *)a[4]);
3261 		break;
3262 	case SYS_SENDMSG:
3263 		err = __sys_sendmsg(a0, (struct user_msghdr __user *)a1,
3264 				    a[2], true);
3265 		break;
3266 	case SYS_SENDMMSG:
3267 		err = __sys_sendmmsg(a0, (struct mmsghdr __user *)a1, a[2],
3268 				     a[3], true);
3269 		break;
3270 	case SYS_RECVMSG:
3271 		err = __sys_recvmsg(a0, (struct user_msghdr __user *)a1,
3272 				    a[2], true);
3273 		break;
3274 	case SYS_RECVMMSG:
3275 		if (IS_ENABLED(CONFIG_64BIT))
3276 			err = __sys_recvmmsg(a0, (struct mmsghdr __user *)a1,
3277 					     a[2], a[3],
3278 					     (struct __kernel_timespec __user *)a[4],
3279 					     NULL);
3280 		else
3281 			err = __sys_recvmmsg(a0, (struct mmsghdr __user *)a1,
3282 					     a[2], a[3], NULL,
3283 					     (struct old_timespec32 __user *)a[4]);
3284 		break;
3285 	case SYS_ACCEPT4:
3286 		err = __sys_accept4(a0, (struct sockaddr __user *)a1,
3287 				    (int __user *)a[2], a[3]);
3288 		break;
3289 	default:
3290 		err = -EINVAL;
3291 		break;
3292 	}
3293 	return err;
3294 }
3295 
3296 #endif				/* __ARCH_WANT_SYS_SOCKETCALL */
3297 
3298 /**
3299  *	sock_register - add a socket protocol handler
3300  *	@ops: description of protocol
3301  *
3302  *	This function is called by a protocol handler that wants to
3303  *	advertise its address family, and have it linked into the
3304  *	socket interface. The value ops->family corresponds to the
3305  *	socket system call protocol family.
3306  */
3307 int sock_register(const struct net_proto_family *ops)
3308 {
3309 	int err;
3310 
3311 	if (ops->family >= NPROTO) {
3312 		pr_crit("protocol %d >= NPROTO(%d)\n", ops->family, NPROTO);
3313 		return -ENOBUFS;
3314 	}
3315 
3316 	spin_lock(&net_family_lock);
3317 	if (rcu_dereference_protected(net_families[ops->family],
3318 				      lockdep_is_held(&net_family_lock)))
3319 		err = -EEXIST;
3320 	else {
3321 		rcu_assign_pointer(net_families[ops->family], ops);
3322 		err = 0;
3323 	}
3324 	spin_unlock(&net_family_lock);
3325 
3326 	pr_info("NET: Registered %s protocol family\n", pf_family_names[ops->family]);
3327 	return err;
3328 }
3329 EXPORT_SYMBOL(sock_register);
3330 
3331 /**
3332  *	sock_unregister - remove a protocol handler
3333  *	@family: protocol family to remove
3334  *
3335  *	This function is called by a protocol handler that wants to
3336  *	remove its address family, and have it unlinked from the
3337  *	new socket creation.
3338  *
3339  *	If protocol handler is a module, then it can use module reference
3340  *	counts to protect against new references. If protocol handler is not
3341  *	a module then it needs to provide its own protection in
3342  *	the ops->create routine.
3343  */
3344 void sock_unregister(int family)
3345 {
3346 	BUG_ON(family < 0 || family >= NPROTO);
3347 
3348 	spin_lock(&net_family_lock);
3349 	RCU_INIT_POINTER(net_families[family], NULL);
3350 	spin_unlock(&net_family_lock);
3351 
3352 	synchronize_rcu();
3353 
3354 	pr_info("NET: Unregistered %s protocol family\n", pf_family_names[family]);
3355 }
3356 EXPORT_SYMBOL(sock_unregister);
3357 
3358 bool sock_is_registered(int family)
3359 {
3360 	return family < NPROTO && rcu_access_pointer(net_families[family]);
3361 }
3362 
3363 static int __init sock_init(void)
3364 {
3365 	int err;
3366 	/*
3367 	 *      Initialize the network sysctl infrastructure.
3368 	 */
3369 	err = net_sysctl_init();
3370 	if (err)
3371 		goto out;
3372 
3373 	/*
3374 	 *      Initialize skbuff SLAB cache
3375 	 */
3376 	skb_init();
3377 
3378 	/*
3379 	 *      Initialize the protocols module.
3380 	 */
3381 
3382 	init_inodecache();
3383 
3384 	err = register_filesystem(&sock_fs_type);
3385 	if (err)
3386 		goto out;
3387 	sock_mnt = kern_mount(&sock_fs_type);
3388 	if (IS_ERR(sock_mnt)) {
3389 		err = PTR_ERR(sock_mnt);
3390 		goto out_mount;
3391 	}
3392 
3393 	/* The real protocol initialization is performed in later initcalls.
3394 	 */
3395 
3396 #ifdef CONFIG_NETFILTER
3397 	err = netfilter_init();
3398 	if (err)
3399 		goto out;
3400 #endif
3401 
3402 	ptp_classifier_init();
3403 
3404 out:
3405 	return err;
3406 
3407 out_mount:
3408 	unregister_filesystem(&sock_fs_type);
3409 	goto out;
3410 }
3411 
3412 core_initcall(sock_init);	/* early initcall */
3413 
3414 #ifdef CONFIG_PROC_FS
3415 void socket_seq_show(struct seq_file *seq)
3416 {
3417 	seq_printf(seq, "sockets: used %d\n",
3418 		   sock_inuse_get(seq->private));
3419 }
3420 #endif				/* CONFIG_PROC_FS */
3421 
3422 /* Handle the fact that while struct ifreq has the same *layout* on
3423  * 32/64 for everything but ifreq::ifru_ifmap and ifreq::ifru_data,
3424  * which are handled elsewhere, it still has different *size* due to
3425  * ifreq::ifru_ifmap (which is 16 bytes on 32 bit, 24 bytes on 64-bit,
3426  * resulting in struct ifreq being 32 and 40 bytes respectively).
3427  * As a result, if the struct happens to be at the end of a page and
3428  * the next page isn't readable/writable, we get a fault. To prevent
3429  * that, copy back and forth to the full size.
3430  */
3431 int get_user_ifreq(struct ifreq *ifr, void __user **ifrdata, void __user *arg)
3432 {
3433 	if (in_compat_syscall()) {
3434 		struct compat_ifreq *ifr32 = (struct compat_ifreq *)ifr;
3435 
3436 		memset(ifr, 0, sizeof(*ifr));
3437 		if (copy_from_user(ifr32, arg, sizeof(*ifr32)))
3438 			return -EFAULT;
3439 
3440 		if (ifrdata)
3441 			*ifrdata = compat_ptr(ifr32->ifr_data);
3442 
3443 		return 0;
3444 	}
3445 
3446 	if (copy_from_user(ifr, arg, sizeof(*ifr)))
3447 		return -EFAULT;
3448 
3449 	if (ifrdata)
3450 		*ifrdata = ifr->ifr_data;
3451 
3452 	return 0;
3453 }
3454 EXPORT_SYMBOL(get_user_ifreq);
3455 
3456 int put_user_ifreq(struct ifreq *ifr, void __user *arg)
3457 {
3458 	size_t size = sizeof(*ifr);
3459 
3460 	if (in_compat_syscall())
3461 		size = sizeof(struct compat_ifreq);
3462 
3463 	if (copy_to_user(arg, ifr, size))
3464 		return -EFAULT;
3465 
3466 	return 0;
3467 }
3468 EXPORT_SYMBOL(put_user_ifreq);
3469 
3470 #ifdef CONFIG_COMPAT
3471 static int compat_siocwandev(struct net *net, struct compat_ifreq __user *uifr32)
3472 {
3473 	compat_uptr_t uptr32;
3474 	struct ifreq ifr;
3475 	void __user *saved;
3476 	int err;
3477 
3478 	if (get_user_ifreq(&ifr, NULL, uifr32))
3479 		return -EFAULT;
3480 
3481 	if (get_user(uptr32, &uifr32->ifr_settings.ifs_ifsu))
3482 		return -EFAULT;
3483 
3484 	saved = ifr.ifr_settings.ifs_ifsu.raw_hdlc;
3485 	ifr.ifr_settings.ifs_ifsu.raw_hdlc = compat_ptr(uptr32);
3486 
3487 	err = dev_ioctl(net, SIOCWANDEV, &ifr, NULL, NULL);
3488 	if (!err) {
3489 		ifr.ifr_settings.ifs_ifsu.raw_hdlc = saved;
3490 		if (put_user_ifreq(&ifr, uifr32))
3491 			err = -EFAULT;
3492 	}
3493 	return err;
3494 }
3495 
3496 /* Handle ioctls that use ifreq::ifr_data and just need struct ifreq converted */
3497 static int compat_ifr_data_ioctl(struct net *net, unsigned int cmd,
3498 				 struct compat_ifreq __user *u_ifreq32)
3499 {
3500 	struct ifreq ifreq;
3501 	void __user *data;
3502 
3503 	if (!is_socket_ioctl_cmd(cmd))
3504 		return -ENOTTY;
3505 	if (get_user_ifreq(&ifreq, &data, u_ifreq32))
3506 		return -EFAULT;
3507 	ifreq.ifr_data = data;
3508 
3509 	return dev_ioctl(net, cmd, &ifreq, data, NULL);
3510 }
3511 
3512 static int compat_sock_ioctl_trans(struct file *file, struct socket *sock,
3513 			 unsigned int cmd, unsigned long arg)
3514 {
3515 	void __user *argp = compat_ptr(arg);
3516 	struct sock *sk = sock->sk;
3517 	struct net *net = sock_net(sk);
3518 	const struct proto_ops *ops;
3519 
3520 	if (cmd >= SIOCDEVPRIVATE && cmd <= (SIOCDEVPRIVATE + 15))
3521 		return sock_ioctl(file, cmd, (unsigned long)argp);
3522 
3523 	switch (cmd) {
3524 	case SIOCWANDEV:
3525 		return compat_siocwandev(net, argp);
3526 	case SIOCGSTAMP_OLD:
3527 	case SIOCGSTAMPNS_OLD:
3528 		ops = READ_ONCE(sock->ops);
3529 		if (!ops->gettstamp)
3530 			return -ENOIOCTLCMD;
3531 		return ops->gettstamp(sock, argp, cmd == SIOCGSTAMP_OLD,
3532 				      !COMPAT_USE_64BIT_TIME);
3533 
3534 	case SIOCETHTOOL:
3535 	case SIOCBONDSLAVEINFOQUERY:
3536 	case SIOCBONDINFOQUERY:
3537 	case SIOCSHWTSTAMP:
3538 	case SIOCGHWTSTAMP:
3539 		return compat_ifr_data_ioctl(net, cmd, argp);
3540 
3541 	case FIOSETOWN:
3542 	case SIOCSPGRP:
3543 	case FIOGETOWN:
3544 	case SIOCGPGRP:
3545 	case SIOCBRADDBR:
3546 	case SIOCBRDELBR:
3547 	case SIOCBRADDIF:
3548 	case SIOCBRDELIF:
3549 	case SIOCGIFVLAN:
3550 	case SIOCSIFVLAN:
3551 	case SIOCGSKNS:
3552 	case SIOCGSTAMP_NEW:
3553 	case SIOCGSTAMPNS_NEW:
3554 	case SIOCGIFCONF:
3555 	case SIOCSIFBR:
3556 	case SIOCGIFBR:
3557 		return sock_ioctl(file, cmd, arg);
3558 
3559 	case SIOCGIFFLAGS:
3560 	case SIOCSIFFLAGS:
3561 	case SIOCGIFMAP:
3562 	case SIOCSIFMAP:
3563 	case SIOCGIFMETRIC:
3564 	case SIOCSIFMETRIC:
3565 	case SIOCGIFMTU:
3566 	case SIOCSIFMTU:
3567 	case SIOCGIFMEM:
3568 	case SIOCSIFMEM:
3569 	case SIOCGIFHWADDR:
3570 	case SIOCSIFHWADDR:
3571 	case SIOCADDMULTI:
3572 	case SIOCDELMULTI:
3573 	case SIOCGIFINDEX:
3574 	case SIOCGIFADDR:
3575 	case SIOCSIFADDR:
3576 	case SIOCSIFHWBROADCAST:
3577 	case SIOCDIFADDR:
3578 	case SIOCGIFBRDADDR:
3579 	case SIOCSIFBRDADDR:
3580 	case SIOCGIFDSTADDR:
3581 	case SIOCSIFDSTADDR:
3582 	case SIOCGIFNETMASK:
3583 	case SIOCSIFNETMASK:
3584 	case SIOCSIFPFLAGS:
3585 	case SIOCGIFPFLAGS:
3586 	case SIOCGIFTXQLEN:
3587 	case SIOCSIFTXQLEN:
3588 	case SIOCGIFNAME:
3589 	case SIOCSIFNAME:
3590 	case SIOCGMIIPHY:
3591 	case SIOCGMIIREG:
3592 	case SIOCSMIIREG:
3593 	case SIOCBONDENSLAVE:
3594 	case SIOCBONDRELEASE:
3595 	case SIOCBONDSETHWADDR:
3596 	case SIOCBONDCHANGEACTIVE:
3597 	case SIOCSARP:
3598 	case SIOCGARP:
3599 	case SIOCDARP:
3600 	case SIOCOUTQ:
3601 	case SIOCOUTQNSD:
3602 	case SIOCATMARK:
3603 		return sock_do_ioctl(net, sock, cmd, arg);
3604 	}
3605 
3606 	return -ENOIOCTLCMD;
3607 }
3608 
3609 static long compat_sock_ioctl(struct file *file, unsigned int cmd,
3610 			      unsigned long arg)
3611 {
3612 	struct socket *sock = file->private_data;
3613 	const struct proto_ops *ops = READ_ONCE(sock->ops);
3614 	int ret = -ENOIOCTLCMD;
3615 	struct sock *sk;
3616 	struct net *net;
3617 
3618 	sk = sock->sk;
3619 	net = sock_net(sk);
3620 
3621 	if (ops->compat_ioctl)
3622 		ret = ops->compat_ioctl(sock, cmd, arg);
3623 
3624 	if (ret == -ENOIOCTLCMD &&
3625 	    (cmd >= SIOCIWFIRST && cmd <= SIOCIWLAST))
3626 		ret = compat_wext_handle_ioctl(net, cmd, arg);
3627 
3628 	if (ret == -ENOIOCTLCMD)
3629 		ret = compat_sock_ioctl_trans(file, sock, cmd, arg);
3630 
3631 	return ret;
3632 }
3633 #endif
3634 
3635 /**
3636  *	kernel_bind - bind an address to a socket (kernel space)
3637  *	@sock: socket
3638  *	@addr: address
3639  *	@addrlen: length of address
3640  *
3641  *	Returns 0 or an error.
3642  */
3643 
3644 int kernel_bind(struct socket *sock, struct sockaddr_unsized *addr, int addrlen)
3645 {
3646 	struct sockaddr_storage address;
3647 
3648 	memcpy(&address, addr, addrlen);
3649 
3650 	return READ_ONCE(sock->ops)->bind(sock, (struct sockaddr_unsized *)&address,
3651 					  addrlen);
3652 }
3653 EXPORT_SYMBOL(kernel_bind);
3654 
3655 /**
3656  *	kernel_listen - move socket to listening state (kernel space)
3657  *	@sock: socket
3658  *	@backlog: pending connections queue size
3659  *
3660  *	Returns 0 or an error.
3661  */
3662 
3663 int kernel_listen(struct socket *sock, int backlog)
3664 {
3665 	return READ_ONCE(sock->ops)->listen(sock, backlog);
3666 }
3667 EXPORT_SYMBOL(kernel_listen);
3668 
3669 /**
3670  *	kernel_accept - accept a connection (kernel space)
3671  *	@sock: listening socket
3672  *	@newsock: new connected socket
3673  *	@flags: flags
3674  *
3675  *	@flags must be SOCK_CLOEXEC, SOCK_NONBLOCK or 0.
3676  *	If it fails, @newsock is guaranteed to be %NULL.
3677  *	Returns 0 or an error.
3678  */
3679 
3680 int kernel_accept(struct socket *sock, struct socket **newsock, int flags)
3681 {
3682 	struct sock *sk = sock->sk;
3683 	const struct proto_ops *ops = READ_ONCE(sock->ops);
3684 	struct proto_accept_arg arg = {
3685 		.flags = flags,
3686 		.kern = true,
3687 	};
3688 	int err;
3689 
3690 	err = sock_create_lite(sk->sk_family, sk->sk_type, sk->sk_protocol,
3691 			       newsock);
3692 	if (err < 0)
3693 		goto done;
3694 
3695 	err = ops->accept(sock, *newsock, &arg);
3696 	if (err < 0) {
3697 		sock_release(*newsock);
3698 		*newsock = NULL;
3699 		goto done;
3700 	}
3701 
3702 	(*newsock)->ops = ops;
3703 	__module_get(ops->owner);
3704 
3705 done:
3706 	return err;
3707 }
3708 EXPORT_SYMBOL(kernel_accept);
3709 
3710 /**
3711  *	kernel_connect - connect a socket (kernel space)
3712  *	@sock: socket
3713  *	@addr: address
3714  *	@addrlen: address length
3715  *	@flags: flags (O_NONBLOCK, ...)
3716  *
3717  *	For datagram sockets, @addr is the address to which datagrams are sent
3718  *	by default, and the only address from which datagrams are received.
3719  *	For stream sockets, attempts to connect to @addr.
3720  *	Returns 0 or an error code.
3721  */
3722 
3723 int kernel_connect(struct socket *sock, struct sockaddr_unsized *addr, int addrlen,
3724 		   int flags)
3725 {
3726 	struct sockaddr_storage address;
3727 
3728 	memcpy(&address, addr, addrlen);
3729 
3730 	return READ_ONCE(sock->ops)->connect(sock, (struct sockaddr_unsized *)&address,
3731 					     addrlen, flags);
3732 }
3733 EXPORT_SYMBOL(kernel_connect);
3734 
3735 /**
3736  *	kernel_getsockname - get the address which the socket is bound (kernel space)
3737  *	@sock: socket
3738  *	@addr: address holder
3739  *
3740  * 	Fills the @addr pointer with the address which the socket is bound.
3741  *	Returns the length of the address in bytes or an error code.
3742  */
3743 
3744 int kernel_getsockname(struct socket *sock, struct sockaddr *addr)
3745 {
3746 	return READ_ONCE(sock->ops)->getname(sock, addr, 0);
3747 }
3748 EXPORT_SYMBOL(kernel_getsockname);
3749 
3750 /**
3751  *	kernel_getpeername - get the address which the socket is connected (kernel space)
3752  *	@sock: socket
3753  *	@addr: address holder
3754  *
3755  * 	Fills the @addr pointer with the address which the socket is connected.
3756  *	Returns the length of the address in bytes or an error code.
3757  */
3758 
3759 int kernel_getpeername(struct socket *sock, struct sockaddr *addr)
3760 {
3761 	return READ_ONCE(sock->ops)->getname(sock, addr, 1);
3762 }
3763 EXPORT_SYMBOL(kernel_getpeername);
3764 
3765 /**
3766  *	kernel_sock_shutdown - shut down part of a full-duplex connection (kernel space)
3767  *	@sock: socket
3768  *	@how: connection part
3769  *
3770  *	Returns 0 or an error.
3771  */
3772 
3773 int kernel_sock_shutdown(struct socket *sock, enum sock_shutdown_cmd how)
3774 {
3775 	return READ_ONCE(sock->ops)->shutdown(sock, how);
3776 }
3777 EXPORT_SYMBOL(kernel_sock_shutdown);
3778 
3779 /**
3780  *	kernel_sock_ip_overhead - returns the IP overhead imposed by a socket
3781  *	@sk: socket
3782  *
3783  *	This routine returns the IP overhead imposed by a socket i.e.
3784  *	the length of the underlying IP header, depending on whether
3785  *	this is an IPv4 or IPv6 socket and the length from IP options turned
3786  *	on at the socket. Assumes that the caller has a lock on the socket.
3787  */
3788 
3789 u32 kernel_sock_ip_overhead(struct sock *sk)
3790 {
3791 	struct inet_sock *inet;
3792 	struct ip_options_rcu *opt;
3793 	u32 overhead = 0;
3794 #if IS_ENABLED(CONFIG_IPV6)
3795 	struct ipv6_pinfo *np;
3796 	struct ipv6_txoptions *optv6 = NULL;
3797 #endif /* IS_ENABLED(CONFIG_IPV6) */
3798 
3799 	if (!sk)
3800 		return overhead;
3801 
3802 	switch (sk->sk_family) {
3803 	case AF_INET:
3804 		inet = inet_sk(sk);
3805 		overhead += sizeof(struct iphdr);
3806 		opt = rcu_dereference_protected(inet->inet_opt,
3807 						sock_owned_by_user(sk));
3808 		if (opt)
3809 			overhead += opt->opt.optlen;
3810 		return overhead;
3811 #if IS_ENABLED(CONFIG_IPV6)
3812 	case AF_INET6:
3813 		np = inet6_sk(sk);
3814 		overhead += sizeof(struct ipv6hdr);
3815 		if (np)
3816 			optv6 = rcu_dereference_protected(np->opt,
3817 							  sock_owned_by_user(sk));
3818 		if (optv6)
3819 			overhead += (optv6->opt_flen + optv6->opt_nflen);
3820 		return overhead;
3821 #endif /* IS_ENABLED(CONFIG_IPV6) */
3822 	default: /* Returns 0 overhead if the socket is not ipv4 or ipv6 */
3823 		return overhead;
3824 	}
3825 }
3826 EXPORT_SYMBOL(kernel_sock_ip_overhead);
3827