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