ea33eab4fb9d7f082e993f2db6feceda2beb9562
[pandora-kernel.git] / net / tipc / socket.c
1 /*
2  * net/tipc/socket.c: TIPC socket API
3  *
4  * Copyright (c) 2001-2007, 2012-2014, 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 "ref.h"
39 #include "port.h"
40 #include "name_table.h"
41 #include "node.h"
42 #include "link.h"
43 #include <linux/export.h>
44 #include "config.h"
45
46 #define SS_LISTENING    -1      /* socket is listening */
47 #define SS_READY        -2      /* socket is connectionless */
48
49 #define CONN_TIMEOUT_DEFAULT    8000    /* default connect timeout = 8s */
50 #define CONN_PROBING_INTERVAL 3600000   /* [ms] => 1 h */
51 #define TIPC_FWD_MSG            1
52
53 static int tipc_backlog_rcv(struct sock *sk, struct sk_buff *skb);
54 static void tipc_data_ready(struct sock *sk);
55 static void tipc_write_space(struct sock *sk);
56 static int tipc_release(struct socket *sock);
57 static int tipc_accept(struct socket *sock, struct socket *new_sock, int flags);
58 static int tipc_wait_for_sndmsg(struct socket *sock, long *timeo_p);
59 static void tipc_sk_timeout(unsigned long ref);
60 static int tipc_sk_publish(struct tipc_port *port, uint scope,
61                            struct tipc_name_seq const *seq);
62 static int tipc_sk_withdraw(struct tipc_port *port, uint scope,
63                             struct tipc_name_seq const *seq);
64
65 static const struct proto_ops packet_ops;
66 static const struct proto_ops stream_ops;
67 static const struct proto_ops msg_ops;
68
69 static struct proto tipc_proto;
70 static struct proto tipc_proto_kern;
71
72 /*
73  * Revised TIPC socket locking policy:
74  *
75  * Most socket operations take the standard socket lock when they start
76  * and hold it until they finish (or until they need to sleep).  Acquiring
77  * this lock grants the owner exclusive access to the fields of the socket
78  * data structures, with the exception of the backlog queue.  A few socket
79  * operations can be done without taking the socket lock because they only
80  * read socket information that never changes during the life of the socket.
81  *
82  * Socket operations may acquire the lock for the associated TIPC port if they
83  * need to perform an operation on the port.  If any routine needs to acquire
84  * both the socket lock and the port lock it must take the socket lock first
85  * to avoid the risk of deadlock.
86  *
87  * The dispatcher handling incoming messages cannot grab the socket lock in
88  * the standard fashion, since invoked it runs at the BH level and cannot block.
89  * Instead, it checks to see if the socket lock is currently owned by someone,
90  * and either handles the message itself or adds it to the socket's backlog
91  * queue; in the latter case the queued message is processed once the process
92  * owning the socket lock releases it.
93  *
94  * NOTE: Releasing the socket lock while an operation is sleeping overcomes
95  * the problem of a blocked socket operation preventing any other operations
96  * from occurring.  However, applications must be careful if they have
97  * multiple threads trying to send (or receive) on the same socket, as these
98  * operations might interfere with each other.  For example, doing a connect
99  * and a receive at the same time might allow the receive to consume the
100  * ACK message meant for the connect.  While additional work could be done
101  * to try and overcome this, it doesn't seem to be worthwhile at the present.
102  *
103  * NOTE: Releasing the socket lock while an operation is sleeping also ensures
104  * that another operation that must be performed in a non-blocking manner is
105  * not delayed for very long because the lock has already been taken.
106  *
107  * NOTE: This code assumes that certain fields of a port/socket pair are
108  * constant over its lifetime; such fields can be examined without taking
109  * the socket lock and/or port lock, and do not need to be re-read even
110  * after resuming processing after waiting.  These fields include:
111  *   - socket type
112  *   - pointer to socket sk structure (aka tipc_sock structure)
113  *   - pointer to port structure
114  *   - port reference
115  */
116
117 #include "socket.h"
118
119 /**
120  * advance_rx_queue - discard first buffer in socket receive queue
121  *
122  * Caller must hold socket lock
123  */
124 static void advance_rx_queue(struct sock *sk)
125 {
126         kfree_skb(__skb_dequeue(&sk->sk_receive_queue));
127 }
128
129 /**
130  * reject_rx_queue - reject all buffers in socket receive queue
131  *
132  * Caller must hold socket lock
133  */
134 static void reject_rx_queue(struct sock *sk)
135 {
136         struct sk_buff *buf;
137         u32 dnode;
138
139         while ((buf = __skb_dequeue(&sk->sk_receive_queue))) {
140                 if (tipc_msg_reverse(buf, &dnode, TIPC_ERR_NO_PORT))
141                         tipc_link_xmit(buf, dnode, 0);
142         }
143 }
144
145 /* tipc_sk_peer_msg - verify if message was sent by connected port's peer
146  *
147  * Handles cases where the node's network address has changed from
148  * the default of <0.0.0> to its configured setting.
149  */
150 static bool tipc_sk_peer_msg(struct tipc_sock *tsk, struct tipc_msg *msg)
151 {
152         u32 peer_port = tipc_port_peerport(&tsk->port);
153         u32 orig_node;
154         u32 peer_node;
155
156         if (unlikely(!tsk->port.connected))
157                 return false;
158
159         if (unlikely(msg_origport(msg) != peer_port))
160                 return false;
161
162         orig_node = msg_orignode(msg);
163         peer_node = tipc_port_peernode(&tsk->port);
164
165         if (likely(orig_node == peer_node))
166                 return true;
167
168         if (!orig_node && (peer_node == tipc_own_addr))
169                 return true;
170
171         if (!peer_node && (orig_node == tipc_own_addr))
172                 return true;
173
174         return false;
175 }
176
177 /**
178  * tipc_sk_create - create a TIPC socket
179  * @net: network namespace (must be default network)
180  * @sock: pre-allocated socket structure
181  * @protocol: protocol indicator (must be 0)
182  * @kern: caused by kernel or by userspace?
183  *
184  * This routine creates additional data structures used by the TIPC socket,
185  * initializes them, and links them together.
186  *
187  * Returns 0 on success, errno otherwise
188  */
189 static int tipc_sk_create(struct net *net, struct socket *sock,
190                           int protocol, int kern)
191 {
192         const struct proto_ops *ops;
193         socket_state state;
194         struct sock *sk;
195         struct tipc_sock *tsk;
196         struct tipc_port *port;
197         struct tipc_msg *msg;
198         u32 ref;
199
200         /* Validate arguments */
201         if (unlikely(protocol != 0))
202                 return -EPROTONOSUPPORT;
203
204         switch (sock->type) {
205         case SOCK_STREAM:
206                 ops = &stream_ops;
207                 state = SS_UNCONNECTED;
208                 break;
209         case SOCK_SEQPACKET:
210                 ops = &packet_ops;
211                 state = SS_UNCONNECTED;
212                 break;
213         case SOCK_DGRAM:
214         case SOCK_RDM:
215                 ops = &msg_ops;
216                 state = SS_READY;
217                 break;
218         default:
219                 return -EPROTOTYPE;
220         }
221
222         /* Allocate socket's protocol area */
223         if (!kern)
224                 sk = sk_alloc(net, AF_TIPC, GFP_KERNEL, &tipc_proto);
225         else
226                 sk = sk_alloc(net, AF_TIPC, GFP_KERNEL, &tipc_proto_kern);
227
228         if (sk == NULL)
229                 return -ENOMEM;
230
231         tsk = tipc_sk(sk);
232         port = &tsk->port;
233         ref = tipc_ref_acquire(tsk);
234         if (!ref) {
235                 pr_warn("Socket create failed; reference table exhausted\n");
236                 return -ENOMEM;
237         }
238         port->max_pkt = MAX_PKT_DEFAULT;
239         port->ref = ref;
240         INIT_LIST_HEAD(&port->publications);
241
242         msg = &port->phdr;
243         tipc_msg_init(msg, TIPC_LOW_IMPORTANCE, TIPC_NAMED_MSG,
244                       NAMED_H_SIZE, 0);
245         msg_set_origport(msg, ref);
246
247         /* Finish initializing socket data structures */
248         sock->ops = ops;
249         sock->state = state;
250         sock_init_data(sock, sk);
251         k_init_timer(&port->timer, (Handler)tipc_sk_timeout, ref);
252         sk->sk_backlog_rcv = tipc_backlog_rcv;
253         sk->sk_rcvbuf = sysctl_tipc_rmem[1];
254         sk->sk_data_ready = tipc_data_ready;
255         sk->sk_write_space = tipc_write_space;
256         tsk->conn_timeout = CONN_TIMEOUT_DEFAULT;
257         tsk->sent_unacked = 0;
258         atomic_set(&tsk->dupl_rcvcnt, 0);
259
260         if (sock->state == SS_READY) {
261                 tipc_port_set_unreturnable(port, true);
262                 if (sock->type == SOCK_DGRAM)
263                         tipc_port_set_unreliable(port, true);
264         }
265         return 0;
266 }
267
268 /**
269  * tipc_sock_create_local - create TIPC socket from inside TIPC module
270  * @type: socket type - SOCK_RDM or SOCK_SEQPACKET
271  *
272  * We cannot use sock_creat_kern here because it bumps module user count.
273  * Since socket owner and creator is the same module we must make sure
274  * that module count remains zero for module local sockets, otherwise
275  * we cannot do rmmod.
276  *
277  * Returns 0 on success, errno otherwise
278  */
279 int tipc_sock_create_local(int type, struct socket **res)
280 {
281         int rc;
282
283         rc = sock_create_lite(AF_TIPC, type, 0, res);
284         if (rc < 0) {
285                 pr_err("Failed to create kernel socket\n");
286                 return rc;
287         }
288         tipc_sk_create(&init_net, *res, 0, 1);
289
290         return 0;
291 }
292
293 /**
294  * tipc_sock_release_local - release socket created by tipc_sock_create_local
295  * @sock: the socket to be released.
296  *
297  * Module reference count is not incremented when such sockets are created,
298  * so we must keep it from being decremented when they are released.
299  */
300 void tipc_sock_release_local(struct socket *sock)
301 {
302         tipc_release(sock);
303         sock->ops = NULL;
304         sock_release(sock);
305 }
306
307 /**
308  * tipc_sock_accept_local - accept a connection on a socket created
309  * with tipc_sock_create_local. Use this function to avoid that
310  * module reference count is inadvertently incremented.
311  *
312  * @sock:    the accepting socket
313  * @newsock: reference to the new socket to be created
314  * @flags:   socket flags
315  */
316
317 int tipc_sock_accept_local(struct socket *sock, struct socket **newsock,
318                            int flags)
319 {
320         struct sock *sk = sock->sk;
321         int ret;
322
323         ret = sock_create_lite(sk->sk_family, sk->sk_type,
324                                sk->sk_protocol, newsock);
325         if (ret < 0)
326                 return ret;
327
328         ret = tipc_accept(sock, *newsock, flags);
329         if (ret < 0) {
330                 sock_release(*newsock);
331                 return ret;
332         }
333         (*newsock)->ops = sock->ops;
334         return ret;
335 }
336
337 /**
338  * tipc_release - destroy a TIPC socket
339  * @sock: socket to destroy
340  *
341  * This routine cleans up any messages that are still queued on the socket.
342  * For DGRAM and RDM socket types, all queued messages are rejected.
343  * For SEQPACKET and STREAM socket types, the first message is rejected
344  * and any others are discarded.  (If the first message on a STREAM socket
345  * is partially-read, it is discarded and the next one is rejected instead.)
346  *
347  * NOTE: Rejected messages are not necessarily returned to the sender!  They
348  * are returned or discarded according to the "destination droppable" setting
349  * specified for the message by the sender.
350  *
351  * Returns 0 on success, errno otherwise
352  */
353 static int tipc_release(struct socket *sock)
354 {
355         struct sock *sk = sock->sk;
356         struct tipc_sock *tsk;
357         struct tipc_port *port;
358         struct sk_buff *buf;
359         u32 dnode;
360
361         /*
362          * Exit if socket isn't fully initialized (occurs when a failed accept()
363          * releases a pre-allocated child socket that was never used)
364          */
365         if (sk == NULL)
366                 return 0;
367
368         tsk = tipc_sk(sk);
369         port = &tsk->port;
370         lock_sock(sk);
371
372         /*
373          * Reject all unreceived messages, except on an active connection
374          * (which disconnects locally & sends a 'FIN+' to peer)
375          */
376         dnode = tipc_port_peernode(port);
377         while (sock->state != SS_DISCONNECTING) {
378                 buf = __skb_dequeue(&sk->sk_receive_queue);
379                 if (buf == NULL)
380                         break;
381                 if (TIPC_SKB_CB(buf)->handle != NULL)
382                         kfree_skb(buf);
383                 else {
384                         if ((sock->state == SS_CONNECTING) ||
385                             (sock->state == SS_CONNECTED)) {
386                                 sock->state = SS_DISCONNECTING;
387                                 port->connected = 0;
388                                 tipc_node_remove_conn(dnode, port->ref);
389                         }
390                         if (tipc_msg_reverse(buf, &dnode, TIPC_ERR_NO_PORT))
391                                 tipc_link_xmit(buf, dnode, 0);
392                 }
393         }
394
395         tipc_sk_withdraw(port, 0, NULL);
396         tipc_ref_discard(port->ref);
397         k_cancel_timer(&port->timer);
398         if (port->connected) {
399                 buf = tipc_msg_create(TIPC_CRITICAL_IMPORTANCE, TIPC_CONN_MSG,
400                                       SHORT_H_SIZE, 0, dnode, tipc_own_addr,
401                                       tipc_port_peerport(port),
402                                       port->ref, TIPC_ERR_NO_PORT);
403                 if (buf)
404                         tipc_link_xmit(buf, dnode, port->ref);
405                 tipc_node_remove_conn(dnode, port->ref);
406         }
407         k_term_timer(&port->timer);
408
409         /* Discard any remaining (connection-based) messages in receive queue */
410         __skb_queue_purge(&sk->sk_receive_queue);
411
412         /* Reject any messages that accumulated in backlog queue */
413         sock->state = SS_DISCONNECTING;
414         release_sock(sk);
415         sock_put(sk);
416         sock->sk = NULL;
417
418         return 0;
419 }
420
421 /**
422  * tipc_bind - associate or disassocate TIPC name(s) with a socket
423  * @sock: socket structure
424  * @uaddr: socket address describing name(s) and desired operation
425  * @uaddr_len: size of socket address data structure
426  *
427  * Name and name sequence binding is indicated using a positive scope value;
428  * a negative scope value unbinds the specified name.  Specifying no name
429  * (i.e. a socket address length of 0) unbinds all names from the socket.
430  *
431  * Returns 0 on success, errno otherwise
432  *
433  * NOTE: This routine doesn't need to take the socket lock since it doesn't
434  *       access any non-constant socket information.
435  */
436 static int tipc_bind(struct socket *sock, struct sockaddr *uaddr,
437                      int uaddr_len)
438 {
439         struct sock *sk = sock->sk;
440         struct sockaddr_tipc *addr = (struct sockaddr_tipc *)uaddr;
441         struct tipc_sock *tsk = tipc_sk(sk);
442         int res = -EINVAL;
443
444         lock_sock(sk);
445         if (unlikely(!uaddr_len)) {
446                 res = tipc_sk_withdraw(&tsk->port, 0, NULL);
447                 goto exit;
448         }
449
450         if (uaddr_len < sizeof(struct sockaddr_tipc)) {
451                 res = -EINVAL;
452                 goto exit;
453         }
454         if (addr->family != AF_TIPC) {
455                 res = -EAFNOSUPPORT;
456                 goto exit;
457         }
458
459         if (addr->addrtype == TIPC_ADDR_NAME)
460                 addr->addr.nameseq.upper = addr->addr.nameseq.lower;
461         else if (addr->addrtype != TIPC_ADDR_NAMESEQ) {
462                 res = -EAFNOSUPPORT;
463                 goto exit;
464         }
465
466         if ((addr->addr.nameseq.type < TIPC_RESERVED_TYPES) &&
467             (addr->addr.nameseq.type != TIPC_TOP_SRV) &&
468             (addr->addr.nameseq.type != TIPC_CFG_SRV)) {
469                 res = -EACCES;
470                 goto exit;
471         }
472
473         res = (addr->scope > 0) ?
474                 tipc_sk_publish(&tsk->port, addr->scope, &addr->addr.nameseq) :
475                 tipc_sk_withdraw(&tsk->port, -addr->scope, &addr->addr.nameseq);
476 exit:
477         release_sock(sk);
478         return res;
479 }
480
481 /**
482  * tipc_getname - get port ID of socket or peer socket
483  * @sock: socket structure
484  * @uaddr: area for returned socket address
485  * @uaddr_len: area for returned length of socket address
486  * @peer: 0 = own ID, 1 = current peer ID, 2 = current/former peer ID
487  *
488  * Returns 0 on success, errno otherwise
489  *
490  * NOTE: This routine doesn't need to take the socket lock since it only
491  *       accesses socket information that is unchanging (or which changes in
492  *       a completely predictable manner).
493  */
494 static int tipc_getname(struct socket *sock, struct sockaddr *uaddr,
495                         int *uaddr_len, int peer)
496 {
497         struct sockaddr_tipc *addr = (struct sockaddr_tipc *)uaddr;
498         struct tipc_sock *tsk = tipc_sk(sock->sk);
499
500         memset(addr, 0, sizeof(*addr));
501         if (peer) {
502                 if ((sock->state != SS_CONNECTED) &&
503                         ((peer != 2) || (sock->state != SS_DISCONNECTING)))
504                         return -ENOTCONN;
505                 addr->addr.id.ref = tipc_port_peerport(&tsk->port);
506                 addr->addr.id.node = tipc_port_peernode(&tsk->port);
507         } else {
508                 addr->addr.id.ref = tsk->port.ref;
509                 addr->addr.id.node = tipc_own_addr;
510         }
511
512         *uaddr_len = sizeof(*addr);
513         addr->addrtype = TIPC_ADDR_ID;
514         addr->family = AF_TIPC;
515         addr->scope = 0;
516         addr->addr.name.domain = 0;
517
518         return 0;
519 }
520
521 /**
522  * tipc_poll - read and possibly block on pollmask
523  * @file: file structure associated with the socket
524  * @sock: socket for which to calculate the poll bits
525  * @wait: ???
526  *
527  * Returns pollmask value
528  *
529  * COMMENTARY:
530  * It appears that the usual socket locking mechanisms are not useful here
531  * since the pollmask info is potentially out-of-date the moment this routine
532  * exits.  TCP and other protocols seem to rely on higher level poll routines
533  * to handle any preventable race conditions, so TIPC will do the same ...
534  *
535  * TIPC sets the returned events as follows:
536  *
537  * socket state         flags set
538  * ------------         ---------
539  * unconnected          no read flags
540  *                      POLLOUT if port is not congested
541  *
542  * connecting           POLLIN/POLLRDNORM if ACK/NACK in rx queue
543  *                      no write flags
544  *
545  * connected            POLLIN/POLLRDNORM if data in rx queue
546  *                      POLLOUT if port is not congested
547  *
548  * disconnecting        POLLIN/POLLRDNORM/POLLHUP
549  *                      no write flags
550  *
551  * listening            POLLIN if SYN in rx queue
552  *                      no write flags
553  *
554  * ready                POLLIN/POLLRDNORM if data in rx queue
555  * [connectionless]     POLLOUT (since port cannot be congested)
556  *
557  * IMPORTANT: The fact that a read or write operation is indicated does NOT
558  * imply that the operation will succeed, merely that it should be performed
559  * and will not block.
560  */
561 static unsigned int tipc_poll(struct file *file, struct socket *sock,
562                               poll_table *wait)
563 {
564         struct sock *sk = sock->sk;
565         struct tipc_sock *tsk = tipc_sk(sk);
566         u32 mask = 0;
567
568         sock_poll_wait(file, sk_sleep(sk), wait);
569
570         switch ((int)sock->state) {
571         case SS_UNCONNECTED:
572                 if (!tsk->link_cong)
573                         mask |= POLLOUT;
574                 break;
575         case SS_READY:
576         case SS_CONNECTED:
577                 if (!tsk->link_cong && !tipc_sk_conn_cong(tsk))
578                         mask |= POLLOUT;
579                 /* fall thru' */
580         case SS_CONNECTING:
581         case SS_LISTENING:
582                 if (!skb_queue_empty(&sk->sk_receive_queue))
583                         mask |= (POLLIN | POLLRDNORM);
584                 break;
585         case SS_DISCONNECTING:
586                 mask = (POLLIN | POLLRDNORM | POLLHUP);
587                 break;
588         }
589
590         return mask;
591 }
592
593 /**
594  * tipc_sendmcast - send multicast message
595  * @sock: socket structure
596  * @seq: destination address
597  * @iov: message data to send
598  * @dsz: total length of message data
599  * @timeo: timeout to wait for wakeup
600  *
601  * Called from function tipc_sendmsg(), which has done all sanity checks
602  * Returns the number of bytes sent on success, or errno
603  */
604 static int tipc_sendmcast(struct  socket *sock, struct tipc_name_seq *seq,
605                           struct iovec *iov, size_t dsz, long timeo)
606 {
607         struct sock *sk = sock->sk;
608         struct tipc_msg *mhdr = &tipc_sk(sk)->port.phdr;
609         struct sk_buff *buf;
610         uint mtu;
611         int rc;
612
613         msg_set_type(mhdr, TIPC_MCAST_MSG);
614         msg_set_lookup_scope(mhdr, TIPC_CLUSTER_SCOPE);
615         msg_set_destport(mhdr, 0);
616         msg_set_destnode(mhdr, 0);
617         msg_set_nametype(mhdr, seq->type);
618         msg_set_namelower(mhdr, seq->lower);
619         msg_set_nameupper(mhdr, seq->upper);
620         msg_set_hdr_sz(mhdr, MCAST_H_SIZE);
621
622 new_mtu:
623         mtu = tipc_bclink_get_mtu();
624         rc = tipc_msg_build(mhdr, iov, 0, dsz, mtu, &buf);
625         if (unlikely(rc < 0))
626                 return rc;
627
628         do {
629                 rc = tipc_bclink_xmit(buf);
630                 if (likely(rc >= 0)) {
631                         rc = dsz;
632                         break;
633                 }
634                 if (rc == -EMSGSIZE)
635                         goto new_mtu;
636                 if (rc != -ELINKCONG)
637                         break;
638                 tipc_sk(sk)->link_cong = 1;
639                 rc = tipc_wait_for_sndmsg(sock, &timeo);
640                 if (rc)
641                         kfree_skb_list(buf);
642         } while (!rc);
643         return rc;
644 }
645
646 /* tipc_sk_mcast_rcv - Deliver multicast message to all destination sockets
647  */
648 void tipc_sk_mcast_rcv(struct sk_buff *buf)
649 {
650         struct tipc_msg *msg = buf_msg(buf);
651         struct tipc_port_list dports = {0, NULL, };
652         struct tipc_port_list *item;
653         struct sk_buff *b;
654         uint i, last, dst = 0;
655         u32 scope = TIPC_CLUSTER_SCOPE;
656
657         if (in_own_node(msg_orignode(msg)))
658                 scope = TIPC_NODE_SCOPE;
659
660         /* Create destination port list: */
661         tipc_nametbl_mc_translate(msg_nametype(msg),
662                                   msg_namelower(msg),
663                                   msg_nameupper(msg),
664                                   scope,
665                                   &dports);
666         last = dports.count;
667         if (!last) {
668                 kfree_skb(buf);
669                 return;
670         }
671
672         for (item = &dports; item; item = item->next) {
673                 for (i = 0; i < PLSIZE && ++dst <= last; i++) {
674                         b = (dst != last) ? skb_clone(buf, GFP_ATOMIC) : buf;
675                         if (!b) {
676                                 pr_warn("Failed do clone mcast rcv buffer\n");
677                                 continue;
678                         }
679                         msg_set_destport(msg, item->ports[i]);
680                         tipc_sk_rcv(b);
681                 }
682         }
683         tipc_port_list_free(&dports);
684 }
685
686 /**
687  * tipc_sk_proto_rcv - receive a connection mng protocol message
688  * @tsk: receiving socket
689  * @dnode: node to send response message to, if any
690  * @buf: buffer containing protocol message
691  * Returns 0 (TIPC_OK) if message was consumed, 1 (TIPC_FWD_MSG) if
692  * (CONN_PROBE_REPLY) message should be forwarded.
693  */
694 static int tipc_sk_proto_rcv(struct tipc_sock *tsk, u32 *dnode,
695                              struct sk_buff *buf)
696 {
697         struct tipc_msg *msg = buf_msg(buf);
698         struct tipc_port *port = &tsk->port;
699         int conn_cong;
700
701         /* Ignore if connection cannot be validated: */
702         if (!tipc_sk_peer_msg(tsk, msg))
703                 goto exit;
704
705         port->probing_state = TIPC_CONN_OK;
706
707         if (msg_type(msg) == CONN_ACK) {
708                 conn_cong = tipc_sk_conn_cong(tsk);
709                 tsk->sent_unacked -= msg_msgcnt(msg);
710                 if (conn_cong)
711                         tsk->sk.sk_write_space(&tsk->sk);
712         } else if (msg_type(msg) == CONN_PROBE) {
713                 if (!tipc_msg_reverse(buf, dnode, TIPC_OK))
714                         return TIPC_OK;
715                 msg_set_type(msg, CONN_PROBE_REPLY);
716                 return TIPC_FWD_MSG;
717         }
718         /* Do nothing if msg_type() == CONN_PROBE_REPLY */
719 exit:
720         kfree_skb(buf);
721         return TIPC_OK;
722 }
723
724 /**
725  * dest_name_check - verify user is permitted to send to specified port name
726  * @dest: destination address
727  * @m: descriptor for message to be sent
728  *
729  * Prevents restricted configuration commands from being issued by
730  * unauthorized users.
731  *
732  * Returns 0 if permission is granted, otherwise errno
733  */
734 static int dest_name_check(struct sockaddr_tipc *dest, struct msghdr *m)
735 {
736         struct tipc_cfg_msg_hdr hdr;
737
738         if (unlikely(dest->addrtype == TIPC_ADDR_ID))
739                 return 0;
740         if (likely(dest->addr.name.name.type >= TIPC_RESERVED_TYPES))
741                 return 0;
742         if (likely(dest->addr.name.name.type == TIPC_TOP_SRV))
743                 return 0;
744         if (likely(dest->addr.name.name.type != TIPC_CFG_SRV))
745                 return -EACCES;
746
747         if (!m->msg_iovlen || (m->msg_iov[0].iov_len < sizeof(hdr)))
748                 return -EMSGSIZE;
749         if (copy_from_user(&hdr, m->msg_iov[0].iov_base, sizeof(hdr)))
750                 return -EFAULT;
751         if ((ntohs(hdr.tcm_type) & 0xC000) && (!capable(CAP_NET_ADMIN)))
752                 return -EACCES;
753
754         return 0;
755 }
756
757 static int tipc_wait_for_sndmsg(struct socket *sock, long *timeo_p)
758 {
759         struct sock *sk = sock->sk;
760         struct tipc_sock *tsk = tipc_sk(sk);
761         DEFINE_WAIT(wait);
762         int done;
763
764         do {
765                 int err = sock_error(sk);
766                 if (err)
767                         return err;
768                 if (sock->state == SS_DISCONNECTING)
769                         return -EPIPE;
770                 if (!*timeo_p)
771                         return -EAGAIN;
772                 if (signal_pending(current))
773                         return sock_intr_errno(*timeo_p);
774
775                 prepare_to_wait(sk_sleep(sk), &wait, TASK_INTERRUPTIBLE);
776                 done = sk_wait_event(sk, timeo_p, !tsk->link_cong);
777                 finish_wait(sk_sleep(sk), &wait);
778         } while (!done);
779         return 0;
780 }
781
782 /**
783  * tipc_sendmsg - send message in connectionless manner
784  * @iocb: if NULL, indicates that socket lock is already held
785  * @sock: socket structure
786  * @m: message to send
787  * @dsz: amount of user data to be sent
788  *
789  * Message must have an destination specified explicitly.
790  * Used for SOCK_RDM and SOCK_DGRAM messages,
791  * and for 'SYN' messages on SOCK_SEQPACKET and SOCK_STREAM connections.
792  * (Note: 'SYN+' is prohibited on SOCK_STREAM.)
793  *
794  * Returns the number of bytes sent on success, or errno otherwise
795  */
796 static int tipc_sendmsg(struct kiocb *iocb, struct socket *sock,
797                         struct msghdr *m, size_t dsz)
798 {
799         DECLARE_SOCKADDR(struct sockaddr_tipc *, dest, m->msg_name);
800         struct sock *sk = sock->sk;
801         struct tipc_sock *tsk = tipc_sk(sk);
802         struct tipc_port *port = &tsk->port;
803         struct tipc_msg *mhdr = &port->phdr;
804         struct iovec *iov = m->msg_iov;
805         u32 dnode, dport;
806         struct sk_buff *buf;
807         struct tipc_name_seq *seq = &dest->addr.nameseq;
808         u32 mtu;
809         long timeo;
810         int rc = -EINVAL;
811
812         if (unlikely(!dest))
813                 return -EDESTADDRREQ;
814
815         if (unlikely((m->msg_namelen < sizeof(*dest)) ||
816                      (dest->family != AF_TIPC)))
817                 return -EINVAL;
818
819         if (dsz > TIPC_MAX_USER_MSG_SIZE)
820                 return -EMSGSIZE;
821
822         if (iocb)
823                 lock_sock(sk);
824
825         if (unlikely(sock->state != SS_READY)) {
826                 if (sock->state == SS_LISTENING) {
827                         rc = -EPIPE;
828                         goto exit;
829                 }
830                 if (sock->state != SS_UNCONNECTED) {
831                         rc = -EISCONN;
832                         goto exit;
833                 }
834                 if (tsk->port.published) {
835                         rc = -EOPNOTSUPP;
836                         goto exit;
837                 }
838                 if (dest->addrtype == TIPC_ADDR_NAME) {
839                         tsk->port.conn_type = dest->addr.name.name.type;
840                         tsk->port.conn_instance = dest->addr.name.name.instance;
841                 }
842         }
843         rc = dest_name_check(dest, m);
844         if (rc)
845                 goto exit;
846
847         timeo = sock_sndtimeo(sk, m->msg_flags & MSG_DONTWAIT);
848
849         if (dest->addrtype == TIPC_ADDR_MCAST) {
850                 rc = tipc_sendmcast(sock, seq, iov, dsz, timeo);
851                 goto exit;
852         } else if (dest->addrtype == TIPC_ADDR_NAME) {
853                 u32 type = dest->addr.name.name.type;
854                 u32 inst = dest->addr.name.name.instance;
855                 u32 domain = dest->addr.name.domain;
856
857                 dnode = domain;
858                 msg_set_type(mhdr, TIPC_NAMED_MSG);
859                 msg_set_hdr_sz(mhdr, NAMED_H_SIZE);
860                 msg_set_nametype(mhdr, type);
861                 msg_set_nameinst(mhdr, inst);
862                 msg_set_lookup_scope(mhdr, tipc_addr_scope(domain));
863                 dport = tipc_nametbl_translate(type, inst, &dnode);
864                 msg_set_destnode(mhdr, dnode);
865                 msg_set_destport(mhdr, dport);
866                 if (unlikely(!dport && !dnode)) {
867                         rc = -EHOSTUNREACH;
868                         goto exit;
869                 }
870         } else if (dest->addrtype == TIPC_ADDR_ID) {
871                 dnode = dest->addr.id.node;
872                 msg_set_type(mhdr, TIPC_DIRECT_MSG);
873                 msg_set_lookup_scope(mhdr, 0);
874                 msg_set_destnode(mhdr, dnode);
875                 msg_set_destport(mhdr, dest->addr.id.ref);
876                 msg_set_hdr_sz(mhdr, BASIC_H_SIZE);
877         }
878
879 new_mtu:
880         mtu = tipc_node_get_mtu(dnode, tsk->port.ref);
881         rc = tipc_msg_build(mhdr, iov, 0, dsz, mtu, &buf);
882         if (rc < 0)
883                 goto exit;
884
885         do {
886                 TIPC_SKB_CB(buf)->wakeup_pending = tsk->link_cong;
887                 rc = tipc_link_xmit(buf, dnode, tsk->port.ref);
888                 if (likely(rc >= 0)) {
889                         if (sock->state != SS_READY)
890                                 sock->state = SS_CONNECTING;
891                         rc = dsz;
892                         break;
893                 }
894                 if (rc == -EMSGSIZE)
895                         goto new_mtu;
896                 if (rc != -ELINKCONG)
897                         break;
898                 tsk->link_cong = 1;
899                 rc = tipc_wait_for_sndmsg(sock, &timeo);
900                 if (rc)
901                         kfree_skb_list(buf);
902         } while (!rc);
903 exit:
904         if (iocb)
905                 release_sock(sk);
906
907         return rc;
908 }
909
910 static int tipc_wait_for_sndpkt(struct socket *sock, long *timeo_p)
911 {
912         struct sock *sk = sock->sk;
913         struct tipc_sock *tsk = tipc_sk(sk);
914         DEFINE_WAIT(wait);
915         int done;
916
917         do {
918                 int err = sock_error(sk);
919                 if (err)
920                         return err;
921                 if (sock->state == SS_DISCONNECTING)
922                         return -EPIPE;
923                 else if (sock->state != SS_CONNECTED)
924                         return -ENOTCONN;
925                 if (!*timeo_p)
926                         return -EAGAIN;
927                 if (signal_pending(current))
928                         return sock_intr_errno(*timeo_p);
929
930                 prepare_to_wait(sk_sleep(sk), &wait, TASK_INTERRUPTIBLE);
931                 done = sk_wait_event(sk, timeo_p,
932                                      (!tsk->link_cong &&
933                                       !tipc_sk_conn_cong(tsk)) ||
934                                      !tsk->port.connected);
935                 finish_wait(sk_sleep(sk), &wait);
936         } while (!done);
937         return 0;
938 }
939
940 /**
941  * tipc_send_stream - send stream-oriented data
942  * @iocb: (unused)
943  * @sock: socket structure
944  * @m: data to send
945  * @dsz: total length of data to be transmitted
946  *
947  * Used for SOCK_STREAM data.
948  *
949  * Returns the number of bytes sent on success (or partial success),
950  * or errno if no data sent
951  */
952 static int tipc_send_stream(struct kiocb *iocb, struct socket *sock,
953                             struct msghdr *m, size_t dsz)
954 {
955         struct sock *sk = sock->sk;
956         struct tipc_sock *tsk = tipc_sk(sk);
957         struct tipc_port *port = &tsk->port;
958         struct tipc_msg *mhdr = &port->phdr;
959         struct sk_buff *buf;
960         DECLARE_SOCKADDR(struct sockaddr_tipc *, dest, m->msg_name);
961         u32 ref = port->ref;
962         int rc = -EINVAL;
963         long timeo;
964         u32 dnode;
965         uint mtu, send, sent = 0;
966
967         /* Handle implied connection establishment */
968         if (unlikely(dest)) {
969                 rc = tipc_sendmsg(iocb, sock, m, dsz);
970                 if (dsz && (dsz == rc))
971                         tsk->sent_unacked = 1;
972                 return rc;
973         }
974         if (dsz > (uint)INT_MAX)
975                 return -EMSGSIZE;
976
977         if (iocb)
978                 lock_sock(sk);
979
980         if (unlikely(sock->state != SS_CONNECTED)) {
981                 if (sock->state == SS_DISCONNECTING)
982                         rc = -EPIPE;
983                 else
984                         rc = -ENOTCONN;
985                 goto exit;
986         }
987
988         timeo = sock_sndtimeo(sk, m->msg_flags & MSG_DONTWAIT);
989         dnode = tipc_port_peernode(port);
990
991 next:
992         mtu = port->max_pkt;
993         send = min_t(uint, dsz - sent, TIPC_MAX_USER_MSG_SIZE);
994         rc = tipc_msg_build(mhdr, m->msg_iov, sent, send, mtu, &buf);
995         if (unlikely(rc < 0))
996                 goto exit;
997         do {
998                 if (likely(!tipc_sk_conn_cong(tsk))) {
999                         rc = tipc_link_xmit(buf, dnode, ref);
1000                         if (likely(!rc)) {
1001                                 tsk->sent_unacked++;
1002                                 sent += send;
1003                                 if (sent == dsz)
1004                                         break;
1005                                 goto next;
1006                         }
1007                         if (rc == -EMSGSIZE) {
1008                                 port->max_pkt = tipc_node_get_mtu(dnode, ref);
1009                                 goto next;
1010                         }
1011                         if (rc != -ELINKCONG)
1012                                 break;
1013                         tsk->link_cong = 1;
1014                 }
1015                 rc = tipc_wait_for_sndpkt(sock, &timeo);
1016                 if (rc)
1017                         kfree_skb_list(buf);
1018         } while (!rc);
1019 exit:
1020         if (iocb)
1021                 release_sock(sk);
1022         return sent ? sent : rc;
1023 }
1024
1025 /**
1026  * tipc_send_packet - send a connection-oriented message
1027  * @iocb: if NULL, indicates that socket lock is already held
1028  * @sock: socket structure
1029  * @m: message to send
1030  * @dsz: length of data to be transmitted
1031  *
1032  * Used for SOCK_SEQPACKET messages.
1033  *
1034  * Returns the number of bytes sent on success, or errno otherwise
1035  */
1036 static int tipc_send_packet(struct kiocb *iocb, struct socket *sock,
1037                             struct msghdr *m, size_t dsz)
1038 {
1039         if (dsz > TIPC_MAX_USER_MSG_SIZE)
1040                 return -EMSGSIZE;
1041
1042         return tipc_send_stream(iocb, sock, m, dsz);
1043 }
1044
1045 /* tipc_sk_finish_conn - complete the setup of a connection
1046  */
1047 static void tipc_sk_finish_conn(struct tipc_port *port, u32 peer_port,
1048                                 u32 peer_node)
1049 {
1050         struct tipc_msg *msg = &port->phdr;
1051
1052         msg_set_destnode(msg, peer_node);
1053         msg_set_destport(msg, peer_port);
1054         msg_set_type(msg, TIPC_CONN_MSG);
1055         msg_set_lookup_scope(msg, 0);
1056         msg_set_hdr_sz(msg, SHORT_H_SIZE);
1057
1058         port->probing_interval = CONN_PROBING_INTERVAL;
1059         port->probing_state = TIPC_CONN_OK;
1060         port->connected = 1;
1061         k_start_timer(&port->timer, port->probing_interval);
1062         tipc_node_add_conn(peer_node, port->ref, peer_port);
1063         port->max_pkt = tipc_node_get_mtu(peer_node, port->ref);
1064 }
1065
1066 /**
1067  * set_orig_addr - capture sender's address for received message
1068  * @m: descriptor for message info
1069  * @msg: received message header
1070  *
1071  * Note: Address is not captured if not requested by receiver.
1072  */
1073 static void set_orig_addr(struct msghdr *m, struct tipc_msg *msg)
1074 {
1075         DECLARE_SOCKADDR(struct sockaddr_tipc *, addr, m->msg_name);
1076
1077         if (addr) {
1078                 addr->family = AF_TIPC;
1079                 addr->addrtype = TIPC_ADDR_ID;
1080                 memset(&addr->addr, 0, sizeof(addr->addr));
1081                 addr->addr.id.ref = msg_origport(msg);
1082                 addr->addr.id.node = msg_orignode(msg);
1083                 addr->addr.name.domain = 0;     /* could leave uninitialized */
1084                 addr->scope = 0;                /* could leave uninitialized */
1085                 m->msg_namelen = sizeof(struct sockaddr_tipc);
1086         }
1087 }
1088
1089 /**
1090  * anc_data_recv - optionally capture ancillary data for received message
1091  * @m: descriptor for message info
1092  * @msg: received message header
1093  * @tport: TIPC port associated with message
1094  *
1095  * Note: Ancillary data is not captured if not requested by receiver.
1096  *
1097  * Returns 0 if successful, otherwise errno
1098  */
1099 static int anc_data_recv(struct msghdr *m, struct tipc_msg *msg,
1100                          struct tipc_port *tport)
1101 {
1102         u32 anc_data[3];
1103         u32 err;
1104         u32 dest_type;
1105         int has_name;
1106         int res;
1107
1108         if (likely(m->msg_controllen == 0))
1109                 return 0;
1110
1111         /* Optionally capture errored message object(s) */
1112         err = msg ? msg_errcode(msg) : 0;
1113         if (unlikely(err)) {
1114                 anc_data[0] = err;
1115                 anc_data[1] = msg_data_sz(msg);
1116                 res = put_cmsg(m, SOL_TIPC, TIPC_ERRINFO, 8, anc_data);
1117                 if (res)
1118                         return res;
1119                 if (anc_data[1]) {
1120                         res = put_cmsg(m, SOL_TIPC, TIPC_RETDATA, anc_data[1],
1121                                        msg_data(msg));
1122                         if (res)
1123                                 return res;
1124                 }
1125         }
1126
1127         /* Optionally capture message destination object */
1128         dest_type = msg ? msg_type(msg) : TIPC_DIRECT_MSG;
1129         switch (dest_type) {
1130         case TIPC_NAMED_MSG:
1131                 has_name = 1;
1132                 anc_data[0] = msg_nametype(msg);
1133                 anc_data[1] = msg_namelower(msg);
1134                 anc_data[2] = msg_namelower(msg);
1135                 break;
1136         case TIPC_MCAST_MSG:
1137                 has_name = 1;
1138                 anc_data[0] = msg_nametype(msg);
1139                 anc_data[1] = msg_namelower(msg);
1140                 anc_data[2] = msg_nameupper(msg);
1141                 break;
1142         case TIPC_CONN_MSG:
1143                 has_name = (tport->conn_type != 0);
1144                 anc_data[0] = tport->conn_type;
1145                 anc_data[1] = tport->conn_instance;
1146                 anc_data[2] = tport->conn_instance;
1147                 break;
1148         default:
1149                 has_name = 0;
1150         }
1151         if (has_name) {
1152                 res = put_cmsg(m, SOL_TIPC, TIPC_DESTNAME, 12, anc_data);
1153                 if (res)
1154                         return res;
1155         }
1156
1157         return 0;
1158 }
1159
1160 static void tipc_sk_send_ack(struct tipc_port *port, uint ack)
1161 {
1162         struct sk_buff *buf = NULL;
1163         struct tipc_msg *msg;
1164         u32 peer_port = tipc_port_peerport(port);
1165         u32 dnode = tipc_port_peernode(port);
1166
1167         if (!port->connected)
1168                 return;
1169         buf = tipc_msg_create(CONN_MANAGER, CONN_ACK, INT_H_SIZE, 0, dnode,
1170                               tipc_own_addr, peer_port, port->ref, TIPC_OK);
1171         if (!buf)
1172                 return;
1173         msg = buf_msg(buf);
1174         msg_set_msgcnt(msg, ack);
1175         tipc_link_xmit(buf, dnode, msg_link_selector(msg));
1176 }
1177
1178 static int tipc_wait_for_rcvmsg(struct socket *sock, long *timeop)
1179 {
1180         struct sock *sk = sock->sk;
1181         DEFINE_WAIT(wait);
1182         long timeo = *timeop;
1183         int err;
1184
1185         for (;;) {
1186                 prepare_to_wait(sk_sleep(sk), &wait, TASK_INTERRUPTIBLE);
1187                 if (timeo && skb_queue_empty(&sk->sk_receive_queue)) {
1188                         if (sock->state == SS_DISCONNECTING) {
1189                                 err = -ENOTCONN;
1190                                 break;
1191                         }
1192                         release_sock(sk);
1193                         timeo = schedule_timeout(timeo);
1194                         lock_sock(sk);
1195                 }
1196                 err = 0;
1197                 if (!skb_queue_empty(&sk->sk_receive_queue))
1198                         break;
1199                 err = sock_intr_errno(timeo);
1200                 if (signal_pending(current))
1201                         break;
1202                 err = -EAGAIN;
1203                 if (!timeo)
1204                         break;
1205         }
1206         finish_wait(sk_sleep(sk), &wait);
1207         *timeop = timeo;
1208         return err;
1209 }
1210
1211 /**
1212  * tipc_recvmsg - receive packet-oriented message
1213  * @iocb: (unused)
1214  * @m: descriptor for message info
1215  * @buf_len: total size of user buffer area
1216  * @flags: receive flags
1217  *
1218  * Used for SOCK_DGRAM, SOCK_RDM, and SOCK_SEQPACKET messages.
1219  * If the complete message doesn't fit in user area, truncate it.
1220  *
1221  * Returns size of returned message data, errno otherwise
1222  */
1223 static int tipc_recvmsg(struct kiocb *iocb, struct socket *sock,
1224                         struct msghdr *m, size_t buf_len, int flags)
1225 {
1226         struct sock *sk = sock->sk;
1227         struct tipc_sock *tsk = tipc_sk(sk);
1228         struct tipc_port *port = &tsk->port;
1229         struct sk_buff *buf;
1230         struct tipc_msg *msg;
1231         long timeo;
1232         unsigned int sz;
1233         u32 err;
1234         int res;
1235
1236         /* Catch invalid receive requests */
1237         if (unlikely(!buf_len))
1238                 return -EINVAL;
1239
1240         lock_sock(sk);
1241
1242         if (unlikely(sock->state == SS_UNCONNECTED)) {
1243                 res = -ENOTCONN;
1244                 goto exit;
1245         }
1246
1247         timeo = sock_rcvtimeo(sk, flags & MSG_DONTWAIT);
1248 restart:
1249
1250         /* Look for a message in receive queue; wait if necessary */
1251         res = tipc_wait_for_rcvmsg(sock, &timeo);
1252         if (res)
1253                 goto exit;
1254
1255         /* Look at first message in receive queue */
1256         buf = skb_peek(&sk->sk_receive_queue);
1257         msg = buf_msg(buf);
1258         sz = msg_data_sz(msg);
1259         err = msg_errcode(msg);
1260
1261         /* Discard an empty non-errored message & try again */
1262         if ((!sz) && (!err)) {
1263                 advance_rx_queue(sk);
1264                 goto restart;
1265         }
1266
1267         /* Capture sender's address (optional) */
1268         set_orig_addr(m, msg);
1269
1270         /* Capture ancillary data (optional) */
1271         res = anc_data_recv(m, msg, port);
1272         if (res)
1273                 goto exit;
1274
1275         /* Capture message data (if valid) & compute return value (always) */
1276         if (!err) {
1277                 if (unlikely(buf_len < sz)) {
1278                         sz = buf_len;
1279                         m->msg_flags |= MSG_TRUNC;
1280                 }
1281                 res = skb_copy_datagram_iovec(buf, msg_hdr_sz(msg),
1282                                               m->msg_iov, sz);
1283                 if (res)
1284                         goto exit;
1285                 res = sz;
1286         } else {
1287                 if ((sock->state == SS_READY) ||
1288                     ((err == TIPC_CONN_SHUTDOWN) || m->msg_control))
1289                         res = 0;
1290                 else
1291                         res = -ECONNRESET;
1292         }
1293
1294         /* Consume received message (optional) */
1295         if (likely(!(flags & MSG_PEEK))) {
1296                 if ((sock->state != SS_READY) &&
1297                     (++tsk->rcv_unacked >= TIPC_CONNACK_INTV)) {
1298                         tipc_sk_send_ack(port, tsk->rcv_unacked);
1299                         tsk->rcv_unacked = 0;
1300                 }
1301                 advance_rx_queue(sk);
1302         }
1303 exit:
1304         release_sock(sk);
1305         return res;
1306 }
1307
1308 /**
1309  * tipc_recv_stream - receive stream-oriented data
1310  * @iocb: (unused)
1311  * @m: descriptor for message info
1312  * @buf_len: total size of user buffer area
1313  * @flags: receive flags
1314  *
1315  * Used for SOCK_STREAM messages only.  If not enough data is available
1316  * will optionally wait for more; never truncates data.
1317  *
1318  * Returns size of returned message data, errno otherwise
1319  */
1320 static int tipc_recv_stream(struct kiocb *iocb, struct socket *sock,
1321                             struct msghdr *m, size_t buf_len, int flags)
1322 {
1323         struct sock *sk = sock->sk;
1324         struct tipc_sock *tsk = tipc_sk(sk);
1325         struct tipc_port *port = &tsk->port;
1326         struct sk_buff *buf;
1327         struct tipc_msg *msg;
1328         long timeo;
1329         unsigned int sz;
1330         int sz_to_copy, target, needed;
1331         int sz_copied = 0;
1332         u32 err;
1333         int res = 0;
1334
1335         /* Catch invalid receive attempts */
1336         if (unlikely(!buf_len))
1337                 return -EINVAL;
1338
1339         lock_sock(sk);
1340
1341         if (unlikely(sock->state == SS_UNCONNECTED)) {
1342                 res = -ENOTCONN;
1343                 goto exit;
1344         }
1345
1346         target = sock_rcvlowat(sk, flags & MSG_WAITALL, buf_len);
1347         timeo = sock_rcvtimeo(sk, flags & MSG_DONTWAIT);
1348
1349 restart:
1350         /* Look for a message in receive queue; wait if necessary */
1351         res = tipc_wait_for_rcvmsg(sock, &timeo);
1352         if (res)
1353                 goto exit;
1354
1355         /* Look at first message in receive queue */
1356         buf = skb_peek(&sk->sk_receive_queue);
1357         msg = buf_msg(buf);
1358         sz = msg_data_sz(msg);
1359         err = msg_errcode(msg);
1360
1361         /* Discard an empty non-errored message & try again */
1362         if ((!sz) && (!err)) {
1363                 advance_rx_queue(sk);
1364                 goto restart;
1365         }
1366
1367         /* Optionally capture sender's address & ancillary data of first msg */
1368         if (sz_copied == 0) {
1369                 set_orig_addr(m, msg);
1370                 res = anc_data_recv(m, msg, port);
1371                 if (res)
1372                         goto exit;
1373         }
1374
1375         /* Capture message data (if valid) & compute return value (always) */
1376         if (!err) {
1377                 u32 offset = (u32)(unsigned long)(TIPC_SKB_CB(buf)->handle);
1378
1379                 sz -= offset;
1380                 needed = (buf_len - sz_copied);
1381                 sz_to_copy = (sz <= needed) ? sz : needed;
1382
1383                 res = skb_copy_datagram_iovec(buf, msg_hdr_sz(msg) + offset,
1384                                               m->msg_iov, sz_to_copy);
1385                 if (res)
1386                         goto exit;
1387
1388                 sz_copied += sz_to_copy;
1389
1390                 if (sz_to_copy < sz) {
1391                         if (!(flags & MSG_PEEK))
1392                                 TIPC_SKB_CB(buf)->handle =
1393                                 (void *)(unsigned long)(offset + sz_to_copy);
1394                         goto exit;
1395                 }
1396         } else {
1397                 if (sz_copied != 0)
1398                         goto exit; /* can't add error msg to valid data */
1399
1400                 if ((err == TIPC_CONN_SHUTDOWN) || m->msg_control)
1401                         res = 0;
1402                 else
1403                         res = -ECONNRESET;
1404         }
1405
1406         /* Consume received message (optional) */
1407         if (likely(!(flags & MSG_PEEK))) {
1408                 if (unlikely(++tsk->rcv_unacked >= TIPC_CONNACK_INTV)) {
1409                         tipc_sk_send_ack(port, tsk->rcv_unacked);
1410                         tsk->rcv_unacked = 0;
1411                 }
1412                 advance_rx_queue(sk);
1413         }
1414
1415         /* Loop around if more data is required */
1416         if ((sz_copied < buf_len) &&    /* didn't get all requested data */
1417             (!skb_queue_empty(&sk->sk_receive_queue) ||
1418             (sz_copied < target)) &&    /* and more is ready or required */
1419             (!(flags & MSG_PEEK)) &&    /* and aren't just peeking at data */
1420             (!err))                     /* and haven't reached a FIN */
1421                 goto restart;
1422
1423 exit:
1424         release_sock(sk);
1425         return sz_copied ? sz_copied : res;
1426 }
1427
1428 /**
1429  * tipc_write_space - wake up thread if port congestion is released
1430  * @sk: socket
1431  */
1432 static void tipc_write_space(struct sock *sk)
1433 {
1434         struct socket_wq *wq;
1435
1436         rcu_read_lock();
1437         wq = rcu_dereference(sk->sk_wq);
1438         if (wq_has_sleeper(wq))
1439                 wake_up_interruptible_sync_poll(&wq->wait, POLLOUT |
1440                                                 POLLWRNORM | POLLWRBAND);
1441         rcu_read_unlock();
1442 }
1443
1444 /**
1445  * tipc_data_ready - wake up threads to indicate messages have been received
1446  * @sk: socket
1447  * @len: the length of messages
1448  */
1449 static void tipc_data_ready(struct sock *sk)
1450 {
1451         struct socket_wq *wq;
1452
1453         rcu_read_lock();
1454         wq = rcu_dereference(sk->sk_wq);
1455         if (wq_has_sleeper(wq))
1456                 wake_up_interruptible_sync_poll(&wq->wait, POLLIN |
1457                                                 POLLRDNORM | POLLRDBAND);
1458         rcu_read_unlock();
1459 }
1460
1461 /**
1462  * filter_connect - Handle all incoming messages for a connection-based socket
1463  * @tsk: TIPC socket
1464  * @msg: message
1465  *
1466  * Returns 0 (TIPC_OK) if everyting ok, -TIPC_ERR_NO_PORT otherwise
1467  */
1468 static int filter_connect(struct tipc_sock *tsk, struct sk_buff **buf)
1469 {
1470         struct sock *sk = &tsk->sk;
1471         struct tipc_port *port = &tsk->port;
1472         struct socket *sock = sk->sk_socket;
1473         struct tipc_msg *msg = buf_msg(*buf);
1474
1475         int retval = -TIPC_ERR_NO_PORT;
1476
1477         if (msg_mcast(msg))
1478                 return retval;
1479
1480         switch ((int)sock->state) {
1481         case SS_CONNECTED:
1482                 /* Accept only connection-based messages sent by peer */
1483                 if (tipc_sk_peer_msg(tsk, msg)) {
1484                         if (unlikely(msg_errcode(msg))) {
1485                                 sock->state = SS_DISCONNECTING;
1486                                 port->connected = 0;
1487                                 /* let timer expire on it's own */
1488                                 tipc_node_remove_conn(tipc_port_peernode(port),
1489                                                       port->ref);
1490                         }
1491                         retval = TIPC_OK;
1492                 }
1493                 break;
1494         case SS_CONNECTING:
1495                 /* Accept only ACK or NACK message */
1496
1497                 if (unlikely(!msg_connected(msg)))
1498                         break;
1499
1500                 if (unlikely(msg_errcode(msg))) {
1501                         sock->state = SS_DISCONNECTING;
1502                         sk->sk_err = ECONNREFUSED;
1503                         retval = TIPC_OK;
1504                         break;
1505                 }
1506
1507                 if (unlikely(msg_importance(msg) > TIPC_CRITICAL_IMPORTANCE)) {
1508                         sock->state = SS_DISCONNECTING;
1509                         sk->sk_err = EINVAL;
1510                         retval = TIPC_OK;
1511                         break;
1512                 }
1513
1514                 tipc_sk_finish_conn(port, msg_origport(msg), msg_orignode(msg));
1515                 msg_set_importance(&port->phdr, msg_importance(msg));
1516                 sock->state = SS_CONNECTED;
1517
1518                 /* If an incoming message is an 'ACK-', it should be
1519                  * discarded here because it doesn't contain useful
1520                  * data. In addition, we should try to wake up
1521                  * connect() routine if sleeping.
1522                  */
1523                 if (msg_data_sz(msg) == 0) {
1524                         kfree_skb(*buf);
1525                         *buf = NULL;
1526                         if (waitqueue_active(sk_sleep(sk)))
1527                                 wake_up_interruptible(sk_sleep(sk));
1528                 }
1529                 retval = TIPC_OK;
1530                 break;
1531         case SS_LISTENING:
1532         case SS_UNCONNECTED:
1533                 /* Accept only SYN message */
1534                 if (!msg_connected(msg) && !(msg_errcode(msg)))
1535                         retval = TIPC_OK;
1536                 break;
1537         case SS_DISCONNECTING:
1538                 break;
1539         default:
1540                 pr_err("Unknown socket state %u\n", sock->state);
1541         }
1542         return retval;
1543 }
1544
1545 /**
1546  * rcvbuf_limit - get proper overload limit of socket receive queue
1547  * @sk: socket
1548  * @buf: message
1549  *
1550  * For all connection oriented messages, irrespective of importance,
1551  * the default overload value (i.e. 67MB) is set as limit.
1552  *
1553  * For all connectionless messages, by default new queue limits are
1554  * as belows:
1555  *
1556  * TIPC_LOW_IMPORTANCE       (4 MB)
1557  * TIPC_MEDIUM_IMPORTANCE    (8 MB)
1558  * TIPC_HIGH_IMPORTANCE      (16 MB)
1559  * TIPC_CRITICAL_IMPORTANCE  (32 MB)
1560  *
1561  * Returns overload limit according to corresponding message importance
1562  */
1563 static unsigned int rcvbuf_limit(struct sock *sk, struct sk_buff *buf)
1564 {
1565         struct tipc_msg *msg = buf_msg(buf);
1566
1567         if (msg_connected(msg))
1568                 return sysctl_tipc_rmem[2];
1569
1570         return sk->sk_rcvbuf >> TIPC_CRITICAL_IMPORTANCE <<
1571                 msg_importance(msg);
1572 }
1573
1574 /**
1575  * filter_rcv - validate incoming message
1576  * @sk: socket
1577  * @buf: message
1578  *
1579  * Enqueues message on receive queue if acceptable; optionally handles
1580  * disconnect indication for a connected socket.
1581  *
1582  * Called with socket lock already taken; port lock may also be taken.
1583  *
1584  * Returns 0 (TIPC_OK) if message was consumed, -TIPC error code if message
1585  * to be rejected, 1 (TIPC_FWD_MSG) if (CONN_MANAGER) message to be forwarded
1586  */
1587 static int filter_rcv(struct sock *sk, struct sk_buff *buf)
1588 {
1589         struct socket *sock = sk->sk_socket;
1590         struct tipc_sock *tsk = tipc_sk(sk);
1591         struct tipc_msg *msg = buf_msg(buf);
1592         unsigned int limit = rcvbuf_limit(sk, buf);
1593         u32 onode;
1594         int rc = TIPC_OK;
1595
1596         if (unlikely(msg_user(msg) == CONN_MANAGER))
1597                 return tipc_sk_proto_rcv(tsk, &onode, buf);
1598
1599         if (unlikely(msg_user(msg) == SOCK_WAKEUP)) {
1600                 kfree_skb(buf);
1601                 tsk->link_cong = 0;
1602                 sk->sk_write_space(sk);
1603                 return TIPC_OK;
1604         }
1605
1606         /* Reject message if it is wrong sort of message for socket */
1607         if (msg_type(msg) > TIPC_DIRECT_MSG)
1608                 return -TIPC_ERR_NO_PORT;
1609
1610         if (sock->state == SS_READY) {
1611                 if (msg_connected(msg))
1612                         return -TIPC_ERR_NO_PORT;
1613         } else {
1614                 rc = filter_connect(tsk, &buf);
1615                 if (rc != TIPC_OK || buf == NULL)
1616                         return rc;
1617         }
1618
1619         /* Reject message if there isn't room to queue it */
1620         if (sk_rmem_alloc_get(sk) + buf->truesize >= limit)
1621                 return -TIPC_ERR_OVERLOAD;
1622
1623         /* Enqueue message */
1624         TIPC_SKB_CB(buf)->handle = NULL;
1625         __skb_queue_tail(&sk->sk_receive_queue, buf);
1626         skb_set_owner_r(buf, sk);
1627
1628         sk->sk_data_ready(sk);
1629         return TIPC_OK;
1630 }
1631
1632 /**
1633  * tipc_backlog_rcv - handle incoming message from backlog queue
1634  * @sk: socket
1635  * @buf: message
1636  *
1637  * Caller must hold socket lock, but not port lock.
1638  *
1639  * Returns 0
1640  */
1641 static int tipc_backlog_rcv(struct sock *sk, struct sk_buff *buf)
1642 {
1643         int rc;
1644         u32 onode;
1645         struct tipc_sock *tsk = tipc_sk(sk);
1646         uint truesize = buf->truesize;
1647
1648         rc = filter_rcv(sk, buf);
1649
1650         if (likely(!rc)) {
1651                 if (atomic_read(&tsk->dupl_rcvcnt) < TIPC_CONN_OVERLOAD_LIMIT)
1652                         atomic_add(truesize, &tsk->dupl_rcvcnt);
1653                 return 0;
1654         }
1655
1656         if ((rc < 0) && !tipc_msg_reverse(buf, &onode, -rc))
1657                 return 0;
1658
1659         tipc_link_xmit(buf, onode, 0);
1660
1661         return 0;
1662 }
1663
1664 /**
1665  * tipc_sk_rcv - handle incoming message
1666  * @buf: buffer containing arriving message
1667  * Consumes buffer
1668  * Returns 0 if success, or errno: -EHOSTUNREACH
1669  */
1670 int tipc_sk_rcv(struct sk_buff *buf)
1671 {
1672         struct tipc_sock *tsk;
1673         struct tipc_port *port;
1674         struct sock *sk;
1675         u32 dport = msg_destport(buf_msg(buf));
1676         int rc = TIPC_OK;
1677         uint limit;
1678         u32 dnode;
1679
1680         /* Validate destination and message */
1681         tsk = tipc_sk_get(dport);
1682         if (unlikely(!tsk)) {
1683                 rc = tipc_msg_eval(buf, &dnode);
1684                 goto exit;
1685         }
1686         port = &tsk->port;
1687         sk = &tsk->sk;
1688
1689         /* Queue message */
1690         bh_lock_sock(sk);
1691
1692         if (!sock_owned_by_user(sk)) {
1693                 rc = filter_rcv(sk, buf);
1694         } else {
1695                 if (sk->sk_backlog.len == 0)
1696                         atomic_set(&tsk->dupl_rcvcnt, 0);
1697                 limit = rcvbuf_limit(sk, buf) + atomic_read(&tsk->dupl_rcvcnt);
1698                 if (sk_add_backlog(sk, buf, limit))
1699                         rc = -TIPC_ERR_OVERLOAD;
1700         }
1701         bh_unlock_sock(sk);
1702         tipc_sk_put(tsk);
1703         if (likely(!rc))
1704                 return 0;
1705 exit:
1706         if ((rc < 0) && !tipc_msg_reverse(buf, &dnode, -rc))
1707                 return -EHOSTUNREACH;
1708
1709         tipc_link_xmit(buf, dnode, 0);
1710         return (rc < 0) ? -EHOSTUNREACH : 0;
1711 }
1712
1713 static int tipc_wait_for_connect(struct socket *sock, long *timeo_p)
1714 {
1715         struct sock *sk = sock->sk;
1716         DEFINE_WAIT(wait);
1717         int done;
1718
1719         do {
1720                 int err = sock_error(sk);
1721                 if (err)
1722                         return err;
1723                 if (!*timeo_p)
1724                         return -ETIMEDOUT;
1725                 if (signal_pending(current))
1726                         return sock_intr_errno(*timeo_p);
1727
1728                 prepare_to_wait(sk_sleep(sk), &wait, TASK_INTERRUPTIBLE);
1729                 done = sk_wait_event(sk, timeo_p, sock->state != SS_CONNECTING);
1730                 finish_wait(sk_sleep(sk), &wait);
1731         } while (!done);
1732         return 0;
1733 }
1734
1735 /**
1736  * tipc_connect - establish a connection to another TIPC port
1737  * @sock: socket structure
1738  * @dest: socket address for destination port
1739  * @destlen: size of socket address data structure
1740  * @flags: file-related flags associated with socket
1741  *
1742  * Returns 0 on success, errno otherwise
1743  */
1744 static int tipc_connect(struct socket *sock, struct sockaddr *dest,
1745                         int destlen, int flags)
1746 {
1747         struct sock *sk = sock->sk;
1748         struct sockaddr_tipc *dst = (struct sockaddr_tipc *)dest;
1749         struct msghdr m = {NULL,};
1750         long timeout = (flags & O_NONBLOCK) ? 0 : tipc_sk(sk)->conn_timeout;
1751         socket_state previous;
1752         int res;
1753
1754         lock_sock(sk);
1755
1756         /* For now, TIPC does not allow use of connect() with DGRAM/RDM types */
1757         if (sock->state == SS_READY) {
1758                 res = -EOPNOTSUPP;
1759                 goto exit;
1760         }
1761
1762         /*
1763          * Reject connection attempt using multicast address
1764          *
1765          * Note: send_msg() validates the rest of the address fields,
1766          *       so there's no need to do it here
1767          */
1768         if (dst->addrtype == TIPC_ADDR_MCAST) {
1769                 res = -EINVAL;
1770                 goto exit;
1771         }
1772
1773         previous = sock->state;
1774         switch (sock->state) {
1775         case SS_UNCONNECTED:
1776                 /* Send a 'SYN-' to destination */
1777                 m.msg_name = dest;
1778                 m.msg_namelen = destlen;
1779
1780                 /* If connect is in non-blocking case, set MSG_DONTWAIT to
1781                  * indicate send_msg() is never blocked.
1782                  */
1783                 if (!timeout)
1784                         m.msg_flags = MSG_DONTWAIT;
1785
1786                 res = tipc_sendmsg(NULL, sock, &m, 0);
1787                 if ((res < 0) && (res != -EWOULDBLOCK))
1788                         goto exit;
1789
1790                 /* Just entered SS_CONNECTING state; the only
1791                  * difference is that return value in non-blocking
1792                  * case is EINPROGRESS, rather than EALREADY.
1793                  */
1794                 res = -EINPROGRESS;
1795         case SS_CONNECTING:
1796                 if (previous == SS_CONNECTING)
1797                         res = -EALREADY;
1798                 if (!timeout)
1799                         goto exit;
1800                 timeout = msecs_to_jiffies(timeout);
1801                 /* Wait until an 'ACK' or 'RST' arrives, or a timeout occurs */
1802                 res = tipc_wait_for_connect(sock, &timeout);
1803                 break;
1804         case SS_CONNECTED:
1805                 res = -EISCONN;
1806                 break;
1807         default:
1808                 res = -EINVAL;
1809                 break;
1810         }
1811 exit:
1812         release_sock(sk);
1813         return res;
1814 }
1815
1816 /**
1817  * tipc_listen - allow socket to listen for incoming connections
1818  * @sock: socket structure
1819  * @len: (unused)
1820  *
1821  * Returns 0 on success, errno otherwise
1822  */
1823 static int tipc_listen(struct socket *sock, int len)
1824 {
1825         struct sock *sk = sock->sk;
1826         int res;
1827
1828         lock_sock(sk);
1829
1830         if (sock->state != SS_UNCONNECTED)
1831                 res = -EINVAL;
1832         else {
1833                 sock->state = SS_LISTENING;
1834                 res = 0;
1835         }
1836
1837         release_sock(sk);
1838         return res;
1839 }
1840
1841 static int tipc_wait_for_accept(struct socket *sock, long timeo)
1842 {
1843         struct sock *sk = sock->sk;
1844         DEFINE_WAIT(wait);
1845         int err;
1846
1847         /* True wake-one mechanism for incoming connections: only
1848          * one process gets woken up, not the 'whole herd'.
1849          * Since we do not 'race & poll' for established sockets
1850          * anymore, the common case will execute the loop only once.
1851         */
1852         for (;;) {
1853                 prepare_to_wait_exclusive(sk_sleep(sk), &wait,
1854                                           TASK_INTERRUPTIBLE);
1855                 if (timeo && skb_queue_empty(&sk->sk_receive_queue)) {
1856                         release_sock(sk);
1857                         timeo = schedule_timeout(timeo);
1858                         lock_sock(sk);
1859                 }
1860                 err = 0;
1861                 if (!skb_queue_empty(&sk->sk_receive_queue))
1862                         break;
1863                 err = -EINVAL;
1864                 if (sock->state != SS_LISTENING)
1865                         break;
1866                 err = sock_intr_errno(timeo);
1867                 if (signal_pending(current))
1868                         break;
1869                 err = -EAGAIN;
1870                 if (!timeo)
1871                         break;
1872         }
1873         finish_wait(sk_sleep(sk), &wait);
1874         return err;
1875 }
1876
1877 /**
1878  * tipc_accept - wait for connection request
1879  * @sock: listening socket
1880  * @newsock: new socket that is to be connected
1881  * @flags: file-related flags associated with socket
1882  *
1883  * Returns 0 on success, errno otherwise
1884  */
1885 static int tipc_accept(struct socket *sock, struct socket *new_sock, int flags)
1886 {
1887         struct sock *new_sk, *sk = sock->sk;
1888         struct sk_buff *buf;
1889         struct tipc_port *new_port;
1890         struct tipc_msg *msg;
1891         long timeo;
1892         int res;
1893
1894         lock_sock(sk);
1895
1896         if (sock->state != SS_LISTENING) {
1897                 res = -EINVAL;
1898                 goto exit;
1899         }
1900         timeo = sock_rcvtimeo(sk, flags & O_NONBLOCK);
1901         res = tipc_wait_for_accept(sock, timeo);
1902         if (res)
1903                 goto exit;
1904
1905         buf = skb_peek(&sk->sk_receive_queue);
1906
1907         res = tipc_sk_create(sock_net(sock->sk), new_sock, 0, 1);
1908         if (res)
1909                 goto exit;
1910
1911         new_sk = new_sock->sk;
1912         new_port = &tipc_sk(new_sk)->port;
1913         msg = buf_msg(buf);
1914
1915         /* we lock on new_sk; but lockdep sees the lock on sk */
1916         lock_sock_nested(new_sk, SINGLE_DEPTH_NESTING);
1917
1918         /*
1919          * Reject any stray messages received by new socket
1920          * before the socket lock was taken (very, very unlikely)
1921          */
1922         reject_rx_queue(new_sk);
1923
1924         /* Connect new socket to it's peer */
1925         tipc_sk_finish_conn(new_port, msg_origport(msg), msg_orignode(msg));
1926         new_sock->state = SS_CONNECTED;
1927
1928         tipc_port_set_importance(new_port, msg_importance(msg));
1929         if (msg_named(msg)) {
1930                 new_port->conn_type = msg_nametype(msg);
1931                 new_port->conn_instance = msg_nameinst(msg);
1932         }
1933
1934         /*
1935          * Respond to 'SYN-' by discarding it & returning 'ACK'-.
1936          * Respond to 'SYN+' by queuing it on new socket.
1937          */
1938         if (!msg_data_sz(msg)) {
1939                 struct msghdr m = {NULL,};
1940
1941                 advance_rx_queue(sk);
1942                 tipc_send_packet(NULL, new_sock, &m, 0);
1943         } else {
1944                 __skb_dequeue(&sk->sk_receive_queue);
1945                 __skb_queue_head(&new_sk->sk_receive_queue, buf);
1946                 skb_set_owner_r(buf, new_sk);
1947         }
1948         release_sock(new_sk);
1949 exit:
1950         release_sock(sk);
1951         return res;
1952 }
1953
1954 /**
1955  * tipc_shutdown - shutdown socket connection
1956  * @sock: socket structure
1957  * @how: direction to close (must be SHUT_RDWR)
1958  *
1959  * Terminates connection (if necessary), then purges socket's receive queue.
1960  *
1961  * Returns 0 on success, errno otherwise
1962  */
1963 static int tipc_shutdown(struct socket *sock, int how)
1964 {
1965         struct sock *sk = sock->sk;
1966         struct tipc_sock *tsk = tipc_sk(sk);
1967         struct tipc_port *port = &tsk->port;
1968         struct sk_buff *buf;
1969         u32 dnode;
1970         int res;
1971
1972         if (how != SHUT_RDWR)
1973                 return -EINVAL;
1974
1975         lock_sock(sk);
1976
1977         switch (sock->state) {
1978         case SS_CONNECTING:
1979         case SS_CONNECTED:
1980
1981 restart:
1982                 /* Disconnect and send a 'FIN+' or 'FIN-' message to peer */
1983                 buf = __skb_dequeue(&sk->sk_receive_queue);
1984                 if (buf) {
1985                         if (TIPC_SKB_CB(buf)->handle != NULL) {
1986                                 kfree_skb(buf);
1987                                 goto restart;
1988                         }
1989                         if (tipc_msg_reverse(buf, &dnode, TIPC_CONN_SHUTDOWN))
1990                                 tipc_link_xmit(buf, dnode, port->ref);
1991                         tipc_node_remove_conn(dnode, port->ref);
1992                 } else {
1993                         dnode = tipc_port_peernode(port);
1994                         buf = tipc_msg_create(TIPC_CRITICAL_IMPORTANCE,
1995                                               TIPC_CONN_MSG, SHORT_H_SIZE,
1996                                               0, dnode, tipc_own_addr,
1997                                               tipc_port_peerport(port),
1998                                               port->ref, TIPC_CONN_SHUTDOWN);
1999                         tipc_link_xmit(buf, dnode, port->ref);
2000                 }
2001                 port->connected = 0;
2002                 sock->state = SS_DISCONNECTING;
2003                 tipc_node_remove_conn(dnode, port->ref);
2004                 /* fall through */
2005
2006         case SS_DISCONNECTING:
2007
2008                 /* Discard any unreceived messages */
2009                 __skb_queue_purge(&sk->sk_receive_queue);
2010
2011                 /* Wake up anyone sleeping in poll */
2012                 sk->sk_state_change(sk);
2013                 res = 0;
2014                 break;
2015
2016         default:
2017                 res = -ENOTCONN;
2018         }
2019
2020         release_sock(sk);
2021         return res;
2022 }
2023
2024 static void tipc_sk_timeout(unsigned long ref)
2025 {
2026         struct tipc_sock *tsk;
2027         struct tipc_port *port;
2028         struct sock *sk;
2029         struct sk_buff *buf = NULL;
2030         u32 peer_port, peer_node;
2031
2032         tsk = tipc_sk_get(ref);
2033         if (!tsk)
2034                 goto exit;
2035         sk = &tsk->sk;
2036         port = &tsk->port;
2037
2038         bh_lock_sock(sk);
2039         if (!port->connected) {
2040                 bh_unlock_sock(sk);
2041                 goto exit;
2042         }
2043         peer_port = tipc_port_peerport(port);
2044         peer_node = tipc_port_peernode(port);
2045
2046         if (port->probing_state == TIPC_CONN_PROBING) {
2047                 /* Previous probe not answered -> self abort */
2048                 buf = tipc_msg_create(TIPC_CRITICAL_IMPORTANCE, TIPC_CONN_MSG,
2049                                       SHORT_H_SIZE, 0, tipc_own_addr,
2050                                       peer_node, ref, peer_port,
2051                                       TIPC_ERR_NO_PORT);
2052         } else {
2053                 buf = tipc_msg_create(CONN_MANAGER, CONN_PROBE, INT_H_SIZE,
2054                                       0, peer_node, tipc_own_addr,
2055                                       peer_port, ref, TIPC_OK);
2056                 port->probing_state = TIPC_CONN_PROBING;
2057                 k_start_timer(&port->timer, port->probing_interval);
2058         }
2059         bh_unlock_sock(sk);
2060         if (buf)
2061                 tipc_link_xmit(buf, peer_node, ref);
2062 exit:
2063         tipc_sk_put(tsk);
2064 }
2065
2066 static int tipc_sk_publish(struct tipc_port *port, uint scope,
2067                            struct tipc_name_seq const *seq)
2068 {
2069         struct publication *publ;
2070         u32 key;
2071
2072         if (port->connected)
2073                 return -EINVAL;
2074         key = port->ref + port->pub_count + 1;
2075         if (key == port->ref)
2076                 return -EADDRINUSE;
2077
2078         publ = tipc_nametbl_publish(seq->type, seq->lower, seq->upper,
2079                                     scope, port->ref, key);
2080         if (unlikely(!publ))
2081                 return -EINVAL;
2082
2083         list_add(&publ->pport_list, &port->publications);
2084         port->pub_count++;
2085         port->published = 1;
2086         return 0;
2087 }
2088
2089 static int tipc_sk_withdraw(struct tipc_port *port, uint scope,
2090                             struct tipc_name_seq const *seq)
2091 {
2092         struct publication *publ;
2093         struct publication *safe;
2094         int rc = -EINVAL;
2095
2096         list_for_each_entry_safe(publ, safe, &port->publications, pport_list) {
2097                 if (seq) {
2098                         if (publ->scope != scope)
2099                                 continue;
2100                         if (publ->type != seq->type)
2101                                 continue;
2102                         if (publ->lower != seq->lower)
2103                                 continue;
2104                         if (publ->upper != seq->upper)
2105                                 break;
2106                         tipc_nametbl_withdraw(publ->type, publ->lower,
2107                                               publ->ref, publ->key);
2108                         rc = 0;
2109                         break;
2110                 }
2111                 tipc_nametbl_withdraw(publ->type, publ->lower,
2112                                       publ->ref, publ->key);
2113                 rc = 0;
2114         }
2115         if (list_empty(&port->publications))
2116                 port->published = 0;
2117         return rc;
2118 }
2119
2120 static int tipc_sk_show(struct tipc_port *port, char *buf,
2121                         int len, int full_id)
2122 {
2123         struct publication *publ;
2124         int ret;
2125
2126         if (full_id)
2127                 ret = tipc_snprintf(buf, len, "<%u.%u.%u:%u>:",
2128                                     tipc_zone(tipc_own_addr),
2129                                     tipc_cluster(tipc_own_addr),
2130                                     tipc_node(tipc_own_addr), port->ref);
2131         else
2132                 ret = tipc_snprintf(buf, len, "%-10u:", port->ref);
2133
2134         if (port->connected) {
2135                 u32 dport = tipc_port_peerport(port);
2136                 u32 destnode = tipc_port_peernode(port);
2137
2138                 ret += tipc_snprintf(buf + ret, len - ret,
2139                                      " connected to <%u.%u.%u:%u>",
2140                                      tipc_zone(destnode),
2141                                      tipc_cluster(destnode),
2142                                      tipc_node(destnode), dport);
2143                 if (port->conn_type != 0)
2144                         ret += tipc_snprintf(buf + ret, len - ret,
2145                                              " via {%u,%u}", port->conn_type,
2146                                              port->conn_instance);
2147         } else if (port->published) {
2148                 ret += tipc_snprintf(buf + ret, len - ret, " bound to");
2149                 list_for_each_entry(publ, &port->publications, pport_list) {
2150                         if (publ->lower == publ->upper)
2151                                 ret += tipc_snprintf(buf + ret, len - ret,
2152                                                      " {%u,%u}", publ->type,
2153                                                      publ->lower);
2154                         else
2155                                 ret += tipc_snprintf(buf + ret, len - ret,
2156                                                      " {%u,%u,%u}", publ->type,
2157                                                      publ->lower, publ->upper);
2158                 }
2159         }
2160         ret += tipc_snprintf(buf + ret, len - ret, "\n");
2161         return ret;
2162 }
2163
2164 struct sk_buff *tipc_sk_socks_show(void)
2165 {
2166         struct sk_buff *buf;
2167         struct tlv_desc *rep_tlv;
2168         char *pb;
2169         int pb_len;
2170         struct tipc_sock *tsk;
2171         int str_len = 0;
2172         u32 ref = 0;
2173
2174         buf = tipc_cfg_reply_alloc(TLV_SPACE(ULTRA_STRING_MAX_LEN));
2175         if (!buf)
2176                 return NULL;
2177         rep_tlv = (struct tlv_desc *)buf->data;
2178         pb = TLV_DATA(rep_tlv);
2179         pb_len = ULTRA_STRING_MAX_LEN;
2180
2181         tsk = tipc_sk_get_next(&ref);
2182         for (; tsk; tsk = tipc_sk_get_next(&ref)) {
2183                 lock_sock(&tsk->sk);
2184                 str_len += tipc_sk_show(&tsk->port, pb + str_len,
2185                                         pb_len - str_len, 0);
2186                 release_sock(&tsk->sk);
2187                 tipc_sk_put(tsk);
2188         }
2189         str_len += 1;   /* for "\0" */
2190         skb_put(buf, TLV_SPACE(str_len));
2191         TLV_SET(rep_tlv, TIPC_TLV_ULTRA_STRING, NULL, str_len);
2192
2193         return buf;
2194 }
2195
2196 /* tipc_sk_reinit: set non-zero address in all existing sockets
2197  *                 when we go from standalone to network mode.
2198  */
2199 void tipc_sk_reinit(void)
2200 {
2201         struct tipc_msg *msg;
2202         u32 ref = 0;
2203         struct tipc_sock *tsk = tipc_sk_get_next(&ref);
2204
2205         for (; tsk; tsk = tipc_sk_get_next(&ref)) {
2206                 lock_sock(&tsk->sk);
2207                 msg = &tsk->port.phdr;
2208                 msg_set_prevnode(msg, tipc_own_addr);
2209                 msg_set_orignode(msg, tipc_own_addr);
2210                 release_sock(&tsk->sk);
2211                 tipc_sk_put(tsk);
2212         }
2213 }
2214
2215 /**
2216  * tipc_setsockopt - set socket option
2217  * @sock: socket structure
2218  * @lvl: option level
2219  * @opt: option identifier
2220  * @ov: pointer to new option value
2221  * @ol: length of option value
2222  *
2223  * For stream sockets only, accepts and ignores all IPPROTO_TCP options
2224  * (to ease compatibility).
2225  *
2226  * Returns 0 on success, errno otherwise
2227  */
2228 static int tipc_setsockopt(struct socket *sock, int lvl, int opt,
2229                            char __user *ov, unsigned int ol)
2230 {
2231         struct sock *sk = sock->sk;
2232         struct tipc_sock *tsk = tipc_sk(sk);
2233         struct tipc_port *port = &tsk->port;
2234         u32 value;
2235         int res;
2236
2237         if ((lvl == IPPROTO_TCP) && (sock->type == SOCK_STREAM))
2238                 return 0;
2239         if (lvl != SOL_TIPC)
2240                 return -ENOPROTOOPT;
2241         if (ol < sizeof(value))
2242                 return -EINVAL;
2243         res = get_user(value, (u32 __user *)ov);
2244         if (res)
2245                 return res;
2246
2247         lock_sock(sk);
2248
2249         switch (opt) {
2250         case TIPC_IMPORTANCE:
2251                 res = tipc_port_set_importance(port, value);
2252                 break;
2253         case TIPC_SRC_DROPPABLE:
2254                 if (sock->type != SOCK_STREAM)
2255                         tipc_port_set_unreliable(port, value);
2256                 else
2257                         res = -ENOPROTOOPT;
2258                 break;
2259         case TIPC_DEST_DROPPABLE:
2260                 tipc_port_set_unreturnable(port, value);
2261                 break;
2262         case TIPC_CONN_TIMEOUT:
2263                 tipc_sk(sk)->conn_timeout = value;
2264                 /* no need to set "res", since already 0 at this point */
2265                 break;
2266         default:
2267                 res = -EINVAL;
2268         }
2269
2270         release_sock(sk);
2271
2272         return res;
2273 }
2274
2275 /**
2276  * tipc_getsockopt - get socket option
2277  * @sock: socket structure
2278  * @lvl: option level
2279  * @opt: option identifier
2280  * @ov: receptacle for option value
2281  * @ol: receptacle for length of option value
2282  *
2283  * For stream sockets only, returns 0 length result for all IPPROTO_TCP options
2284  * (to ease compatibility).
2285  *
2286  * Returns 0 on success, errno otherwise
2287  */
2288 static int tipc_getsockopt(struct socket *sock, int lvl, int opt,
2289                            char __user *ov, int __user *ol)
2290 {
2291         struct sock *sk = sock->sk;
2292         struct tipc_sock *tsk = tipc_sk(sk);
2293         struct tipc_port *port = &tsk->port;
2294         int len;
2295         u32 value;
2296         int res;
2297
2298         if ((lvl == IPPROTO_TCP) && (sock->type == SOCK_STREAM))
2299                 return put_user(0, ol);
2300         if (lvl != SOL_TIPC)
2301                 return -ENOPROTOOPT;
2302         res = get_user(len, ol);
2303         if (res)
2304                 return res;
2305
2306         lock_sock(sk);
2307
2308         switch (opt) {
2309         case TIPC_IMPORTANCE:
2310                 value = tipc_port_importance(port);
2311                 break;
2312         case TIPC_SRC_DROPPABLE:
2313                 value = tipc_port_unreliable(port);
2314                 break;
2315         case TIPC_DEST_DROPPABLE:
2316                 value = tipc_port_unreturnable(port);
2317                 break;
2318         case TIPC_CONN_TIMEOUT:
2319                 value = tipc_sk(sk)->conn_timeout;
2320                 /* no need to set "res", since already 0 at this point */
2321                 break;
2322         case TIPC_NODE_RECVQ_DEPTH:
2323                 value = 0; /* was tipc_queue_size, now obsolete */
2324                 break;
2325         case TIPC_SOCK_RECVQ_DEPTH:
2326                 value = skb_queue_len(&sk->sk_receive_queue);
2327                 break;
2328         default:
2329                 res = -EINVAL;
2330         }
2331
2332         release_sock(sk);
2333
2334         if (res)
2335                 return res;     /* "get" failed */
2336
2337         if (len < sizeof(value))
2338                 return -EINVAL;
2339
2340         if (copy_to_user(ov, &value, sizeof(value)))
2341                 return -EFAULT;
2342
2343         return put_user(sizeof(value), ol);
2344 }
2345
2346 static int tipc_ioctl(struct socket *sk, unsigned int cmd, unsigned long arg)
2347 {
2348         struct tipc_sioc_ln_req lnr;
2349         void __user *argp = (void __user *)arg;
2350
2351         switch (cmd) {
2352         case SIOCGETLINKNAME:
2353                 if (copy_from_user(&lnr, argp, sizeof(lnr)))
2354                         return -EFAULT;
2355                 if (!tipc_node_get_linkname(lnr.bearer_id, lnr.peer,
2356                                             lnr.linkname, TIPC_MAX_LINK_NAME)) {
2357                         if (copy_to_user(argp, &lnr, sizeof(lnr)))
2358                                 return -EFAULT;
2359                         return 0;
2360                 }
2361                 return -EADDRNOTAVAIL;
2362         default:
2363                 return -ENOIOCTLCMD;
2364         }
2365 }
2366
2367 /* Protocol switches for the various types of TIPC sockets */
2368
2369 static const struct proto_ops msg_ops = {
2370         .owner          = THIS_MODULE,
2371         .family         = AF_TIPC,
2372         .release        = tipc_release,
2373         .bind           = tipc_bind,
2374         .connect        = tipc_connect,
2375         .socketpair     = sock_no_socketpair,
2376         .accept         = sock_no_accept,
2377         .getname        = tipc_getname,
2378         .poll           = tipc_poll,
2379         .ioctl          = tipc_ioctl,
2380         .listen         = sock_no_listen,
2381         .shutdown       = tipc_shutdown,
2382         .setsockopt     = tipc_setsockopt,
2383         .getsockopt     = tipc_getsockopt,
2384         .sendmsg        = tipc_sendmsg,
2385         .recvmsg        = tipc_recvmsg,
2386         .mmap           = sock_no_mmap,
2387         .sendpage       = sock_no_sendpage
2388 };
2389
2390 static const struct proto_ops packet_ops = {
2391         .owner          = THIS_MODULE,
2392         .family         = AF_TIPC,
2393         .release        = tipc_release,
2394         .bind           = tipc_bind,
2395         .connect        = tipc_connect,
2396         .socketpair     = sock_no_socketpair,
2397         .accept         = tipc_accept,
2398         .getname        = tipc_getname,
2399         .poll           = tipc_poll,
2400         .ioctl          = tipc_ioctl,
2401         .listen         = tipc_listen,
2402         .shutdown       = tipc_shutdown,
2403         .setsockopt     = tipc_setsockopt,
2404         .getsockopt     = tipc_getsockopt,
2405         .sendmsg        = tipc_send_packet,
2406         .recvmsg        = tipc_recvmsg,
2407         .mmap           = sock_no_mmap,
2408         .sendpage       = sock_no_sendpage
2409 };
2410
2411 static const struct proto_ops stream_ops = {
2412         .owner          = THIS_MODULE,
2413         .family         = AF_TIPC,
2414         .release        = tipc_release,
2415         .bind           = tipc_bind,
2416         .connect        = tipc_connect,
2417         .socketpair     = sock_no_socketpair,
2418         .accept         = tipc_accept,
2419         .getname        = tipc_getname,
2420         .poll           = tipc_poll,
2421         .ioctl          = tipc_ioctl,
2422         .listen         = tipc_listen,
2423         .shutdown       = tipc_shutdown,
2424         .setsockopt     = tipc_setsockopt,
2425         .getsockopt     = tipc_getsockopt,
2426         .sendmsg        = tipc_send_stream,
2427         .recvmsg        = tipc_recv_stream,
2428         .mmap           = sock_no_mmap,
2429         .sendpage       = sock_no_sendpage
2430 };
2431
2432 static const struct net_proto_family tipc_family_ops = {
2433         .owner          = THIS_MODULE,
2434         .family         = AF_TIPC,
2435         .create         = tipc_sk_create
2436 };
2437
2438 static struct proto tipc_proto = {
2439         .name           = "TIPC",
2440         .owner          = THIS_MODULE,
2441         .obj_size       = sizeof(struct tipc_sock),
2442         .sysctl_rmem    = sysctl_tipc_rmem
2443 };
2444
2445 static struct proto tipc_proto_kern = {
2446         .name           = "TIPC",
2447         .obj_size       = sizeof(struct tipc_sock),
2448         .sysctl_rmem    = sysctl_tipc_rmem
2449 };
2450
2451 /**
2452  * tipc_socket_init - initialize TIPC socket interface
2453  *
2454  * Returns 0 on success, errno otherwise
2455  */
2456 int tipc_socket_init(void)
2457 {
2458         int res;
2459
2460         res = proto_register(&tipc_proto, 1);
2461         if (res) {
2462                 pr_err("Failed to register TIPC protocol type\n");
2463                 goto out;
2464         }
2465
2466         res = sock_register(&tipc_family_ops);
2467         if (res) {
2468                 pr_err("Failed to register TIPC socket type\n");
2469                 proto_unregister(&tipc_proto);
2470                 goto out;
2471         }
2472  out:
2473         return res;
2474 }
2475
2476 /**
2477  * tipc_socket_stop - stop TIPC socket interface
2478  */
2479 void tipc_socket_stop(void)
2480 {
2481         sock_unregister(tipc_family_ops.family);
2482         proto_unregister(&tipc_proto);
2483 }