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