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