fb885977bd2a534e87006bb47f7db546508cbc1a
[firefly-linux-kernel-4.4.55.git] / net / tipc / socket.c
1 /*
2  * net/tipc/socket.c: TIPC socket API
3  *
4  * Copyright (c) 2001-2007, 2012 Ericsson AB
5  * Copyright (c) 2004-2008, 2010-2013, Wind River Systems
6  * All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions are met:
10  *
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 3. Neither the names of the copyright holders nor the names of its
17  *    contributors may be used to endorse or promote products derived from
18  *    this software without specific prior written permission.
19  *
20  * Alternatively, this software may be distributed under the terms of the
21  * GNU General Public License ("GPL") version 2 as published by the Free
22  * Software Foundation.
23  *
24  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
25  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27  * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
28  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
29  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
30  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
31  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
32  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
33  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
34  * POSSIBILITY OF SUCH DAMAGE.
35  */
36
37 #include "core.h"
38 #include "port.h"
39
40 #include <linux/export.h>
41 #include <net/sock.h>
42
43 #define SS_LISTENING    -1      /* socket is listening */
44 #define SS_READY        -2      /* socket is connectionless */
45
46 #define CONN_TIMEOUT_DEFAULT    8000    /* default connect timeout = 8s */
47
48 struct tipc_sock {
49         struct sock sk;
50         struct tipc_port *p;
51         struct tipc_portid peer_name;
52         unsigned int conn_timeout;
53 };
54
55 #define tipc_sk(sk) ((struct tipc_sock *)(sk))
56 #define tipc_sk_port(sk) (tipc_sk(sk)->p)
57
58 static int backlog_rcv(struct sock *sk, struct sk_buff *skb);
59 static u32 dispatch(struct tipc_port *tport, struct sk_buff *buf);
60 static void wakeupdispatch(struct tipc_port *tport);
61 static void tipc_data_ready(struct sock *sk, int len);
62 static void tipc_write_space(struct sock *sk);
63 static int tipc_release(struct socket *sock);
64 static int tipc_accept(struct socket *sock, struct socket *new_sock, int flags);
65
66 static const struct proto_ops packet_ops;
67 static const struct proto_ops stream_ops;
68 static const struct proto_ops msg_ops;
69
70 static struct proto tipc_proto;
71 static struct proto tipc_proto_kern;
72
73 static int sockets_enabled;
74
75 /*
76  * Revised TIPC socket locking policy:
77  *
78  * Most socket operations take the standard socket lock when they start
79  * and hold it until they finish (or until they need to sleep).  Acquiring
80  * this lock grants the owner exclusive access to the fields of the socket
81  * data structures, with the exception of the backlog queue.  A few socket
82  * operations can be done without taking the socket lock because they only
83  * read socket information that never changes during the life of the socket.
84  *
85  * Socket operations may acquire the lock for the associated TIPC port if they
86  * need to perform an operation on the port.  If any routine needs to acquire
87  * both the socket lock and the port lock it must take the socket lock first
88  * to avoid the risk of deadlock.
89  *
90  * The dispatcher handling incoming messages cannot grab the socket lock in
91  * the standard fashion, since invoked it runs at the BH level and cannot block.
92  * Instead, it checks to see if the socket lock is currently owned by someone,
93  * and either handles the message itself or adds it to the socket's backlog
94  * queue; in the latter case the queued message is processed once the process
95  * owning the socket lock releases it.
96  *
97  * NOTE: Releasing the socket lock while an operation is sleeping overcomes
98  * the problem of a blocked socket operation preventing any other operations
99  * from occurring.  However, applications must be careful if they have
100  * multiple threads trying to send (or receive) on the same socket, as these
101  * operations might interfere with each other.  For example, doing a connect
102  * and a receive at the same time might allow the receive to consume the
103  * ACK message meant for the connect.  While additional work could be done
104  * to try and overcome this, it doesn't seem to be worthwhile at the present.
105  *
106  * NOTE: Releasing the socket lock while an operation is sleeping also ensures
107  * that another operation that must be performed in a non-blocking manner is
108  * not delayed for very long because the lock has already been taken.
109  *
110  * NOTE: This code assumes that certain fields of a port/socket pair are
111  * constant over its lifetime; such fields can be examined without taking
112  * the socket lock and/or port lock, and do not need to be re-read even
113  * after resuming processing after waiting.  These fields include:
114  *   - socket type
115  *   - pointer to socket sk structure (aka tipc_sock structure)
116  *   - pointer to port structure
117  *   - port reference
118  */
119
120 /**
121  * advance_rx_queue - discard first buffer in socket receive queue
122  *
123  * Caller must hold socket lock
124  */
125 static void advance_rx_queue(struct sock *sk)
126 {
127         kfree_skb(__skb_dequeue(&sk->sk_receive_queue));
128 }
129
130 /**
131  * reject_rx_queue - reject all buffers in socket receive queue
132  *
133  * Caller must hold socket lock
134  */
135 static void reject_rx_queue(struct sock *sk)
136 {
137         struct sk_buff *buf;
138
139         while ((buf = __skb_dequeue(&sk->sk_receive_queue)))
140                 tipc_reject_msg(buf, TIPC_ERR_NO_PORT);
141 }
142
143 /**
144  * tipc_sk_create - create a TIPC socket
145  * @net: network namespace (must be default network)
146  * @sock: pre-allocated socket structure
147  * @protocol: protocol indicator (must be 0)
148  * @kern: caused by kernel or by userspace?
149  *
150  * This routine creates additional data structures used by the TIPC socket,
151  * initializes them, and links them together.
152  *
153  * Returns 0 on success, errno otherwise
154  */
155 static int tipc_sk_create(struct net *net, struct socket *sock, int protocol,
156                           int kern)
157 {
158         const struct proto_ops *ops;
159         socket_state state;
160         struct sock *sk;
161         struct tipc_port *tp_ptr;
162
163         /* Validate arguments */
164         if (unlikely(protocol != 0))
165                 return -EPROTONOSUPPORT;
166
167         switch (sock->type) {
168         case SOCK_STREAM:
169                 ops = &stream_ops;
170                 state = SS_UNCONNECTED;
171                 break;
172         case SOCK_SEQPACKET:
173                 ops = &packet_ops;
174                 state = SS_UNCONNECTED;
175                 break;
176         case SOCK_DGRAM:
177         case SOCK_RDM:
178                 ops = &msg_ops;
179                 state = SS_READY;
180                 break;
181         default:
182                 return -EPROTOTYPE;
183         }
184
185         /* Allocate socket's protocol area */
186         if (!kern)
187                 sk = sk_alloc(net, AF_TIPC, GFP_KERNEL, &tipc_proto);
188         else
189                 sk = sk_alloc(net, AF_TIPC, GFP_KERNEL, &tipc_proto_kern);
190
191         if (sk == NULL)
192                 return -ENOMEM;
193
194         /* Allocate TIPC port for socket to use */
195         tp_ptr = tipc_createport(sk, &dispatch, &wakeupdispatch,
196                                  TIPC_LOW_IMPORTANCE);
197         if (unlikely(!tp_ptr)) {
198                 sk_free(sk);
199                 return -ENOMEM;
200         }
201
202         /* Finish initializing socket data structures */
203         sock->ops = ops;
204         sock->state = state;
205
206         sock_init_data(sock, sk);
207         sk->sk_backlog_rcv = backlog_rcv;
208         sk->sk_rcvbuf = sysctl_tipc_rmem[1];
209         sk->sk_data_ready = tipc_data_ready;
210         sk->sk_write_space = tipc_write_space;
211         tipc_sk(sk)->p = tp_ptr;
212         tipc_sk(sk)->conn_timeout = CONN_TIMEOUT_DEFAULT;
213
214         spin_unlock_bh(tp_ptr->lock);
215
216         if (sock->state == SS_READY) {
217                 tipc_set_portunreturnable(tp_ptr->ref, 1);
218                 if (sock->type == SOCK_DGRAM)
219                         tipc_set_portunreliable(tp_ptr->ref, 1);
220         }
221
222         return 0;
223 }
224
225 /**
226  * tipc_sock_create_local - create TIPC socket from inside TIPC module
227  * @type: socket type - SOCK_RDM or SOCK_SEQPACKET
228  *
229  * We cannot use sock_creat_kern here because it bumps module user count.
230  * Since socket owner and creator is the same module we must make sure
231  * that module count remains zero for module local sockets, otherwise
232  * we cannot do rmmod.
233  *
234  * Returns 0 on success, errno otherwise
235  */
236 int tipc_sock_create_local(int type, struct socket **res)
237 {
238         int rc;
239
240         rc = sock_create_lite(AF_TIPC, type, 0, res);
241         if (rc < 0) {
242                 pr_err("Failed to create kernel socket\n");
243                 return rc;
244         }
245         tipc_sk_create(&init_net, *res, 0, 1);
246
247         return 0;
248 }
249
250 /**
251  * tipc_sock_release_local - release socket created by tipc_sock_create_local
252  * @sock: the socket to be released.
253  *
254  * Module reference count is not incremented when such sockets are created,
255  * so we must keep it from being decremented when they are released.
256  */
257 void tipc_sock_release_local(struct socket *sock)
258 {
259         tipc_release(sock);
260         sock->ops = NULL;
261         sock_release(sock);
262 }
263
264 /**
265  * tipc_sock_accept_local - accept a connection on a socket created
266  * with tipc_sock_create_local. Use this function to avoid that
267  * module reference count is inadvertently incremented.
268  *
269  * @sock:    the accepting socket
270  * @newsock: reference to the new socket to be created
271  * @flags:   socket flags
272  */
273
274 int tipc_sock_accept_local(struct socket *sock, struct socket **newsock,
275                            int flags)
276 {
277         struct sock *sk = sock->sk;
278         int ret;
279
280         ret = sock_create_lite(sk->sk_family, sk->sk_type,
281                                sk->sk_protocol, newsock);
282         if (ret < 0)
283                 return ret;
284
285         ret = tipc_accept(sock, *newsock, flags);
286         if (ret < 0) {
287                 sock_release(*newsock);
288                 return ret;
289         }
290         (*newsock)->ops = sock->ops;
291         return ret;
292 }
293
294 /**
295  * tipc_release - destroy a TIPC socket
296  * @sock: socket to destroy
297  *
298  * This routine cleans up any messages that are still queued on the socket.
299  * For DGRAM and RDM socket types, all queued messages are rejected.
300  * For SEQPACKET and STREAM socket types, the first message is rejected
301  * and any others are discarded.  (If the first message on a STREAM socket
302  * is partially-read, it is discarded and the next one is rejected instead.)
303  *
304  * NOTE: Rejected messages are not necessarily returned to the sender!  They
305  * are returned or discarded according to the "destination droppable" setting
306  * specified for the message by the sender.
307  *
308  * Returns 0 on success, errno otherwise
309  */
310 static int tipc_release(struct socket *sock)
311 {
312         struct sock *sk = sock->sk;
313         struct tipc_port *tport;
314         struct sk_buff *buf;
315         int res;
316
317         /*
318          * Exit if socket isn't fully initialized (occurs when a failed accept()
319          * releases a pre-allocated child socket that was never used)
320          */
321         if (sk == NULL)
322                 return 0;
323
324         tport = tipc_sk_port(sk);
325         lock_sock(sk);
326
327         /*
328          * Reject all unreceived messages, except on an active connection
329          * (which disconnects locally & sends a 'FIN+' to peer)
330          */
331         while (sock->state != SS_DISCONNECTING) {
332                 buf = __skb_dequeue(&sk->sk_receive_queue);
333                 if (buf == NULL)
334                         break;
335                 if (TIPC_SKB_CB(buf)->handle != NULL)
336                         kfree_skb(buf);
337                 else {
338                         if ((sock->state == SS_CONNECTING) ||
339                             (sock->state == SS_CONNECTED)) {
340                                 sock->state = SS_DISCONNECTING;
341                                 tipc_port_disconnect(tport->ref);
342                         }
343                         tipc_reject_msg(buf, TIPC_ERR_NO_PORT);
344                 }
345         }
346
347         /*
348          * Delete TIPC port; this ensures no more messages are queued
349          * (also disconnects an active connection & sends a 'FIN-' to peer)
350          */
351         res = tipc_deleteport(tport);
352
353         /* Discard any remaining (connection-based) messages in receive queue */
354         __skb_queue_purge(&sk->sk_receive_queue);
355
356         /* Reject any messages that accumulated in backlog queue */
357         sock->state = SS_DISCONNECTING;
358         release_sock(sk);
359
360         sock_put(sk);
361         sock->sk = NULL;
362
363         return res;
364 }
365
366 /**
367  * tipc_bind - associate or disassocate TIPC name(s) with a socket
368  * @sock: socket structure
369  * @uaddr: socket address describing name(s) and desired operation
370  * @uaddr_len: size of socket address data structure
371  *
372  * Name and name sequence binding is indicated using a positive scope value;
373  * a negative scope value unbinds the specified name.  Specifying no name
374  * (i.e. a socket address length of 0) unbinds all names from the socket.
375  *
376  * Returns 0 on success, errno otherwise
377  *
378  * NOTE: This routine doesn't need to take the socket lock since it doesn't
379  *       access any non-constant socket information.
380  */
381 static int tipc_bind(struct socket *sock, struct sockaddr *uaddr,
382                      int uaddr_len)
383 {
384         struct sock *sk = sock->sk;
385         struct sockaddr_tipc *addr = (struct sockaddr_tipc *)uaddr;
386         struct tipc_port *tport = tipc_sk_port(sock->sk);
387         int res = -EINVAL;
388
389         lock_sock(sk);
390         if (unlikely(!uaddr_len)) {
391                 res = tipc_withdraw(tport, 0, NULL);
392                 goto exit;
393         }
394
395         if (uaddr_len < sizeof(struct sockaddr_tipc)) {
396                 res = -EINVAL;
397                 goto exit;
398         }
399         if (addr->family != AF_TIPC) {
400                 res = -EAFNOSUPPORT;
401                 goto exit;
402         }
403
404         if (addr->addrtype == TIPC_ADDR_NAME)
405                 addr->addr.nameseq.upper = addr->addr.nameseq.lower;
406         else if (addr->addrtype != TIPC_ADDR_NAMESEQ) {
407                 res = -EAFNOSUPPORT;
408                 goto exit;
409         }
410
411         if ((addr->addr.nameseq.type < TIPC_RESERVED_TYPES) &&
412             (addr->addr.nameseq.type != TIPC_TOP_SRV) &&
413             (addr->addr.nameseq.type != TIPC_CFG_SRV)) {
414                 res = -EACCES;
415                 goto exit;
416         }
417
418         res = (addr->scope > 0) ?
419                 tipc_publish(tport, addr->scope, &addr->addr.nameseq) :
420                 tipc_withdraw(tport, -addr->scope, &addr->addr.nameseq);
421 exit:
422         release_sock(sk);
423         return res;
424 }
425
426 /**
427  * tipc_getname - get port ID of socket or peer socket
428  * @sock: socket structure
429  * @uaddr: area for returned socket address
430  * @uaddr_len: area for returned length of socket address
431  * @peer: 0 = own ID, 1 = current peer ID, 2 = current/former peer ID
432  *
433  * Returns 0 on success, errno otherwise
434  *
435  * NOTE: This routine doesn't need to take the socket lock since it only
436  *       accesses socket information that is unchanging (or which changes in
437  *       a completely predictable manner).
438  */
439 static int tipc_getname(struct socket *sock, struct sockaddr *uaddr,
440                         int *uaddr_len, int peer)
441 {
442         struct sockaddr_tipc *addr = (struct sockaddr_tipc *)uaddr;
443         struct tipc_sock *tsock = tipc_sk(sock->sk);
444
445         memset(addr, 0, sizeof(*addr));
446         if (peer) {
447                 if ((sock->state != SS_CONNECTED) &&
448                         ((peer != 2) || (sock->state != SS_DISCONNECTING)))
449                         return -ENOTCONN;
450                 addr->addr.id.ref = tsock->peer_name.ref;
451                 addr->addr.id.node = tsock->peer_name.node;
452         } else {
453                 addr->addr.id.ref = tsock->p->ref;
454                 addr->addr.id.node = tipc_own_addr;
455         }
456
457         *uaddr_len = sizeof(*addr);
458         addr->addrtype = TIPC_ADDR_ID;
459         addr->family = AF_TIPC;
460         addr->scope = 0;
461         addr->addr.name.domain = 0;
462
463         return 0;
464 }
465
466 /**
467  * tipc_poll - read and possibly block on pollmask
468  * @file: file structure associated with the socket
469  * @sock: socket for which to calculate the poll bits
470  * @wait: ???
471  *
472  * Returns pollmask value
473  *
474  * COMMENTARY:
475  * It appears that the usual socket locking mechanisms are not useful here
476  * since the pollmask info is potentially out-of-date the moment this routine
477  * exits.  TCP and other protocols seem to rely on higher level poll routines
478  * to handle any preventable race conditions, so TIPC will do the same ...
479  *
480  * TIPC sets the returned events as follows:
481  *
482  * socket state         flags set
483  * ------------         ---------
484  * unconnected          no read flags
485  *                      POLLOUT if port is not congested
486  *
487  * connecting           POLLIN/POLLRDNORM if ACK/NACK in rx queue
488  *                      no write flags
489  *
490  * connected            POLLIN/POLLRDNORM if data in rx queue
491  *                      POLLOUT if port is not congested
492  *
493  * disconnecting        POLLIN/POLLRDNORM/POLLHUP
494  *                      no write flags
495  *
496  * listening            POLLIN if SYN in rx queue
497  *                      no write flags
498  *
499  * ready                POLLIN/POLLRDNORM if data in rx queue
500  * [connectionless]     POLLOUT (since port cannot be congested)
501  *
502  * IMPORTANT: The fact that a read or write operation is indicated does NOT
503  * imply that the operation will succeed, merely that it should be performed
504  * and will not block.
505  */
506 static unsigned int tipc_poll(struct file *file, struct socket *sock,
507                               poll_table *wait)
508 {
509         struct sock *sk = sock->sk;
510         u32 mask = 0;
511
512         sock_poll_wait(file, sk_sleep(sk), wait);
513
514         switch ((int)sock->state) {
515         case SS_UNCONNECTED:
516                 if (!tipc_sk_port(sk)->congested)
517                         mask |= POLLOUT;
518                 break;
519         case SS_READY:
520         case SS_CONNECTED:
521                 if (!tipc_sk_port(sk)->congested)
522                         mask |= POLLOUT;
523                 /* fall thru' */
524         case SS_CONNECTING:
525         case SS_LISTENING:
526                 if (!skb_queue_empty(&sk->sk_receive_queue))
527                         mask |= (POLLIN | POLLRDNORM);
528                 break;
529         case SS_DISCONNECTING:
530                 mask = (POLLIN | POLLRDNORM | POLLHUP);
531                 break;
532         }
533
534         return mask;
535 }
536
537 /**
538  * dest_name_check - verify user is permitted to send to specified port name
539  * @dest: destination address
540  * @m: descriptor for message to be sent
541  *
542  * Prevents restricted configuration commands from being issued by
543  * unauthorized users.
544  *
545  * Returns 0 if permission is granted, otherwise errno
546  */
547 static int dest_name_check(struct sockaddr_tipc *dest, struct msghdr *m)
548 {
549         struct tipc_cfg_msg_hdr hdr;
550
551         if (likely(dest->addr.name.name.type >= TIPC_RESERVED_TYPES))
552                 return 0;
553         if (likely(dest->addr.name.name.type == TIPC_TOP_SRV))
554                 return 0;
555         if (likely(dest->addr.name.name.type != TIPC_CFG_SRV))
556                 return -EACCES;
557
558         if (!m->msg_iovlen || (m->msg_iov[0].iov_len < sizeof(hdr)))
559                 return -EMSGSIZE;
560         if (copy_from_user(&hdr, m->msg_iov[0].iov_base, sizeof(hdr)))
561                 return -EFAULT;
562         if ((ntohs(hdr.tcm_type) & 0xC000) && (!capable(CAP_NET_ADMIN)))
563                 return -EACCES;
564
565         return 0;
566 }
567
568 static int tipc_wait_for_sndmsg(struct socket *sock, long *timeo_p)
569 {
570         struct sock *sk = sock->sk;
571         struct tipc_port *tport = tipc_sk_port(sk);
572         DEFINE_WAIT(wait);
573         int done;
574
575         do {
576                 int err = sock_error(sk);
577                 if (err)
578                         return err;
579                 if (sock->state == SS_DISCONNECTING)
580                         return -EPIPE;
581                 if (!*timeo_p)
582                         return -EAGAIN;
583                 if (signal_pending(current))
584                         return sock_intr_errno(*timeo_p);
585
586                 prepare_to_wait(sk_sleep(sk), &wait, TASK_INTERRUPTIBLE);
587                 done = sk_wait_event(sk, timeo_p, !tport->congested);
588                 finish_wait(sk_sleep(sk), &wait);
589         } while (!done);
590         return 0;
591 }
592
593 /**
594  * tipc_sendmsg - send message in connectionless manner
595  * @iocb: if NULL, indicates that socket lock is already held
596  * @sock: socket structure
597  * @m: message to send
598  * @total_len: length of message
599  *
600  * Message must have an destination specified explicitly.
601  * Used for SOCK_RDM and SOCK_DGRAM messages,
602  * and for 'SYN' messages on SOCK_SEQPACKET and SOCK_STREAM connections.
603  * (Note: 'SYN+' is prohibited on SOCK_STREAM.)
604  *
605  * Returns the number of bytes sent on success, or errno otherwise
606  */
607 static int tipc_sendmsg(struct kiocb *iocb, struct socket *sock,
608                         struct msghdr *m, size_t total_len)
609 {
610         struct sock *sk = sock->sk;
611         struct tipc_port *tport = tipc_sk_port(sk);
612         DECLARE_SOCKADDR(struct sockaddr_tipc *, dest, m->msg_name);
613         int needs_conn;
614         long timeo;
615         int res = -EINVAL;
616
617         if (unlikely(!dest))
618                 return -EDESTADDRREQ;
619         if (unlikely((m->msg_namelen < sizeof(*dest)) ||
620                      (dest->family != AF_TIPC)))
621                 return -EINVAL;
622         if (total_len > TIPC_MAX_USER_MSG_SIZE)
623                 return -EMSGSIZE;
624
625         if (iocb)
626                 lock_sock(sk);
627
628         needs_conn = (sock->state != SS_READY);
629         if (unlikely(needs_conn)) {
630                 if (sock->state == SS_LISTENING) {
631                         res = -EPIPE;
632                         goto exit;
633                 }
634                 if (sock->state != SS_UNCONNECTED) {
635                         res = -EISCONN;
636                         goto exit;
637                 }
638                 if (tport->published) {
639                         res = -EOPNOTSUPP;
640                         goto exit;
641                 }
642                 if (dest->addrtype == TIPC_ADDR_NAME) {
643                         tport->conn_type = dest->addr.name.name.type;
644                         tport->conn_instance = dest->addr.name.name.instance;
645                 }
646
647                 /* Abort any pending connection attempts (very unlikely) */
648                 reject_rx_queue(sk);
649         }
650
651         timeo = sock_sndtimeo(sk, m->msg_flags & MSG_DONTWAIT);
652         do {
653                 if (dest->addrtype == TIPC_ADDR_NAME) {
654                         res = dest_name_check(dest, m);
655                         if (res)
656                                 break;
657                         res = tipc_send2name(tport->ref,
658                                              &dest->addr.name.name,
659                                              dest->addr.name.domain,
660                                              m->msg_iov,
661                                              total_len);
662                 } else if (dest->addrtype == TIPC_ADDR_ID) {
663                         res = tipc_send2port(tport->ref,
664                                              &dest->addr.id,
665                                              m->msg_iov,
666                                              total_len);
667                 } else if (dest->addrtype == TIPC_ADDR_MCAST) {
668                         if (needs_conn) {
669                                 res = -EOPNOTSUPP;
670                                 break;
671                         }
672                         res = dest_name_check(dest, m);
673                         if (res)
674                                 break;
675                         res = tipc_port_mcast_xmit(tport->ref,
676                                                    &dest->addr.nameseq,
677                                                    m->msg_iov,
678                                                    total_len);
679                 }
680                 if (likely(res != -ELINKCONG)) {
681                         if (needs_conn && (res >= 0))
682                                 sock->state = SS_CONNECTING;
683                         break;
684                 }
685                 res = tipc_wait_for_sndmsg(sock, &timeo);
686                 if (res)
687                         break;
688         } while (1);
689
690 exit:
691         if (iocb)
692                 release_sock(sk);
693         return res;
694 }
695
696 static int tipc_wait_for_sndpkt(struct socket *sock, long *timeo_p)
697 {
698         struct sock *sk = sock->sk;
699         struct tipc_port *tport = tipc_sk_port(sk);
700         DEFINE_WAIT(wait);
701         int done;
702
703         do {
704                 int err = sock_error(sk);
705                 if (err)
706                         return err;
707                 if (sock->state == SS_DISCONNECTING)
708                         return -EPIPE;
709                 else if (sock->state != SS_CONNECTED)
710                         return -ENOTCONN;
711                 if (!*timeo_p)
712                         return -EAGAIN;
713                 if (signal_pending(current))
714                         return sock_intr_errno(*timeo_p);
715
716                 prepare_to_wait(sk_sleep(sk), &wait, TASK_INTERRUPTIBLE);
717                 done = sk_wait_event(sk, timeo_p,
718                                      (!tport->congested || !tport->connected));
719                 finish_wait(sk_sleep(sk), &wait);
720         } while (!done);
721         return 0;
722 }
723
724 /**
725  * tipc_send_packet - send a connection-oriented message
726  * @iocb: if NULL, indicates that socket lock is already held
727  * @sock: socket structure
728  * @m: message to send
729  * @total_len: length of message
730  *
731  * Used for SOCK_SEQPACKET messages and SOCK_STREAM data.
732  *
733  * Returns the number of bytes sent on success, or errno otherwise
734  */
735 static int tipc_send_packet(struct kiocb *iocb, struct socket *sock,
736                             struct msghdr *m, size_t total_len)
737 {
738         struct sock *sk = sock->sk;
739         struct tipc_port *tport = tipc_sk_port(sk);
740         DECLARE_SOCKADDR(struct sockaddr_tipc *, dest, m->msg_name);
741         int res = -EINVAL;
742         long timeo;
743
744         /* Handle implied connection establishment */
745         if (unlikely(dest))
746                 return tipc_sendmsg(iocb, sock, m, total_len);
747
748         if (total_len > TIPC_MAX_USER_MSG_SIZE)
749                 return -EMSGSIZE;
750
751         if (iocb)
752                 lock_sock(sk);
753
754         if (unlikely(sock->state != SS_CONNECTED)) {
755                 if (sock->state == SS_DISCONNECTING)
756                         res = -EPIPE;
757                 else
758                         res = -ENOTCONN;
759                 goto exit;
760         }
761
762         timeo = sock_sndtimeo(sk, m->msg_flags & MSG_DONTWAIT);
763         do {
764                 res = tipc_send(tport->ref, m->msg_iov, total_len);
765                 if (likely(res != -ELINKCONG))
766                         break;
767                 res = tipc_wait_for_sndpkt(sock, &timeo);
768                 if (res)
769                         break;
770         } while (1);
771 exit:
772         if (iocb)
773                 release_sock(sk);
774         return res;
775 }
776
777 /**
778  * tipc_send_stream - send stream-oriented data
779  * @iocb: (unused)
780  * @sock: socket structure
781  * @m: data to send
782  * @total_len: total length of data to be sent
783  *
784  * Used for SOCK_STREAM data.
785  *
786  * Returns the number of bytes sent on success (or partial success),
787  * or errno if no data sent
788  */
789 static int tipc_send_stream(struct kiocb *iocb, struct socket *sock,
790                             struct msghdr *m, size_t total_len)
791 {
792         struct sock *sk = sock->sk;
793         struct tipc_port *tport = tipc_sk_port(sk);
794         struct msghdr my_msg;
795         struct iovec my_iov;
796         struct iovec *curr_iov;
797         int curr_iovlen;
798         char __user *curr_start;
799         u32 hdr_size;
800         int curr_left;
801         int bytes_to_send;
802         int bytes_sent;
803         int res;
804
805         lock_sock(sk);
806
807         /* Handle special cases where there is no connection */
808         if (unlikely(sock->state != SS_CONNECTED)) {
809                 if (sock->state == SS_UNCONNECTED)
810                         res = tipc_send_packet(NULL, sock, m, total_len);
811                 else
812                         res = sock->state == SS_DISCONNECTING ? -EPIPE : -ENOTCONN;
813                 goto exit;
814         }
815
816         if (unlikely(m->msg_name)) {
817                 res = -EISCONN;
818                 goto exit;
819         }
820
821         if (total_len > (unsigned int)INT_MAX) {
822                 res = -EMSGSIZE;
823                 goto exit;
824         }
825
826         /*
827          * Send each iovec entry using one or more messages
828          *
829          * Note: This algorithm is good for the most likely case
830          * (i.e. one large iovec entry), but could be improved to pass sets
831          * of small iovec entries into send_packet().
832          */
833         curr_iov = m->msg_iov;
834         curr_iovlen = m->msg_iovlen;
835         my_msg.msg_iov = &my_iov;
836         my_msg.msg_iovlen = 1;
837         my_msg.msg_flags = m->msg_flags;
838         my_msg.msg_name = NULL;
839         bytes_sent = 0;
840
841         hdr_size = msg_hdr_sz(&tport->phdr);
842
843         while (curr_iovlen--) {
844                 curr_start = curr_iov->iov_base;
845                 curr_left = curr_iov->iov_len;
846
847                 while (curr_left) {
848                         bytes_to_send = tport->max_pkt - hdr_size;
849                         if (bytes_to_send > TIPC_MAX_USER_MSG_SIZE)
850                                 bytes_to_send = TIPC_MAX_USER_MSG_SIZE;
851                         if (curr_left < bytes_to_send)
852                                 bytes_to_send = curr_left;
853                         my_iov.iov_base = curr_start;
854                         my_iov.iov_len = bytes_to_send;
855                         res = tipc_send_packet(NULL, sock, &my_msg,
856                                                bytes_to_send);
857                         if (res < 0) {
858                                 if (bytes_sent)
859                                         res = bytes_sent;
860                                 goto exit;
861                         }
862                         curr_left -= bytes_to_send;
863                         curr_start += bytes_to_send;
864                         bytes_sent += bytes_to_send;
865                 }
866
867                 curr_iov++;
868         }
869         res = bytes_sent;
870 exit:
871         release_sock(sk);
872         return res;
873 }
874
875 /**
876  * auto_connect - complete connection setup to a remote port
877  * @sock: socket structure
878  * @msg: peer's response message
879  *
880  * Returns 0 on success, errno otherwise
881  */
882 static int auto_connect(struct socket *sock, struct tipc_msg *msg)
883 {
884         struct tipc_sock *tsock = tipc_sk(sock->sk);
885         struct tipc_port *p_ptr;
886
887         tsock->peer_name.ref = msg_origport(msg);
888         tsock->peer_name.node = msg_orignode(msg);
889         p_ptr = tipc_port_deref(tsock->p->ref);
890         if (!p_ptr)
891                 return -EINVAL;
892
893         __tipc_port_connect(tsock->p->ref, p_ptr, &tsock->peer_name);
894
895         if (msg_importance(msg) > TIPC_CRITICAL_IMPORTANCE)
896                 return -EINVAL;
897         msg_set_importance(&p_ptr->phdr, (u32)msg_importance(msg));
898         sock->state = SS_CONNECTED;
899         return 0;
900 }
901
902 /**
903  * set_orig_addr - capture sender's address for received message
904  * @m: descriptor for message info
905  * @msg: received message header
906  *
907  * Note: Address is not captured if not requested by receiver.
908  */
909 static void set_orig_addr(struct msghdr *m, struct tipc_msg *msg)
910 {
911         DECLARE_SOCKADDR(struct sockaddr_tipc *, addr, m->msg_name);
912
913         if (addr) {
914                 addr->family = AF_TIPC;
915                 addr->addrtype = TIPC_ADDR_ID;
916                 memset(&addr->addr, 0, sizeof(addr->addr));
917                 addr->addr.id.ref = msg_origport(msg);
918                 addr->addr.id.node = msg_orignode(msg);
919                 addr->addr.name.domain = 0;     /* could leave uninitialized */
920                 addr->scope = 0;                /* could leave uninitialized */
921                 m->msg_namelen = sizeof(struct sockaddr_tipc);
922         }
923 }
924
925 /**
926  * anc_data_recv - optionally capture ancillary data for received message
927  * @m: descriptor for message info
928  * @msg: received message header
929  * @tport: TIPC port associated with message
930  *
931  * Note: Ancillary data is not captured if not requested by receiver.
932  *
933  * Returns 0 if successful, otherwise errno
934  */
935 static int anc_data_recv(struct msghdr *m, struct tipc_msg *msg,
936                          struct tipc_port *tport)
937 {
938         u32 anc_data[3];
939         u32 err;
940         u32 dest_type;
941         int has_name;
942         int res;
943
944         if (likely(m->msg_controllen == 0))
945                 return 0;
946
947         /* Optionally capture errored message object(s) */
948         err = msg ? msg_errcode(msg) : 0;
949         if (unlikely(err)) {
950                 anc_data[0] = err;
951                 anc_data[1] = msg_data_sz(msg);
952                 res = put_cmsg(m, SOL_TIPC, TIPC_ERRINFO, 8, anc_data);
953                 if (res)
954                         return res;
955                 if (anc_data[1]) {
956                         res = put_cmsg(m, SOL_TIPC, TIPC_RETDATA, anc_data[1],
957                                        msg_data(msg));
958                         if (res)
959                                 return res;
960                 }
961         }
962
963         /* Optionally capture message destination object */
964         dest_type = msg ? msg_type(msg) : TIPC_DIRECT_MSG;
965         switch (dest_type) {
966         case TIPC_NAMED_MSG:
967                 has_name = 1;
968                 anc_data[0] = msg_nametype(msg);
969                 anc_data[1] = msg_namelower(msg);
970                 anc_data[2] = msg_namelower(msg);
971                 break;
972         case TIPC_MCAST_MSG:
973                 has_name = 1;
974                 anc_data[0] = msg_nametype(msg);
975                 anc_data[1] = msg_namelower(msg);
976                 anc_data[2] = msg_nameupper(msg);
977                 break;
978         case TIPC_CONN_MSG:
979                 has_name = (tport->conn_type != 0);
980                 anc_data[0] = tport->conn_type;
981                 anc_data[1] = tport->conn_instance;
982                 anc_data[2] = tport->conn_instance;
983                 break;
984         default:
985                 has_name = 0;
986         }
987         if (has_name) {
988                 res = put_cmsg(m, SOL_TIPC, TIPC_DESTNAME, 12, anc_data);
989                 if (res)
990                         return res;
991         }
992
993         return 0;
994 }
995
996 static int tipc_wait_for_rcvmsg(struct socket *sock, long timeo)
997 {
998         struct sock *sk = sock->sk;
999         DEFINE_WAIT(wait);
1000         int err;
1001
1002         for (;;) {
1003                 prepare_to_wait(sk_sleep(sk), &wait, TASK_INTERRUPTIBLE);
1004                 if (skb_queue_empty(&sk->sk_receive_queue)) {
1005                         if (sock->state == SS_DISCONNECTING) {
1006                                 err = -ENOTCONN;
1007                                 break;
1008                         }
1009                         release_sock(sk);
1010                         timeo = schedule_timeout(timeo);
1011                         lock_sock(sk);
1012                 }
1013                 err = 0;
1014                 if (!skb_queue_empty(&sk->sk_receive_queue))
1015                         break;
1016                 err = sock_intr_errno(timeo);
1017                 if (signal_pending(current))
1018                         break;
1019                 err = -EAGAIN;
1020                 if (!timeo)
1021                         break;
1022         }
1023         finish_wait(sk_sleep(sk), &wait);
1024         return err;
1025 }
1026
1027 /**
1028  * tipc_recvmsg - receive packet-oriented message
1029  * @iocb: (unused)
1030  * @m: descriptor for message info
1031  * @buf_len: total size of user buffer area
1032  * @flags: receive flags
1033  *
1034  * Used for SOCK_DGRAM, SOCK_RDM, and SOCK_SEQPACKET messages.
1035  * If the complete message doesn't fit in user area, truncate it.
1036  *
1037  * Returns size of returned message data, errno otherwise
1038  */
1039 static int tipc_recvmsg(struct kiocb *iocb, struct socket *sock,
1040                         struct msghdr *m, size_t buf_len, int flags)
1041 {
1042         struct sock *sk = sock->sk;
1043         struct tipc_port *tport = tipc_sk_port(sk);
1044         struct sk_buff *buf;
1045         struct tipc_msg *msg;
1046         long timeo;
1047         unsigned int sz;
1048         u32 err;
1049         int res;
1050
1051         /* Catch invalid receive requests */
1052         if (unlikely(!buf_len))
1053                 return -EINVAL;
1054
1055         lock_sock(sk);
1056
1057         if (unlikely(sock->state == SS_UNCONNECTED)) {
1058                 res = -ENOTCONN;
1059                 goto exit;
1060         }
1061
1062         timeo = sock_rcvtimeo(sk, flags & MSG_DONTWAIT);
1063 restart:
1064
1065         /* Look for a message in receive queue; wait if necessary */
1066         res = tipc_wait_for_rcvmsg(sock, timeo);
1067         if (res)
1068                 goto exit;
1069
1070         /* Look at first message in receive queue */
1071         buf = skb_peek(&sk->sk_receive_queue);
1072         msg = buf_msg(buf);
1073         sz = msg_data_sz(msg);
1074         err = msg_errcode(msg);
1075
1076         /* Discard an empty non-errored message & try again */
1077         if ((!sz) && (!err)) {
1078                 advance_rx_queue(sk);
1079                 goto restart;
1080         }
1081
1082         /* Capture sender's address (optional) */
1083         set_orig_addr(m, msg);
1084
1085         /* Capture ancillary data (optional) */
1086         res = anc_data_recv(m, msg, tport);
1087         if (res)
1088                 goto exit;
1089
1090         /* Capture message data (if valid) & compute return value (always) */
1091         if (!err) {
1092                 if (unlikely(buf_len < sz)) {
1093                         sz = buf_len;
1094                         m->msg_flags |= MSG_TRUNC;
1095                 }
1096                 res = skb_copy_datagram_iovec(buf, msg_hdr_sz(msg),
1097                                               m->msg_iov, sz);
1098                 if (res)
1099                         goto exit;
1100                 res = sz;
1101         } else {
1102                 if ((sock->state == SS_READY) ||
1103                     ((err == TIPC_CONN_SHUTDOWN) || m->msg_control))
1104                         res = 0;
1105                 else
1106                         res = -ECONNRESET;
1107         }
1108
1109         /* Consume received message (optional) */
1110         if (likely(!(flags & MSG_PEEK))) {
1111                 if ((sock->state != SS_READY) &&
1112                     (++tport->conn_unacked >= TIPC_FLOW_CONTROL_WIN))
1113                         tipc_acknowledge(tport->ref, tport->conn_unacked);
1114                 advance_rx_queue(sk);
1115         }
1116 exit:
1117         release_sock(sk);
1118         return res;
1119 }
1120
1121 /**
1122  * tipc_recv_stream - receive stream-oriented data
1123  * @iocb: (unused)
1124  * @m: descriptor for message info
1125  * @buf_len: total size of user buffer area
1126  * @flags: receive flags
1127  *
1128  * Used for SOCK_STREAM messages only.  If not enough data is available
1129  * will optionally wait for more; never truncates data.
1130  *
1131  * Returns size of returned message data, errno otherwise
1132  */
1133 static int tipc_recv_stream(struct kiocb *iocb, struct socket *sock,
1134                             struct msghdr *m, size_t buf_len, int flags)
1135 {
1136         struct sock *sk = sock->sk;
1137         struct tipc_port *tport = tipc_sk_port(sk);
1138         struct sk_buff *buf;
1139         struct tipc_msg *msg;
1140         long timeo;
1141         unsigned int sz;
1142         int sz_to_copy, target, needed;
1143         int sz_copied = 0;
1144         u32 err;
1145         int res = 0;
1146
1147         /* Catch invalid receive attempts */
1148         if (unlikely(!buf_len))
1149                 return -EINVAL;
1150
1151         lock_sock(sk);
1152
1153         if (unlikely(sock->state == SS_UNCONNECTED)) {
1154                 res = -ENOTCONN;
1155                 goto exit;
1156         }
1157
1158         target = sock_rcvlowat(sk, flags & MSG_WAITALL, buf_len);
1159         timeo = sock_rcvtimeo(sk, flags & MSG_DONTWAIT);
1160
1161 restart:
1162         /* Look for a message in receive queue; wait if necessary */
1163         res = tipc_wait_for_rcvmsg(sock, timeo);
1164         if (res)
1165                 goto exit;
1166
1167         /* Look at first message in receive queue */
1168         buf = skb_peek(&sk->sk_receive_queue);
1169         msg = buf_msg(buf);
1170         sz = msg_data_sz(msg);
1171         err = msg_errcode(msg);
1172
1173         /* Discard an empty non-errored message & try again */
1174         if ((!sz) && (!err)) {
1175                 advance_rx_queue(sk);
1176                 goto restart;
1177         }
1178
1179         /* Optionally capture sender's address & ancillary data of first msg */
1180         if (sz_copied == 0) {
1181                 set_orig_addr(m, msg);
1182                 res = anc_data_recv(m, msg, tport);
1183                 if (res)
1184                         goto exit;
1185         }
1186
1187         /* Capture message data (if valid) & compute return value (always) */
1188         if (!err) {
1189                 u32 offset = (u32)(unsigned long)(TIPC_SKB_CB(buf)->handle);
1190
1191                 sz -= offset;
1192                 needed = (buf_len - sz_copied);
1193                 sz_to_copy = (sz <= needed) ? sz : needed;
1194
1195                 res = skb_copy_datagram_iovec(buf, msg_hdr_sz(msg) + offset,
1196                                               m->msg_iov, sz_to_copy);
1197                 if (res)
1198                         goto exit;
1199
1200                 sz_copied += sz_to_copy;
1201
1202                 if (sz_to_copy < sz) {
1203                         if (!(flags & MSG_PEEK))
1204                                 TIPC_SKB_CB(buf)->handle =
1205                                 (void *)(unsigned long)(offset + sz_to_copy);
1206                         goto exit;
1207                 }
1208         } else {
1209                 if (sz_copied != 0)
1210                         goto exit; /* can't add error msg to valid data */
1211
1212                 if ((err == TIPC_CONN_SHUTDOWN) || m->msg_control)
1213                         res = 0;
1214                 else
1215                         res = -ECONNRESET;
1216         }
1217
1218         /* Consume received message (optional) */
1219         if (likely(!(flags & MSG_PEEK))) {
1220                 if (unlikely(++tport->conn_unacked >= TIPC_FLOW_CONTROL_WIN))
1221                         tipc_acknowledge(tport->ref, tport->conn_unacked);
1222                 advance_rx_queue(sk);
1223         }
1224
1225         /* Loop around if more data is required */
1226         if ((sz_copied < buf_len) &&    /* didn't get all requested data */
1227             (!skb_queue_empty(&sk->sk_receive_queue) ||
1228             (sz_copied < target)) &&    /* and more is ready or required */
1229             (!(flags & MSG_PEEK)) &&    /* and aren't just peeking at data */
1230             (!err))                     /* and haven't reached a FIN */
1231                 goto restart;
1232
1233 exit:
1234         release_sock(sk);
1235         return sz_copied ? sz_copied : res;
1236 }
1237
1238 /**
1239  * tipc_write_space - wake up thread if port congestion is released
1240  * @sk: socket
1241  */
1242 static void tipc_write_space(struct sock *sk)
1243 {
1244         struct socket_wq *wq;
1245
1246         rcu_read_lock();
1247         wq = rcu_dereference(sk->sk_wq);
1248         if (wq_has_sleeper(wq))
1249                 wake_up_interruptible_sync_poll(&wq->wait, POLLOUT |
1250                                                 POLLWRNORM | POLLWRBAND);
1251         rcu_read_unlock();
1252 }
1253
1254 /**
1255  * tipc_data_ready - wake up threads to indicate messages have been received
1256  * @sk: socket
1257  * @len: the length of messages
1258  */
1259 static void tipc_data_ready(struct sock *sk, int len)
1260 {
1261         struct socket_wq *wq;
1262
1263         rcu_read_lock();
1264         wq = rcu_dereference(sk->sk_wq);
1265         if (wq_has_sleeper(wq))
1266                 wake_up_interruptible_sync_poll(&wq->wait, POLLIN |
1267                                                 POLLRDNORM | POLLRDBAND);
1268         rcu_read_unlock();
1269 }
1270
1271 /**
1272  * filter_connect - Handle all incoming messages for a connection-based socket
1273  * @tsock: TIPC socket
1274  * @msg: message
1275  *
1276  * Returns TIPC error status code and socket error status code
1277  * once it encounters some errors
1278  */
1279 static u32 filter_connect(struct tipc_sock *tsock, struct sk_buff **buf)
1280 {
1281         struct socket *sock = tsock->sk.sk_socket;
1282         struct tipc_msg *msg = buf_msg(*buf);
1283         struct sock *sk = &tsock->sk;
1284         u32 retval = TIPC_ERR_NO_PORT;
1285         int res;
1286
1287         if (msg_mcast(msg))
1288                 return retval;
1289
1290         switch ((int)sock->state) {
1291         case SS_CONNECTED:
1292                 /* Accept only connection-based messages sent by peer */
1293                 if (msg_connected(msg) && tipc_port_peer_msg(tsock->p, msg)) {
1294                         if (unlikely(msg_errcode(msg))) {
1295                                 sock->state = SS_DISCONNECTING;
1296                                 __tipc_port_disconnect(tsock->p);
1297                         }
1298                         retval = TIPC_OK;
1299                 }
1300                 break;
1301         case SS_CONNECTING:
1302                 /* Accept only ACK or NACK message */
1303                 if (unlikely(msg_errcode(msg))) {
1304                         sock->state = SS_DISCONNECTING;
1305                         sk->sk_err = ECONNREFUSED;
1306                         retval = TIPC_OK;
1307                         break;
1308                 }
1309
1310                 if (unlikely(!msg_connected(msg)))
1311                         break;
1312
1313                 res = auto_connect(sock, msg);
1314                 if (res) {
1315                         sock->state = SS_DISCONNECTING;
1316                         sk->sk_err = -res;
1317                         retval = TIPC_OK;
1318                         break;
1319                 }
1320
1321                 /* If an incoming message is an 'ACK-', it should be
1322                  * discarded here because it doesn't contain useful
1323                  * data. In addition, we should try to wake up
1324                  * connect() routine if sleeping.
1325                  */
1326                 if (msg_data_sz(msg) == 0) {
1327                         kfree_skb(*buf);
1328                         *buf = NULL;
1329                         if (waitqueue_active(sk_sleep(sk)))
1330                                 wake_up_interruptible(sk_sleep(sk));
1331                 }
1332                 retval = TIPC_OK;
1333                 break;
1334         case SS_LISTENING:
1335         case SS_UNCONNECTED:
1336                 /* Accept only SYN message */
1337                 if (!msg_connected(msg) && !(msg_errcode(msg)))
1338                         retval = TIPC_OK;
1339                 break;
1340         case SS_DISCONNECTING:
1341                 break;
1342         default:
1343                 pr_err("Unknown socket state %u\n", sock->state);
1344         }
1345         return retval;
1346 }
1347
1348 /**
1349  * rcvbuf_limit - get proper overload limit of socket receive queue
1350  * @sk: socket
1351  * @buf: message
1352  *
1353  * For all connection oriented messages, irrespective of importance,
1354  * the default overload value (i.e. 67MB) is set as limit.
1355  *
1356  * For all connectionless messages, by default new queue limits are
1357  * as belows:
1358  *
1359  * TIPC_LOW_IMPORTANCE       (4 MB)
1360  * TIPC_MEDIUM_IMPORTANCE    (8 MB)
1361  * TIPC_HIGH_IMPORTANCE      (16 MB)
1362  * TIPC_CRITICAL_IMPORTANCE  (32 MB)
1363  *
1364  * Returns overload limit according to corresponding message importance
1365  */
1366 static unsigned int rcvbuf_limit(struct sock *sk, struct sk_buff *buf)
1367 {
1368         struct tipc_msg *msg = buf_msg(buf);
1369
1370         if (msg_connected(msg))
1371                 return sysctl_tipc_rmem[2];
1372
1373         return sk->sk_rcvbuf >> TIPC_CRITICAL_IMPORTANCE <<
1374                 msg_importance(msg);
1375 }
1376
1377 /**
1378  * filter_rcv - validate incoming message
1379  * @sk: socket
1380  * @buf: message
1381  *
1382  * Enqueues message on receive queue if acceptable; optionally handles
1383  * disconnect indication for a connected socket.
1384  *
1385  * Called with socket lock already taken; port lock may also be taken.
1386  *
1387  * Returns TIPC error status code (TIPC_OK if message is not to be rejected)
1388  */
1389 static u32 filter_rcv(struct sock *sk, struct sk_buff *buf)
1390 {
1391         struct socket *sock = sk->sk_socket;
1392         struct tipc_msg *msg = buf_msg(buf);
1393         unsigned int limit = rcvbuf_limit(sk, buf);
1394         u32 res = TIPC_OK;
1395
1396         /* Reject message if it is wrong sort of message for socket */
1397         if (msg_type(msg) > TIPC_DIRECT_MSG)
1398                 return TIPC_ERR_NO_PORT;
1399
1400         if (sock->state == SS_READY) {
1401                 if (msg_connected(msg))
1402                         return TIPC_ERR_NO_PORT;
1403         } else {
1404                 res = filter_connect(tipc_sk(sk), &buf);
1405                 if (res != TIPC_OK || buf == NULL)
1406                         return res;
1407         }
1408
1409         /* Reject message if there isn't room to queue it */
1410         if (sk_rmem_alloc_get(sk) + buf->truesize >= limit)
1411                 return TIPC_ERR_OVERLOAD;
1412
1413         /* Enqueue message */
1414         TIPC_SKB_CB(buf)->handle = NULL;
1415         __skb_queue_tail(&sk->sk_receive_queue, buf);
1416         skb_set_owner_r(buf, sk);
1417
1418         sk->sk_data_ready(sk, 0);
1419         return TIPC_OK;
1420 }
1421
1422 /**
1423  * backlog_rcv - handle incoming message from backlog queue
1424  * @sk: socket
1425  * @buf: message
1426  *
1427  * Caller must hold socket lock, but not port lock.
1428  *
1429  * Returns 0
1430  */
1431 static int backlog_rcv(struct sock *sk, struct sk_buff *buf)
1432 {
1433         u32 res;
1434
1435         res = filter_rcv(sk, buf);
1436         if (res)
1437                 tipc_reject_msg(buf, res);
1438         return 0;
1439 }
1440
1441 /**
1442  * dispatch - handle incoming message
1443  * @tport: TIPC port that received message
1444  * @buf: message
1445  *
1446  * Called with port lock already taken.
1447  *
1448  * Returns TIPC error status code (TIPC_OK if message is not to be rejected)
1449  */
1450 static u32 dispatch(struct tipc_port *tport, struct sk_buff *buf)
1451 {
1452         struct sock *sk = tport->sk;
1453         u32 res;
1454
1455         /*
1456          * Process message if socket is unlocked; otherwise add to backlog queue
1457          *
1458          * This code is based on sk_receive_skb(), but must be distinct from it
1459          * since a TIPC-specific filter/reject mechanism is utilized
1460          */
1461         bh_lock_sock(sk);
1462         if (!sock_owned_by_user(sk)) {
1463                 res = filter_rcv(sk, buf);
1464         } else {
1465                 if (sk_add_backlog(sk, buf, rcvbuf_limit(sk, buf)))
1466                         res = TIPC_ERR_OVERLOAD;
1467                 else
1468                         res = TIPC_OK;
1469         }
1470         bh_unlock_sock(sk);
1471
1472         return res;
1473 }
1474
1475 /**
1476  * wakeupdispatch - wake up port after congestion
1477  * @tport: port to wakeup
1478  *
1479  * Called with port lock already taken.
1480  */
1481 static void wakeupdispatch(struct tipc_port *tport)
1482 {
1483         struct sock *sk = tport->sk;
1484
1485         sk->sk_write_space(sk);
1486 }
1487
1488 static int tipc_wait_for_connect(struct socket *sock, long *timeo_p)
1489 {
1490         struct sock *sk = sock->sk;
1491         DEFINE_WAIT(wait);
1492         int done;
1493
1494         do {
1495                 int err = sock_error(sk);
1496                 if (err)
1497                         return err;
1498                 if (!*timeo_p)
1499                         return -ETIMEDOUT;
1500                 if (signal_pending(current))
1501                         return sock_intr_errno(*timeo_p);
1502
1503                 prepare_to_wait(sk_sleep(sk), &wait, TASK_INTERRUPTIBLE);
1504                 done = sk_wait_event(sk, timeo_p, sock->state != SS_CONNECTING);
1505                 finish_wait(sk_sleep(sk), &wait);
1506         } while (!done);
1507         return 0;
1508 }
1509
1510 /**
1511  * tipc_connect - establish a connection to another TIPC port
1512  * @sock: socket structure
1513  * @dest: socket address for destination port
1514  * @destlen: size of socket address data structure
1515  * @flags: file-related flags associated with socket
1516  *
1517  * Returns 0 on success, errno otherwise
1518  */
1519 static int tipc_connect(struct socket *sock, struct sockaddr *dest,
1520                         int destlen, int flags)
1521 {
1522         struct sock *sk = sock->sk;
1523         struct sockaddr_tipc *dst = (struct sockaddr_tipc *)dest;
1524         struct msghdr m = {NULL,};
1525         long timeout = (flags & O_NONBLOCK) ? 0 : tipc_sk(sk)->conn_timeout;
1526         socket_state previous;
1527         int res;
1528
1529         lock_sock(sk);
1530
1531         /* For now, TIPC does not allow use of connect() with DGRAM/RDM types */
1532         if (sock->state == SS_READY) {
1533                 res = -EOPNOTSUPP;
1534                 goto exit;
1535         }
1536
1537         /*
1538          * Reject connection attempt using multicast address
1539          *
1540          * Note: send_msg() validates the rest of the address fields,
1541          *       so there's no need to do it here
1542          */
1543         if (dst->addrtype == TIPC_ADDR_MCAST) {
1544                 res = -EINVAL;
1545                 goto exit;
1546         }
1547
1548         previous = sock->state;
1549         switch (sock->state) {
1550         case SS_UNCONNECTED:
1551                 /* Send a 'SYN-' to destination */
1552                 m.msg_name = dest;
1553                 m.msg_namelen = destlen;
1554
1555                 /* If connect is in non-blocking case, set MSG_DONTWAIT to
1556                  * indicate send_msg() is never blocked.
1557                  */
1558                 if (!timeout)
1559                         m.msg_flags = MSG_DONTWAIT;
1560
1561                 res = tipc_sendmsg(NULL, sock, &m, 0);
1562                 if ((res < 0) && (res != -EWOULDBLOCK))
1563                         goto exit;
1564
1565                 /* Just entered SS_CONNECTING state; the only
1566                  * difference is that return value in non-blocking
1567                  * case is EINPROGRESS, rather than EALREADY.
1568                  */
1569                 res = -EINPROGRESS;
1570         case SS_CONNECTING:
1571                 if (previous == SS_CONNECTING)
1572                         res = -EALREADY;
1573                 if (!timeout)
1574                         goto exit;
1575                 timeout = msecs_to_jiffies(timeout);
1576                 /* Wait until an 'ACK' or 'RST' arrives, or a timeout occurs */
1577                 res = tipc_wait_for_connect(sock, &timeout);
1578                 break;
1579         case SS_CONNECTED:
1580                 res = -EISCONN;
1581                 break;
1582         default:
1583                 res = -EINVAL;
1584                 break;
1585         }
1586 exit:
1587         release_sock(sk);
1588         return res;
1589 }
1590
1591 /**
1592  * tipc_listen - allow socket to listen for incoming connections
1593  * @sock: socket structure
1594  * @len: (unused)
1595  *
1596  * Returns 0 on success, errno otherwise
1597  */
1598 static int tipc_listen(struct socket *sock, int len)
1599 {
1600         struct sock *sk = sock->sk;
1601         int res;
1602
1603         lock_sock(sk);
1604
1605         if (sock->state != SS_UNCONNECTED)
1606                 res = -EINVAL;
1607         else {
1608                 sock->state = SS_LISTENING;
1609                 res = 0;
1610         }
1611
1612         release_sock(sk);
1613         return res;
1614 }
1615
1616 static int tipc_wait_for_accept(struct socket *sock, long timeo)
1617 {
1618         struct sock *sk = sock->sk;
1619         DEFINE_WAIT(wait);
1620         int err;
1621
1622         /* True wake-one mechanism for incoming connections: only
1623          * one process gets woken up, not the 'whole herd'.
1624          * Since we do not 'race & poll' for established sockets
1625          * anymore, the common case will execute the loop only once.
1626         */
1627         for (;;) {
1628                 prepare_to_wait_exclusive(sk_sleep(sk), &wait,
1629                                           TASK_INTERRUPTIBLE);
1630                 if (skb_queue_empty(&sk->sk_receive_queue)) {
1631                         release_sock(sk);
1632                         timeo = schedule_timeout(timeo);
1633                         lock_sock(sk);
1634                 }
1635                 err = 0;
1636                 if (!skb_queue_empty(&sk->sk_receive_queue))
1637                         break;
1638                 err = -EINVAL;
1639                 if (sock->state != SS_LISTENING)
1640                         break;
1641                 err = sock_intr_errno(timeo);
1642                 if (signal_pending(current))
1643                         break;
1644                 err = -EAGAIN;
1645                 if (!timeo)
1646                         break;
1647         }
1648         finish_wait(sk_sleep(sk), &wait);
1649         return err;
1650 }
1651
1652 /**
1653  * tipc_accept - wait for connection request
1654  * @sock: listening socket
1655  * @newsock: new socket that is to be connected
1656  * @flags: file-related flags associated with socket
1657  *
1658  * Returns 0 on success, errno otherwise
1659  */
1660 static int tipc_accept(struct socket *sock, struct socket *new_sock, int flags)
1661 {
1662         struct sock *new_sk, *sk = sock->sk;
1663         struct sk_buff *buf;
1664         struct tipc_sock *new_tsock;
1665         struct tipc_port *new_tport;
1666         struct tipc_msg *msg;
1667         u32 new_ref;
1668         long timeo;
1669         int res;
1670
1671         lock_sock(sk);
1672
1673         if (sock->state != SS_LISTENING) {
1674                 res = -EINVAL;
1675                 goto exit;
1676         }
1677
1678         timeo = sock_rcvtimeo(sk, flags & O_NONBLOCK);
1679         res = tipc_wait_for_accept(sock, timeo);
1680         if (res)
1681                 goto exit;
1682
1683         buf = skb_peek(&sk->sk_receive_queue);
1684
1685         res = tipc_sk_create(sock_net(sock->sk), new_sock, 0, 1);
1686         if (res)
1687                 goto exit;
1688
1689         new_sk = new_sock->sk;
1690         new_tsock = tipc_sk(new_sk);
1691         new_tport = new_tsock->p;
1692         new_ref = new_tport->ref;
1693         msg = buf_msg(buf);
1694
1695         /* we lock on new_sk; but lockdep sees the lock on sk */
1696         lock_sock_nested(new_sk, SINGLE_DEPTH_NESTING);
1697
1698         /*
1699          * Reject any stray messages received by new socket
1700          * before the socket lock was taken (very, very unlikely)
1701          */
1702         reject_rx_queue(new_sk);
1703
1704         /* Connect new socket to it's peer */
1705         new_tsock->peer_name.ref = msg_origport(msg);
1706         new_tsock->peer_name.node = msg_orignode(msg);
1707         tipc_port_connect(new_ref, &new_tsock->peer_name);
1708         new_sock->state = SS_CONNECTED;
1709
1710         tipc_set_portimportance(new_ref, msg_importance(msg));
1711         if (msg_named(msg)) {
1712                 new_tport->conn_type = msg_nametype(msg);
1713                 new_tport->conn_instance = msg_nameinst(msg);
1714         }
1715
1716         /*
1717          * Respond to 'SYN-' by discarding it & returning 'ACK'-.
1718          * Respond to 'SYN+' by queuing it on new socket.
1719          */
1720         if (!msg_data_sz(msg)) {
1721                 struct msghdr m = {NULL,};
1722
1723                 advance_rx_queue(sk);
1724                 tipc_send_packet(NULL, new_sock, &m, 0);
1725         } else {
1726                 __skb_dequeue(&sk->sk_receive_queue);
1727                 __skb_queue_head(&new_sk->sk_receive_queue, buf);
1728                 skb_set_owner_r(buf, new_sk);
1729         }
1730         release_sock(new_sk);
1731
1732 exit:
1733         release_sock(sk);
1734         return res;
1735 }
1736
1737 /**
1738  * tipc_shutdown - shutdown socket connection
1739  * @sock: socket structure
1740  * @how: direction to close (must be SHUT_RDWR)
1741  *
1742  * Terminates connection (if necessary), then purges socket's receive queue.
1743  *
1744  * Returns 0 on success, errno otherwise
1745  */
1746 static int tipc_shutdown(struct socket *sock, int how)
1747 {
1748         struct sock *sk = sock->sk;
1749         struct tipc_port *tport = tipc_sk_port(sk);
1750         struct sk_buff *buf;
1751         int res;
1752
1753         if (how != SHUT_RDWR)
1754                 return -EINVAL;
1755
1756         lock_sock(sk);
1757
1758         switch (sock->state) {
1759         case SS_CONNECTING:
1760         case SS_CONNECTED:
1761
1762 restart:
1763                 /* Disconnect and send a 'FIN+' or 'FIN-' message to peer */
1764                 buf = __skb_dequeue(&sk->sk_receive_queue);
1765                 if (buf) {
1766                         if (TIPC_SKB_CB(buf)->handle != NULL) {
1767                                 kfree_skb(buf);
1768                                 goto restart;
1769                         }
1770                         tipc_port_disconnect(tport->ref);
1771                         tipc_reject_msg(buf, TIPC_CONN_SHUTDOWN);
1772                 } else {
1773                         tipc_port_shutdown(tport->ref);
1774                 }
1775
1776                 sock->state = SS_DISCONNECTING;
1777
1778                 /* fall through */
1779
1780         case SS_DISCONNECTING:
1781
1782                 /* Discard any unreceived messages */
1783                 __skb_queue_purge(&sk->sk_receive_queue);
1784
1785                 /* Wake up anyone sleeping in poll */
1786                 sk->sk_state_change(sk);
1787                 res = 0;
1788                 break;
1789
1790         default:
1791                 res = -ENOTCONN;
1792         }
1793
1794         release_sock(sk);
1795         return res;
1796 }
1797
1798 /**
1799  * tipc_setsockopt - set socket option
1800  * @sock: socket structure
1801  * @lvl: option level
1802  * @opt: option identifier
1803  * @ov: pointer to new option value
1804  * @ol: length of option value
1805  *
1806  * For stream sockets only, accepts and ignores all IPPROTO_TCP options
1807  * (to ease compatibility).
1808  *
1809  * Returns 0 on success, errno otherwise
1810  */
1811 static int tipc_setsockopt(struct socket *sock, int lvl, int opt,
1812                            char __user *ov, unsigned int ol)
1813 {
1814         struct sock *sk = sock->sk;
1815         struct tipc_port *tport = tipc_sk_port(sk);
1816         u32 value;
1817         int res;
1818
1819         if ((lvl == IPPROTO_TCP) && (sock->type == SOCK_STREAM))
1820                 return 0;
1821         if (lvl != SOL_TIPC)
1822                 return -ENOPROTOOPT;
1823         if (ol < sizeof(value))
1824                 return -EINVAL;
1825         res = get_user(value, (u32 __user *)ov);
1826         if (res)
1827                 return res;
1828
1829         lock_sock(sk);
1830
1831         switch (opt) {
1832         case TIPC_IMPORTANCE:
1833                 res = tipc_set_portimportance(tport->ref, value);
1834                 break;
1835         case TIPC_SRC_DROPPABLE:
1836                 if (sock->type != SOCK_STREAM)
1837                         res = tipc_set_portunreliable(tport->ref, value);
1838                 else
1839                         res = -ENOPROTOOPT;
1840                 break;
1841         case TIPC_DEST_DROPPABLE:
1842                 res = tipc_set_portunreturnable(tport->ref, value);
1843                 break;
1844         case TIPC_CONN_TIMEOUT:
1845                 tipc_sk(sk)->conn_timeout = value;
1846                 /* no need to set "res", since already 0 at this point */
1847                 break;
1848         default:
1849                 res = -EINVAL;
1850         }
1851
1852         release_sock(sk);
1853
1854         return res;
1855 }
1856
1857 /**
1858  * tipc_getsockopt - get socket option
1859  * @sock: socket structure
1860  * @lvl: option level
1861  * @opt: option identifier
1862  * @ov: receptacle for option value
1863  * @ol: receptacle for length of option value
1864  *
1865  * For stream sockets only, returns 0 length result for all IPPROTO_TCP options
1866  * (to ease compatibility).
1867  *
1868  * Returns 0 on success, errno otherwise
1869  */
1870 static int tipc_getsockopt(struct socket *sock, int lvl, int opt,
1871                            char __user *ov, int __user *ol)
1872 {
1873         struct sock *sk = sock->sk;
1874         struct tipc_port *tport = tipc_sk_port(sk);
1875         int len;
1876         u32 value;
1877         int res;
1878
1879         if ((lvl == IPPROTO_TCP) && (sock->type == SOCK_STREAM))
1880                 return put_user(0, ol);
1881         if (lvl != SOL_TIPC)
1882                 return -ENOPROTOOPT;
1883         res = get_user(len, ol);
1884         if (res)
1885                 return res;
1886
1887         lock_sock(sk);
1888
1889         switch (opt) {
1890         case TIPC_IMPORTANCE:
1891                 res = tipc_portimportance(tport->ref, &value);
1892                 break;
1893         case TIPC_SRC_DROPPABLE:
1894                 res = tipc_portunreliable(tport->ref, &value);
1895                 break;
1896         case TIPC_DEST_DROPPABLE:
1897                 res = tipc_portunreturnable(tport->ref, &value);
1898                 break;
1899         case TIPC_CONN_TIMEOUT:
1900                 value = tipc_sk(sk)->conn_timeout;
1901                 /* no need to set "res", since already 0 at this point */
1902                 break;
1903         case TIPC_NODE_RECVQ_DEPTH:
1904                 value = 0; /* was tipc_queue_size, now obsolete */
1905                 break;
1906         case TIPC_SOCK_RECVQ_DEPTH:
1907                 value = skb_queue_len(&sk->sk_receive_queue);
1908                 break;
1909         default:
1910                 res = -EINVAL;
1911         }
1912
1913         release_sock(sk);
1914
1915         if (res)
1916                 return res;     /* "get" failed */
1917
1918         if (len < sizeof(value))
1919                 return -EINVAL;
1920
1921         if (copy_to_user(ov, &value, sizeof(value)))
1922                 return -EFAULT;
1923
1924         return put_user(sizeof(value), ol);
1925 }
1926
1927 /* Protocol switches for the various types of TIPC sockets */
1928
1929 static const struct proto_ops msg_ops = {
1930         .owner          = THIS_MODULE,
1931         .family         = AF_TIPC,
1932         .release        = tipc_release,
1933         .bind           = tipc_bind,
1934         .connect        = tipc_connect,
1935         .socketpair     = sock_no_socketpair,
1936         .accept         = sock_no_accept,
1937         .getname        = tipc_getname,
1938         .poll           = tipc_poll,
1939         .ioctl          = sock_no_ioctl,
1940         .listen         = sock_no_listen,
1941         .shutdown       = tipc_shutdown,
1942         .setsockopt     = tipc_setsockopt,
1943         .getsockopt     = tipc_getsockopt,
1944         .sendmsg        = tipc_sendmsg,
1945         .recvmsg        = tipc_recvmsg,
1946         .mmap           = sock_no_mmap,
1947         .sendpage       = sock_no_sendpage
1948 };
1949
1950 static const struct proto_ops packet_ops = {
1951         .owner          = THIS_MODULE,
1952         .family         = AF_TIPC,
1953         .release        = tipc_release,
1954         .bind           = tipc_bind,
1955         .connect        = tipc_connect,
1956         .socketpair     = sock_no_socketpair,
1957         .accept         = tipc_accept,
1958         .getname        = tipc_getname,
1959         .poll           = tipc_poll,
1960         .ioctl          = sock_no_ioctl,
1961         .listen         = tipc_listen,
1962         .shutdown       = tipc_shutdown,
1963         .setsockopt     = tipc_setsockopt,
1964         .getsockopt     = tipc_getsockopt,
1965         .sendmsg        = tipc_send_packet,
1966         .recvmsg        = tipc_recvmsg,
1967         .mmap           = sock_no_mmap,
1968         .sendpage       = sock_no_sendpage
1969 };
1970
1971 static const struct proto_ops stream_ops = {
1972         .owner          = THIS_MODULE,
1973         .family         = AF_TIPC,
1974         .release        = tipc_release,
1975         .bind           = tipc_bind,
1976         .connect        = tipc_connect,
1977         .socketpair     = sock_no_socketpair,
1978         .accept         = tipc_accept,
1979         .getname        = tipc_getname,
1980         .poll           = tipc_poll,
1981         .ioctl          = sock_no_ioctl,
1982         .listen         = tipc_listen,
1983         .shutdown       = tipc_shutdown,
1984         .setsockopt     = tipc_setsockopt,
1985         .getsockopt     = tipc_getsockopt,
1986         .sendmsg        = tipc_send_stream,
1987         .recvmsg        = tipc_recv_stream,
1988         .mmap           = sock_no_mmap,
1989         .sendpage       = sock_no_sendpage
1990 };
1991
1992 static const struct net_proto_family tipc_family_ops = {
1993         .owner          = THIS_MODULE,
1994         .family         = AF_TIPC,
1995         .create         = tipc_sk_create
1996 };
1997
1998 static struct proto tipc_proto = {
1999         .name           = "TIPC",
2000         .owner          = THIS_MODULE,
2001         .obj_size       = sizeof(struct tipc_sock),
2002         .sysctl_rmem    = sysctl_tipc_rmem
2003 };
2004
2005 static struct proto tipc_proto_kern = {
2006         .name           = "TIPC",
2007         .obj_size       = sizeof(struct tipc_sock),
2008         .sysctl_rmem    = sysctl_tipc_rmem
2009 };
2010
2011 /**
2012  * tipc_socket_init - initialize TIPC socket interface
2013  *
2014  * Returns 0 on success, errno otherwise
2015  */
2016 int tipc_socket_init(void)
2017 {
2018         int res;
2019
2020         res = proto_register(&tipc_proto, 1);
2021         if (res) {
2022                 pr_err("Failed to register TIPC protocol type\n");
2023                 goto out;
2024         }
2025
2026         res = sock_register(&tipc_family_ops);
2027         if (res) {
2028                 pr_err("Failed to register TIPC socket type\n");
2029                 proto_unregister(&tipc_proto);
2030                 goto out;
2031         }
2032
2033         sockets_enabled = 1;
2034  out:
2035         return res;
2036 }
2037
2038 /**
2039  * tipc_socket_stop - stop TIPC socket interface
2040  */
2041 void tipc_socket_stop(void)
2042 {
2043         if (!sockets_enabled)
2044                 return;
2045
2046         sockets_enabled = 0;
2047         sock_unregister(tipc_family_ops.family);
2048         proto_unregister(&tipc_proto);
2049 }