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