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