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