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