Merge branch 'master' of git://git.kernel.org/pub/scm/linux/kernel/git/jkirsher/net...
[cascardo/linux.git] / net / tipc / socket.c
1 /*
2  * net/tipc/socket.c: TIPC socket API
3  *
4  * Copyright (c) 2001-2007, 2012-2014, Ericsson AB
5  * Copyright (c) 2004-2008, 2010-2013, Wind River Systems
6  * All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions are met:
10  *
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 3. Neither the names of the copyright holders nor the names of its
17  *    contributors may be used to endorse or promote products derived from
18  *    this software without specific prior written permission.
19  *
20  * Alternatively, this software may be distributed under the terms of the
21  * GNU General Public License ("GPL") version 2 as published by the Free
22  * Software Foundation.
23  *
24  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
25  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27  * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
28  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
29  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
30  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
31  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
32  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
33  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
34  * POSSIBILITY OF SUCH DAMAGE.
35  */
36
37 #include "core.h"
38 #include "name_table.h"
39 #include "node.h"
40 #include "link.h"
41 #include <linux/export.h>
42 #include "config.h"
43 #include "socket.h"
44
45 #define SS_LISTENING    -1      /* socket is listening */
46 #define SS_READY        -2      /* socket is connectionless */
47
48 #define CONN_TIMEOUT_DEFAULT  8000      /* default connect timeout = 8s */
49 #define CONN_PROBING_INTERVAL 3600000   /* [ms] => 1 h */
50 #define TIPC_FWD_MSG          1
51 #define TIPC_CONN_OK          0
52 #define TIPC_CONN_PROBING     1
53
54 /**
55  * struct tipc_sock - TIPC socket structure
56  * @sk: socket - interacts with 'port' and with user via the socket API
57  * @connected: non-zero if port is currently connected to a peer port
58  * @conn_type: TIPC type used when connection was established
59  * @conn_instance: TIPC instance used when connection was established
60  * @published: non-zero if port has one or more associated names
61  * @max_pkt: maximum packet size "hint" used when building messages sent by port
62  * @ref: unique reference to port in TIPC object registry
63  * @phdr: preformatted message header used when sending messages
64  * @port_list: adjacent ports in TIPC's global list of ports
65  * @publications: list of publications for port
66  * @pub_count: total # of publications port has made during its lifetime
67  * @probing_state:
68  * @probing_interval:
69  * @timer:
70  * @port: port - interacts with 'sk' and with the rest of the TIPC stack
71  * @peer_name: the peer of the connection, if any
72  * @conn_timeout: the time we can wait for an unresponded setup request
73  * @dupl_rcvcnt: number of bytes counted twice, in both backlog and rcv queue
74  * @link_cong: non-zero if owner must sleep because of link congestion
75  * @sent_unacked: # messages sent by socket, and not yet acked by peer
76  * @rcv_unacked: # messages read by user, but not yet acked back to peer
77  */
78 struct tipc_sock {
79         struct sock sk;
80         int connected;
81         u32 conn_type;
82         u32 conn_instance;
83         int published;
84         u32 max_pkt;
85         u32 ref;
86         struct tipc_msg phdr;
87         struct list_head sock_list;
88         struct list_head publications;
89         u32 pub_count;
90         u32 probing_state;
91         u32 probing_interval;
92         struct timer_list timer;
93         uint conn_timeout;
94         atomic_t dupl_rcvcnt;
95         bool link_cong;
96         uint sent_unacked;
97         uint rcv_unacked;
98 };
99
100 static int tipc_backlog_rcv(struct sock *sk, struct sk_buff *skb);
101 static void tipc_data_ready(struct sock *sk);
102 static void tipc_write_space(struct sock *sk);
103 static int tipc_release(struct socket *sock);
104 static int tipc_accept(struct socket *sock, struct socket *new_sock, int flags);
105 static int tipc_wait_for_sndmsg(struct socket *sock, long *timeo_p);
106 static void tipc_sk_timeout(unsigned long ref);
107 static int tipc_sk_publish(struct tipc_sock *tsk, uint scope,
108                            struct tipc_name_seq const *seq);
109 static int tipc_sk_withdraw(struct tipc_sock *tsk, uint scope,
110                             struct tipc_name_seq const *seq);
111 static u32 tipc_sk_ref_acquire(struct tipc_sock *tsk);
112 static void tipc_sk_ref_discard(u32 ref);
113 static struct tipc_sock *tipc_sk_get(u32 ref);
114 static struct tipc_sock *tipc_sk_get_next(u32 *ref);
115 static void tipc_sk_put(struct tipc_sock *tsk);
116
117 static const struct proto_ops packet_ops;
118 static const struct proto_ops stream_ops;
119 static const struct proto_ops msg_ops;
120
121 static struct proto tipc_proto;
122 static struct proto tipc_proto_kern;
123
124 static const struct nla_policy tipc_nl_sock_policy[TIPC_NLA_SOCK_MAX + 1] = {
125         [TIPC_NLA_SOCK_UNSPEC]          = { .type = NLA_UNSPEC },
126         [TIPC_NLA_SOCK_ADDR]            = { .type = NLA_U32 },
127         [TIPC_NLA_SOCK_REF]             = { .type = NLA_U32 },
128         [TIPC_NLA_SOCK_CON]             = { .type = NLA_NESTED },
129         [TIPC_NLA_SOCK_HAS_PUBL]        = { .type = NLA_FLAG }
130 };
131
132 /*
133  * Revised TIPC socket locking policy:
134  *
135  * Most socket operations take the standard socket lock when they start
136  * and hold it until they finish (or until they need to sleep).  Acquiring
137  * this lock grants the owner exclusive access to the fields of the socket
138  * data structures, with the exception of the backlog queue.  A few socket
139  * operations can be done without taking the socket lock because they only
140  * read socket information that never changes during the life of the socket.
141  *
142  * Socket operations may acquire the lock for the associated TIPC port if they
143  * need to perform an operation on the port.  If any routine needs to acquire
144  * both the socket lock and the port lock it must take the socket lock first
145  * to avoid the risk of deadlock.
146  *
147  * The dispatcher handling incoming messages cannot grab the socket lock in
148  * the standard fashion, since invoked it runs at the BH level and cannot block.
149  * Instead, it checks to see if the socket lock is currently owned by someone,
150  * and either handles the message itself or adds it to the socket's backlog
151  * queue; in the latter case the queued message is processed once the process
152  * owning the socket lock releases it.
153  *
154  * NOTE: Releasing the socket lock while an operation is sleeping overcomes
155  * the problem of a blocked socket operation preventing any other operations
156  * from occurring.  However, applications must be careful if they have
157  * multiple threads trying to send (or receive) on the same socket, as these
158  * operations might interfere with each other.  For example, doing a connect
159  * and a receive at the same time might allow the receive to consume the
160  * ACK message meant for the connect.  While additional work could be done
161  * to try and overcome this, it doesn't seem to be worthwhile at the present.
162  *
163  * NOTE: Releasing the socket lock while an operation is sleeping also ensures
164  * that another operation that must be performed in a non-blocking manner is
165  * not delayed for very long because the lock has already been taken.
166  *
167  * NOTE: This code assumes that certain fields of a port/socket pair are
168  * constant over its lifetime; such fields can be examined without taking
169  * the socket lock and/or port lock, and do not need to be re-read even
170  * after resuming processing after waiting.  These fields include:
171  *   - socket type
172  *   - pointer to socket sk structure (aka tipc_sock structure)
173  *   - pointer to port structure
174  *   - port reference
175  */
176
177 static u32 tsk_peer_node(struct tipc_sock *tsk)
178 {
179         return msg_destnode(&tsk->phdr);
180 }
181
182 static u32 tsk_peer_port(struct tipc_sock *tsk)
183 {
184         return msg_destport(&tsk->phdr);
185 }
186
187 static  bool tsk_unreliable(struct tipc_sock *tsk)
188 {
189         return msg_src_droppable(&tsk->phdr) != 0;
190 }
191
192 static void tsk_set_unreliable(struct tipc_sock *tsk, bool unreliable)
193 {
194         msg_set_src_droppable(&tsk->phdr, unreliable ? 1 : 0);
195 }
196
197 static bool tsk_unreturnable(struct tipc_sock *tsk)
198 {
199         return msg_dest_droppable(&tsk->phdr) != 0;
200 }
201
202 static void tsk_set_unreturnable(struct tipc_sock *tsk, bool unreturnable)
203 {
204         msg_set_dest_droppable(&tsk->phdr, unreturnable ? 1 : 0);
205 }
206
207 static int tsk_importance(struct tipc_sock *tsk)
208 {
209         return msg_importance(&tsk->phdr);
210 }
211
212 static int tsk_set_importance(struct tipc_sock *tsk, int imp)
213 {
214         if (imp > TIPC_CRITICAL_IMPORTANCE)
215                 return -EINVAL;
216         msg_set_importance(&tsk->phdr, (u32)imp);
217         return 0;
218 }
219
220 static struct tipc_sock *tipc_sk(const struct sock *sk)
221 {
222         return container_of(sk, struct tipc_sock, sk);
223 }
224
225 static int tsk_conn_cong(struct tipc_sock *tsk)
226 {
227         return tsk->sent_unacked >= TIPC_FLOWCTRL_WIN;
228 }
229
230 /**
231  * tsk_advance_rx_queue - discard first buffer in socket receive queue
232  *
233  * Caller must hold socket lock
234  */
235 static void tsk_advance_rx_queue(struct sock *sk)
236 {
237         kfree_skb(__skb_dequeue(&sk->sk_receive_queue));
238 }
239
240 /**
241  * tsk_rej_rx_queue - reject all buffers in socket receive queue
242  *
243  * Caller must hold socket lock
244  */
245 static void tsk_rej_rx_queue(struct sock *sk)
246 {
247         struct sk_buff *buf;
248         u32 dnode;
249
250         while ((buf = __skb_dequeue(&sk->sk_receive_queue))) {
251                 if (tipc_msg_reverse(buf, &dnode, TIPC_ERR_NO_PORT))
252                         tipc_link_xmit(buf, dnode, 0);
253         }
254 }
255
256 /* tsk_peer_msg - verify if message was sent by connected port's peer
257  *
258  * Handles cases where the node's network address has changed from
259  * the default of <0.0.0> to its configured setting.
260  */
261 static bool tsk_peer_msg(struct tipc_sock *tsk, struct tipc_msg *msg)
262 {
263         u32 peer_port = tsk_peer_port(tsk);
264         u32 orig_node;
265         u32 peer_node;
266
267         if (unlikely(!tsk->connected))
268                 return false;
269
270         if (unlikely(msg_origport(msg) != peer_port))
271                 return false;
272
273         orig_node = msg_orignode(msg);
274         peer_node = tsk_peer_node(tsk);
275
276         if (likely(orig_node == peer_node))
277                 return true;
278
279         if (!orig_node && (peer_node == tipc_own_addr))
280                 return true;
281
282         if (!peer_node && (orig_node == tipc_own_addr))
283                 return true;
284
285         return false;
286 }
287
288 /**
289  * tipc_sk_create - create a TIPC socket
290  * @net: network namespace (must be default network)
291  * @sock: pre-allocated socket structure
292  * @protocol: protocol indicator (must be 0)
293  * @kern: caused by kernel or by userspace?
294  *
295  * This routine creates additional data structures used by the TIPC socket,
296  * initializes them, and links them together.
297  *
298  * Returns 0 on success, errno otherwise
299  */
300 static int tipc_sk_create(struct net *net, struct socket *sock,
301                           int protocol, int kern)
302 {
303         const struct proto_ops *ops;
304         socket_state state;
305         struct sock *sk;
306         struct tipc_sock *tsk;
307         struct tipc_msg *msg;
308         u32 ref;
309
310         /* Validate arguments */
311         if (unlikely(protocol != 0))
312                 return -EPROTONOSUPPORT;
313
314         switch (sock->type) {
315         case SOCK_STREAM:
316                 ops = &stream_ops;
317                 state = SS_UNCONNECTED;
318                 break;
319         case SOCK_SEQPACKET:
320                 ops = &packet_ops;
321                 state = SS_UNCONNECTED;
322                 break;
323         case SOCK_DGRAM:
324         case SOCK_RDM:
325                 ops = &msg_ops;
326                 state = SS_READY;
327                 break;
328         default:
329                 return -EPROTOTYPE;
330         }
331
332         /* Allocate socket's protocol area */
333         if (!kern)
334                 sk = sk_alloc(net, AF_TIPC, GFP_KERNEL, &tipc_proto);
335         else
336                 sk = sk_alloc(net, AF_TIPC, GFP_KERNEL, &tipc_proto_kern);
337
338         if (sk == NULL)
339                 return -ENOMEM;
340
341         tsk = tipc_sk(sk);
342         ref = tipc_sk_ref_acquire(tsk);
343         if (!ref) {
344                 pr_warn("Socket create failed; reference table exhausted\n");
345                 return -ENOMEM;
346         }
347         tsk->max_pkt = MAX_PKT_DEFAULT;
348         tsk->ref = ref;
349         INIT_LIST_HEAD(&tsk->publications);
350         msg = &tsk->phdr;
351         tipc_msg_init(msg, TIPC_LOW_IMPORTANCE, TIPC_NAMED_MSG,
352                       NAMED_H_SIZE, 0);
353         msg_set_origport(msg, ref);
354
355         /* Finish initializing socket data structures */
356         sock->ops = ops;
357         sock->state = state;
358         sock_init_data(sock, sk);
359         k_init_timer(&tsk->timer, (Handler)tipc_sk_timeout, ref);
360         sk->sk_backlog_rcv = tipc_backlog_rcv;
361         sk->sk_rcvbuf = sysctl_tipc_rmem[1];
362         sk->sk_data_ready = tipc_data_ready;
363         sk->sk_write_space = tipc_write_space;
364         tsk->conn_timeout = CONN_TIMEOUT_DEFAULT;
365         tsk->sent_unacked = 0;
366         atomic_set(&tsk->dupl_rcvcnt, 0);
367
368         if (sock->state == SS_READY) {
369                 tsk_set_unreturnable(tsk, true);
370                 if (sock->type == SOCK_DGRAM)
371                         tsk_set_unreliable(tsk, true);
372         }
373         return 0;
374 }
375
376 /**
377  * tipc_sock_create_local - create TIPC socket from inside TIPC module
378  * @type: socket type - SOCK_RDM or SOCK_SEQPACKET
379  *
380  * We cannot use sock_creat_kern here because it bumps module user count.
381  * Since socket owner and creator is the same module we must make sure
382  * that module count remains zero for module local sockets, otherwise
383  * we cannot do rmmod.
384  *
385  * Returns 0 on success, errno otherwise
386  */
387 int tipc_sock_create_local(int type, struct socket **res)
388 {
389         int rc;
390
391         rc = sock_create_lite(AF_TIPC, type, 0, res);
392         if (rc < 0) {
393                 pr_err("Failed to create kernel socket\n");
394                 return rc;
395         }
396         tipc_sk_create(&init_net, *res, 0, 1);
397
398         return 0;
399 }
400
401 /**
402  * tipc_sock_release_local - release socket created by tipc_sock_create_local
403  * @sock: the socket to be released.
404  *
405  * Module reference count is not incremented when such sockets are created,
406  * so we must keep it from being decremented when they are released.
407  */
408 void tipc_sock_release_local(struct socket *sock)
409 {
410         tipc_release(sock);
411         sock->ops = NULL;
412         sock_release(sock);
413 }
414
415 /**
416  * tipc_sock_accept_local - accept a connection on a socket created
417  * with tipc_sock_create_local. Use this function to avoid that
418  * module reference count is inadvertently incremented.
419  *
420  * @sock:    the accepting socket
421  * @newsock: reference to the new socket to be created
422  * @flags:   socket flags
423  */
424
425 int tipc_sock_accept_local(struct socket *sock, struct socket **newsock,
426                            int flags)
427 {
428         struct sock *sk = sock->sk;
429         int ret;
430
431         ret = sock_create_lite(sk->sk_family, sk->sk_type,
432                                sk->sk_protocol, newsock);
433         if (ret < 0)
434                 return ret;
435
436         ret = tipc_accept(sock, *newsock, flags);
437         if (ret < 0) {
438                 sock_release(*newsock);
439                 return ret;
440         }
441         (*newsock)->ops = sock->ops;
442         return ret;
443 }
444
445 /**
446  * tipc_release - destroy a TIPC socket
447  * @sock: socket to destroy
448  *
449  * This routine cleans up any messages that are still queued on the socket.
450  * For DGRAM and RDM socket types, all queued messages are rejected.
451  * For SEQPACKET and STREAM socket types, the first message is rejected
452  * and any others are discarded.  (If the first message on a STREAM socket
453  * is partially-read, it is discarded and the next one is rejected instead.)
454  *
455  * NOTE: Rejected messages are not necessarily returned to the sender!  They
456  * are returned or discarded according to the "destination droppable" setting
457  * specified for the message by the sender.
458  *
459  * Returns 0 on success, errno otherwise
460  */
461 static int tipc_release(struct socket *sock)
462 {
463         struct sock *sk = sock->sk;
464         struct tipc_sock *tsk;
465         struct sk_buff *buf;
466         u32 dnode;
467
468         /*
469          * Exit if socket isn't fully initialized (occurs when a failed accept()
470          * releases a pre-allocated child socket that was never used)
471          */
472         if (sk == NULL)
473                 return 0;
474
475         tsk = tipc_sk(sk);
476         lock_sock(sk);
477
478         /*
479          * Reject all unreceived messages, except on an active connection
480          * (which disconnects locally & sends a 'FIN+' to peer)
481          */
482         dnode = tsk_peer_node(tsk);
483         while (sock->state != SS_DISCONNECTING) {
484                 buf = __skb_dequeue(&sk->sk_receive_queue);
485                 if (buf == NULL)
486                         break;
487                 if (TIPC_SKB_CB(buf)->handle != NULL)
488                         kfree_skb(buf);
489                 else {
490                         if ((sock->state == SS_CONNECTING) ||
491                             (sock->state == SS_CONNECTED)) {
492                                 sock->state = SS_DISCONNECTING;
493                                 tsk->connected = 0;
494                                 tipc_node_remove_conn(dnode, tsk->ref);
495                         }
496                         if (tipc_msg_reverse(buf, &dnode, TIPC_ERR_NO_PORT))
497                                 tipc_link_xmit(buf, dnode, 0);
498                 }
499         }
500
501         tipc_sk_withdraw(tsk, 0, NULL);
502         tipc_sk_ref_discard(tsk->ref);
503         k_cancel_timer(&tsk->timer);
504         if (tsk->connected) {
505                 buf = tipc_msg_create(TIPC_CRITICAL_IMPORTANCE, TIPC_CONN_MSG,
506                                       SHORT_H_SIZE, 0, dnode, tipc_own_addr,
507                                       tsk_peer_port(tsk),
508                                       tsk->ref, TIPC_ERR_NO_PORT);
509                 if (buf)
510                         tipc_link_xmit(buf, dnode, tsk->ref);
511                 tipc_node_remove_conn(dnode, tsk->ref);
512         }
513         k_term_timer(&tsk->timer);
514
515         /* Discard any remaining (connection-based) messages in receive queue */
516         __skb_queue_purge(&sk->sk_receive_queue);
517
518         /* Reject any messages that accumulated in backlog queue */
519         sock->state = SS_DISCONNECTING;
520         release_sock(sk);
521         sock_put(sk);
522         sock->sk = NULL;
523
524         return 0;
525 }
526
527 /**
528  * tipc_bind - associate or disassocate TIPC name(s) with a socket
529  * @sock: socket structure
530  * @uaddr: socket address describing name(s) and desired operation
531  * @uaddr_len: size of socket address data structure
532  *
533  * Name and name sequence binding is indicated using a positive scope value;
534  * a negative scope value unbinds the specified name.  Specifying no name
535  * (i.e. a socket address length of 0) unbinds all names from the socket.
536  *
537  * Returns 0 on success, errno otherwise
538  *
539  * NOTE: This routine doesn't need to take the socket lock since it doesn't
540  *       access any non-constant socket information.
541  */
542 static int tipc_bind(struct socket *sock, struct sockaddr *uaddr,
543                      int uaddr_len)
544 {
545         struct sock *sk = sock->sk;
546         struct sockaddr_tipc *addr = (struct sockaddr_tipc *)uaddr;
547         struct tipc_sock *tsk = tipc_sk(sk);
548         int res = -EINVAL;
549
550         lock_sock(sk);
551         if (unlikely(!uaddr_len)) {
552                 res = tipc_sk_withdraw(tsk, 0, NULL);
553                 goto exit;
554         }
555
556         if (uaddr_len < sizeof(struct sockaddr_tipc)) {
557                 res = -EINVAL;
558                 goto exit;
559         }
560         if (addr->family != AF_TIPC) {
561                 res = -EAFNOSUPPORT;
562                 goto exit;
563         }
564
565         if (addr->addrtype == TIPC_ADDR_NAME)
566                 addr->addr.nameseq.upper = addr->addr.nameseq.lower;
567         else if (addr->addrtype != TIPC_ADDR_NAMESEQ) {
568                 res = -EAFNOSUPPORT;
569                 goto exit;
570         }
571
572         if ((addr->addr.nameseq.type < TIPC_RESERVED_TYPES) &&
573             (addr->addr.nameseq.type != TIPC_TOP_SRV) &&
574             (addr->addr.nameseq.type != TIPC_CFG_SRV)) {
575                 res = -EACCES;
576                 goto exit;
577         }
578
579         res = (addr->scope > 0) ?
580                 tipc_sk_publish(tsk, addr->scope, &addr->addr.nameseq) :
581                 tipc_sk_withdraw(tsk, -addr->scope, &addr->addr.nameseq);
582 exit:
583         release_sock(sk);
584         return res;
585 }
586
587 /**
588  * tipc_getname - get port ID of socket or peer socket
589  * @sock: socket structure
590  * @uaddr: area for returned socket address
591  * @uaddr_len: area for returned length of socket address
592  * @peer: 0 = own ID, 1 = current peer ID, 2 = current/former peer ID
593  *
594  * Returns 0 on success, errno otherwise
595  *
596  * NOTE: This routine doesn't need to take the socket lock since it only
597  *       accesses socket information that is unchanging (or which changes in
598  *       a completely predictable manner).
599  */
600 static int tipc_getname(struct socket *sock, struct sockaddr *uaddr,
601                         int *uaddr_len, int peer)
602 {
603         struct sockaddr_tipc *addr = (struct sockaddr_tipc *)uaddr;
604         struct tipc_sock *tsk = tipc_sk(sock->sk);
605
606         memset(addr, 0, sizeof(*addr));
607         if (peer) {
608                 if ((sock->state != SS_CONNECTED) &&
609                         ((peer != 2) || (sock->state != SS_DISCONNECTING)))
610                         return -ENOTCONN;
611                 addr->addr.id.ref = tsk_peer_port(tsk);
612                 addr->addr.id.node = tsk_peer_node(tsk);
613         } else {
614                 addr->addr.id.ref = tsk->ref;
615                 addr->addr.id.node = tipc_own_addr;
616         }
617
618         *uaddr_len = sizeof(*addr);
619         addr->addrtype = TIPC_ADDR_ID;
620         addr->family = AF_TIPC;
621         addr->scope = 0;
622         addr->addr.name.domain = 0;
623
624         return 0;
625 }
626
627 /**
628  * tipc_poll - read and possibly block on pollmask
629  * @file: file structure associated with the socket
630  * @sock: socket for which to calculate the poll bits
631  * @wait: ???
632  *
633  * Returns pollmask value
634  *
635  * COMMENTARY:
636  * It appears that the usual socket locking mechanisms are not useful here
637  * since the pollmask info is potentially out-of-date the moment this routine
638  * exits.  TCP and other protocols seem to rely on higher level poll routines
639  * to handle any preventable race conditions, so TIPC will do the same ...
640  *
641  * TIPC sets the returned events as follows:
642  *
643  * socket state         flags set
644  * ------------         ---------
645  * unconnected          no read flags
646  *                      POLLOUT if port is not congested
647  *
648  * connecting           POLLIN/POLLRDNORM if ACK/NACK in rx queue
649  *                      no write flags
650  *
651  * connected            POLLIN/POLLRDNORM if data in rx queue
652  *                      POLLOUT if port is not congested
653  *
654  * disconnecting        POLLIN/POLLRDNORM/POLLHUP
655  *                      no write flags
656  *
657  * listening            POLLIN if SYN in rx queue
658  *                      no write flags
659  *
660  * ready                POLLIN/POLLRDNORM if data in rx queue
661  * [connectionless]     POLLOUT (since port cannot be congested)
662  *
663  * IMPORTANT: The fact that a read or write operation is indicated does NOT
664  * imply that the operation will succeed, merely that it should be performed
665  * and will not block.
666  */
667 static unsigned int tipc_poll(struct file *file, struct socket *sock,
668                               poll_table *wait)
669 {
670         struct sock *sk = sock->sk;
671         struct tipc_sock *tsk = tipc_sk(sk);
672         u32 mask = 0;
673
674         sock_poll_wait(file, sk_sleep(sk), wait);
675
676         switch ((int)sock->state) {
677         case SS_UNCONNECTED:
678                 if (!tsk->link_cong)
679                         mask |= POLLOUT;
680                 break;
681         case SS_READY:
682         case SS_CONNECTED:
683                 if (!tsk->link_cong && !tsk_conn_cong(tsk))
684                         mask |= POLLOUT;
685                 /* fall thru' */
686         case SS_CONNECTING:
687         case SS_LISTENING:
688                 if (!skb_queue_empty(&sk->sk_receive_queue))
689                         mask |= (POLLIN | POLLRDNORM);
690                 break;
691         case SS_DISCONNECTING:
692                 mask = (POLLIN | POLLRDNORM | POLLHUP);
693                 break;
694         }
695
696         return mask;
697 }
698
699 /**
700  * tipc_sendmcast - send multicast message
701  * @sock: socket structure
702  * @seq: destination address
703  * @iov: message data to send
704  * @dsz: total length of message data
705  * @timeo: timeout to wait for wakeup
706  *
707  * Called from function tipc_sendmsg(), which has done all sanity checks
708  * Returns the number of bytes sent on success, or errno
709  */
710 static int tipc_sendmcast(struct  socket *sock, struct tipc_name_seq *seq,
711                           struct iovec *iov, size_t dsz, long timeo)
712 {
713         struct sock *sk = sock->sk;
714         struct tipc_msg *mhdr = &tipc_sk(sk)->phdr;
715         struct sk_buff *buf;
716         uint mtu;
717         int rc;
718
719         msg_set_type(mhdr, TIPC_MCAST_MSG);
720         msg_set_lookup_scope(mhdr, TIPC_CLUSTER_SCOPE);
721         msg_set_destport(mhdr, 0);
722         msg_set_destnode(mhdr, 0);
723         msg_set_nametype(mhdr, seq->type);
724         msg_set_namelower(mhdr, seq->lower);
725         msg_set_nameupper(mhdr, seq->upper);
726         msg_set_hdr_sz(mhdr, MCAST_H_SIZE);
727
728 new_mtu:
729         mtu = tipc_bclink_get_mtu();
730         rc = tipc_msg_build(mhdr, iov, 0, dsz, mtu, &buf);
731         if (unlikely(rc < 0))
732                 return rc;
733
734         do {
735                 rc = tipc_bclink_xmit(buf);
736                 if (likely(rc >= 0)) {
737                         rc = dsz;
738                         break;
739                 }
740                 if (rc == -EMSGSIZE)
741                         goto new_mtu;
742                 if (rc != -ELINKCONG)
743                         break;
744                 tipc_sk(sk)->link_cong = 1;
745                 rc = tipc_wait_for_sndmsg(sock, &timeo);
746                 if (rc)
747                         kfree_skb_list(buf);
748         } while (!rc);
749         return rc;
750 }
751
752 /* tipc_sk_mcast_rcv - Deliver multicast message to all destination sockets
753  */
754 void tipc_sk_mcast_rcv(struct sk_buff *buf)
755 {
756         struct tipc_msg *msg = buf_msg(buf);
757         struct tipc_port_list dports = {0, NULL, };
758         struct tipc_port_list *item;
759         struct sk_buff *b;
760         uint i, last, dst = 0;
761         u32 scope = TIPC_CLUSTER_SCOPE;
762
763         if (in_own_node(msg_orignode(msg)))
764                 scope = TIPC_NODE_SCOPE;
765
766         /* Create destination port list: */
767         tipc_nametbl_mc_translate(msg_nametype(msg),
768                                   msg_namelower(msg),
769                                   msg_nameupper(msg),
770                                   scope,
771                                   &dports);
772         last = dports.count;
773         if (!last) {
774                 kfree_skb(buf);
775                 return;
776         }
777
778         for (item = &dports; item; item = item->next) {
779                 for (i = 0; i < PLSIZE && ++dst <= last; i++) {
780                         b = (dst != last) ? skb_clone(buf, GFP_ATOMIC) : buf;
781                         if (!b) {
782                                 pr_warn("Failed do clone mcast rcv buffer\n");
783                                 continue;
784                         }
785                         msg_set_destport(msg, item->ports[i]);
786                         tipc_sk_rcv(b);
787                 }
788         }
789         tipc_port_list_free(&dports);
790 }
791
792 /**
793  * tipc_sk_proto_rcv - receive a connection mng protocol message
794  * @tsk: receiving socket
795  * @dnode: node to send response message to, if any
796  * @buf: buffer containing protocol message
797  * Returns 0 (TIPC_OK) if message was consumed, 1 (TIPC_FWD_MSG) if
798  * (CONN_PROBE_REPLY) message should be forwarded.
799  */
800 static int tipc_sk_proto_rcv(struct tipc_sock *tsk, u32 *dnode,
801                              struct sk_buff *buf)
802 {
803         struct tipc_msg *msg = buf_msg(buf);
804         int conn_cong;
805
806         /* Ignore if connection cannot be validated: */
807         if (!tsk_peer_msg(tsk, msg))
808                 goto exit;
809
810         tsk->probing_state = TIPC_CONN_OK;
811
812         if (msg_type(msg) == CONN_ACK) {
813                 conn_cong = tsk_conn_cong(tsk);
814                 tsk->sent_unacked -= msg_msgcnt(msg);
815                 if (conn_cong)
816                         tsk->sk.sk_write_space(&tsk->sk);
817         } else if (msg_type(msg) == CONN_PROBE) {
818                 if (!tipc_msg_reverse(buf, dnode, TIPC_OK))
819                         return TIPC_OK;
820                 msg_set_type(msg, CONN_PROBE_REPLY);
821                 return TIPC_FWD_MSG;
822         }
823         /* Do nothing if msg_type() == CONN_PROBE_REPLY */
824 exit:
825         kfree_skb(buf);
826         return TIPC_OK;
827 }
828
829 /**
830  * dest_name_check - verify user is permitted to send to specified port name
831  * @dest: destination address
832  * @m: descriptor for message to be sent
833  *
834  * Prevents restricted configuration commands from being issued by
835  * unauthorized users.
836  *
837  * Returns 0 if permission is granted, otherwise errno
838  */
839 static int dest_name_check(struct sockaddr_tipc *dest, struct msghdr *m)
840 {
841         struct tipc_cfg_msg_hdr hdr;
842
843         if (unlikely(dest->addrtype == TIPC_ADDR_ID))
844                 return 0;
845         if (likely(dest->addr.name.name.type >= TIPC_RESERVED_TYPES))
846                 return 0;
847         if (likely(dest->addr.name.name.type == TIPC_TOP_SRV))
848                 return 0;
849         if (likely(dest->addr.name.name.type != TIPC_CFG_SRV))
850                 return -EACCES;
851
852         if (!m->msg_iovlen || (m->msg_iov[0].iov_len < sizeof(hdr)))
853                 return -EMSGSIZE;
854         if (copy_from_user(&hdr, m->msg_iov[0].iov_base, sizeof(hdr)))
855                 return -EFAULT;
856         if ((ntohs(hdr.tcm_type) & 0xC000) && (!capable(CAP_NET_ADMIN)))
857                 return -EACCES;
858
859         return 0;
860 }
861
862 static int tipc_wait_for_sndmsg(struct socket *sock, long *timeo_p)
863 {
864         struct sock *sk = sock->sk;
865         struct tipc_sock *tsk = tipc_sk(sk);
866         DEFINE_WAIT(wait);
867         int done;
868
869         do {
870                 int err = sock_error(sk);
871                 if (err)
872                         return err;
873                 if (sock->state == SS_DISCONNECTING)
874                         return -EPIPE;
875                 if (!*timeo_p)
876                         return -EAGAIN;
877                 if (signal_pending(current))
878                         return sock_intr_errno(*timeo_p);
879
880                 prepare_to_wait(sk_sleep(sk), &wait, TASK_INTERRUPTIBLE);
881                 done = sk_wait_event(sk, timeo_p, !tsk->link_cong);
882                 finish_wait(sk_sleep(sk), &wait);
883         } while (!done);
884         return 0;
885 }
886
887 /**
888  * tipc_sendmsg - send message in connectionless manner
889  * @iocb: if NULL, indicates that socket lock is already held
890  * @sock: socket structure
891  * @m: message to send
892  * @dsz: amount of user data to be sent
893  *
894  * Message must have an destination specified explicitly.
895  * Used for SOCK_RDM and SOCK_DGRAM messages,
896  * and for 'SYN' messages on SOCK_SEQPACKET and SOCK_STREAM connections.
897  * (Note: 'SYN+' is prohibited on SOCK_STREAM.)
898  *
899  * Returns the number of bytes sent on success, or errno otherwise
900  */
901 static int tipc_sendmsg(struct kiocb *iocb, struct socket *sock,
902                         struct msghdr *m, size_t dsz)
903 {
904         DECLARE_SOCKADDR(struct sockaddr_tipc *, dest, m->msg_name);
905         struct sock *sk = sock->sk;
906         struct tipc_sock *tsk = tipc_sk(sk);
907         struct tipc_msg *mhdr = &tsk->phdr;
908         struct iovec *iov = m->msg_iov;
909         u32 dnode, dport;
910         struct sk_buff *buf;
911         struct tipc_name_seq *seq = &dest->addr.nameseq;
912         u32 mtu;
913         long timeo;
914         int rc = -EINVAL;
915
916         if (unlikely(!dest))
917                 return -EDESTADDRREQ;
918
919         if (unlikely((m->msg_namelen < sizeof(*dest)) ||
920                      (dest->family != AF_TIPC)))
921                 return -EINVAL;
922
923         if (dsz > TIPC_MAX_USER_MSG_SIZE)
924                 return -EMSGSIZE;
925
926         if (iocb)
927                 lock_sock(sk);
928
929         if (unlikely(sock->state != SS_READY)) {
930                 if (sock->state == SS_LISTENING) {
931                         rc = -EPIPE;
932                         goto exit;
933                 }
934                 if (sock->state != SS_UNCONNECTED) {
935                         rc = -EISCONN;
936                         goto exit;
937                 }
938                 if (tsk->published) {
939                         rc = -EOPNOTSUPP;
940                         goto exit;
941                 }
942                 if (dest->addrtype == TIPC_ADDR_NAME) {
943                         tsk->conn_type = dest->addr.name.name.type;
944                         tsk->conn_instance = dest->addr.name.name.instance;
945                 }
946         }
947         rc = dest_name_check(dest, m);
948         if (rc)
949                 goto exit;
950
951         timeo = sock_sndtimeo(sk, m->msg_flags & MSG_DONTWAIT);
952
953         if (dest->addrtype == TIPC_ADDR_MCAST) {
954                 rc = tipc_sendmcast(sock, seq, iov, dsz, timeo);
955                 goto exit;
956         } else if (dest->addrtype == TIPC_ADDR_NAME) {
957                 u32 type = dest->addr.name.name.type;
958                 u32 inst = dest->addr.name.name.instance;
959                 u32 domain = dest->addr.name.domain;
960
961                 dnode = domain;
962                 msg_set_type(mhdr, TIPC_NAMED_MSG);
963                 msg_set_hdr_sz(mhdr, NAMED_H_SIZE);
964                 msg_set_nametype(mhdr, type);
965                 msg_set_nameinst(mhdr, inst);
966                 msg_set_lookup_scope(mhdr, tipc_addr_scope(domain));
967                 dport = tipc_nametbl_translate(type, inst, &dnode);
968                 msg_set_destnode(mhdr, dnode);
969                 msg_set_destport(mhdr, dport);
970                 if (unlikely(!dport && !dnode)) {
971                         rc = -EHOSTUNREACH;
972                         goto exit;
973                 }
974         } else if (dest->addrtype == TIPC_ADDR_ID) {
975                 dnode = dest->addr.id.node;
976                 msg_set_type(mhdr, TIPC_DIRECT_MSG);
977                 msg_set_lookup_scope(mhdr, 0);
978                 msg_set_destnode(mhdr, dnode);
979                 msg_set_destport(mhdr, dest->addr.id.ref);
980                 msg_set_hdr_sz(mhdr, BASIC_H_SIZE);
981         }
982
983 new_mtu:
984         mtu = tipc_node_get_mtu(dnode, tsk->ref);
985         rc = tipc_msg_build(mhdr, iov, 0, dsz, mtu, &buf);
986         if (rc < 0)
987                 goto exit;
988
989         do {
990                 TIPC_SKB_CB(buf)->wakeup_pending = tsk->link_cong;
991                 rc = tipc_link_xmit(buf, dnode, tsk->ref);
992                 if (likely(rc >= 0)) {
993                         if (sock->state != SS_READY)
994                                 sock->state = SS_CONNECTING;
995                         rc = dsz;
996                         break;
997                 }
998                 if (rc == -EMSGSIZE)
999                         goto new_mtu;
1000                 if (rc != -ELINKCONG)
1001                         break;
1002                 tsk->link_cong = 1;
1003                 rc = tipc_wait_for_sndmsg(sock, &timeo);
1004                 if (rc)
1005                         kfree_skb_list(buf);
1006         } while (!rc);
1007 exit:
1008         if (iocb)
1009                 release_sock(sk);
1010
1011         return rc;
1012 }
1013
1014 static int tipc_wait_for_sndpkt(struct socket *sock, long *timeo_p)
1015 {
1016         struct sock *sk = sock->sk;
1017         struct tipc_sock *tsk = tipc_sk(sk);
1018         DEFINE_WAIT(wait);
1019         int done;
1020
1021         do {
1022                 int err = sock_error(sk);
1023                 if (err)
1024                         return err;
1025                 if (sock->state == SS_DISCONNECTING)
1026                         return -EPIPE;
1027                 else if (sock->state != SS_CONNECTED)
1028                         return -ENOTCONN;
1029                 if (!*timeo_p)
1030                         return -EAGAIN;
1031                 if (signal_pending(current))
1032                         return sock_intr_errno(*timeo_p);
1033
1034                 prepare_to_wait(sk_sleep(sk), &wait, TASK_INTERRUPTIBLE);
1035                 done = sk_wait_event(sk, timeo_p,
1036                                      (!tsk->link_cong &&
1037                                       !tsk_conn_cong(tsk)) ||
1038                                      !tsk->connected);
1039                 finish_wait(sk_sleep(sk), &wait);
1040         } while (!done);
1041         return 0;
1042 }
1043
1044 /**
1045  * tipc_send_stream - send stream-oriented data
1046  * @iocb: (unused)
1047  * @sock: socket structure
1048  * @m: data to send
1049  * @dsz: total length of data to be transmitted
1050  *
1051  * Used for SOCK_STREAM data.
1052  *
1053  * Returns the number of bytes sent on success (or partial success),
1054  * or errno if no data sent
1055  */
1056 static int tipc_send_stream(struct kiocb *iocb, struct socket *sock,
1057                             struct msghdr *m, size_t dsz)
1058 {
1059         struct sock *sk = sock->sk;
1060         struct tipc_sock *tsk = tipc_sk(sk);
1061         struct tipc_msg *mhdr = &tsk->phdr;
1062         struct sk_buff *buf;
1063         DECLARE_SOCKADDR(struct sockaddr_tipc *, dest, m->msg_name);
1064         u32 ref = tsk->ref;
1065         int rc = -EINVAL;
1066         long timeo;
1067         u32 dnode;
1068         uint mtu, send, sent = 0;
1069
1070         /* Handle implied connection establishment */
1071         if (unlikely(dest)) {
1072                 rc = tipc_sendmsg(iocb, sock, m, dsz);
1073                 if (dsz && (dsz == rc))
1074                         tsk->sent_unacked = 1;
1075                 return rc;
1076         }
1077         if (dsz > (uint)INT_MAX)
1078                 return -EMSGSIZE;
1079
1080         if (iocb)
1081                 lock_sock(sk);
1082
1083         if (unlikely(sock->state != SS_CONNECTED)) {
1084                 if (sock->state == SS_DISCONNECTING)
1085                         rc = -EPIPE;
1086                 else
1087                         rc = -ENOTCONN;
1088                 goto exit;
1089         }
1090
1091         timeo = sock_sndtimeo(sk, m->msg_flags & MSG_DONTWAIT);
1092         dnode = tsk_peer_node(tsk);
1093
1094 next:
1095         mtu = tsk->max_pkt;
1096         send = min_t(uint, dsz - sent, TIPC_MAX_USER_MSG_SIZE);
1097         rc = tipc_msg_build(mhdr, m->msg_iov, sent, send, mtu, &buf);
1098         if (unlikely(rc < 0))
1099                 goto exit;
1100         do {
1101                 if (likely(!tsk_conn_cong(tsk))) {
1102                         rc = tipc_link_xmit(buf, dnode, ref);
1103                         if (likely(!rc)) {
1104                                 tsk->sent_unacked++;
1105                                 sent += send;
1106                                 if (sent == dsz)
1107                                         break;
1108                                 goto next;
1109                         }
1110                         if (rc == -EMSGSIZE) {
1111                                 tsk->max_pkt = tipc_node_get_mtu(dnode, ref);
1112                                 goto next;
1113                         }
1114                         if (rc != -ELINKCONG)
1115                                 break;
1116                         tsk->link_cong = 1;
1117                 }
1118                 rc = tipc_wait_for_sndpkt(sock, &timeo);
1119                 if (rc)
1120                         kfree_skb_list(buf);
1121         } while (!rc);
1122 exit:
1123         if (iocb)
1124                 release_sock(sk);
1125         return sent ? sent : rc;
1126 }
1127
1128 /**
1129  * tipc_send_packet - send a connection-oriented message
1130  * @iocb: if NULL, indicates that socket lock is already held
1131  * @sock: socket structure
1132  * @m: message to send
1133  * @dsz: length of data to be transmitted
1134  *
1135  * Used for SOCK_SEQPACKET messages.
1136  *
1137  * Returns the number of bytes sent on success, or errno otherwise
1138  */
1139 static int tipc_send_packet(struct kiocb *iocb, struct socket *sock,
1140                             struct msghdr *m, size_t dsz)
1141 {
1142         if (dsz > TIPC_MAX_USER_MSG_SIZE)
1143                 return -EMSGSIZE;
1144
1145         return tipc_send_stream(iocb, sock, m, dsz);
1146 }
1147
1148 /* tipc_sk_finish_conn - complete the setup of a connection
1149  */
1150 static void tipc_sk_finish_conn(struct tipc_sock *tsk, u32 peer_port,
1151                                 u32 peer_node)
1152 {
1153         struct tipc_msg *msg = &tsk->phdr;
1154
1155         msg_set_destnode(msg, peer_node);
1156         msg_set_destport(msg, peer_port);
1157         msg_set_type(msg, TIPC_CONN_MSG);
1158         msg_set_lookup_scope(msg, 0);
1159         msg_set_hdr_sz(msg, SHORT_H_SIZE);
1160
1161         tsk->probing_interval = CONN_PROBING_INTERVAL;
1162         tsk->probing_state = TIPC_CONN_OK;
1163         tsk->connected = 1;
1164         k_start_timer(&tsk->timer, tsk->probing_interval);
1165         tipc_node_add_conn(peer_node, tsk->ref, peer_port);
1166         tsk->max_pkt = tipc_node_get_mtu(peer_node, tsk->ref);
1167 }
1168
1169 /**
1170  * set_orig_addr - capture sender's address for received message
1171  * @m: descriptor for message info
1172  * @msg: received message header
1173  *
1174  * Note: Address is not captured if not requested by receiver.
1175  */
1176 static void set_orig_addr(struct msghdr *m, struct tipc_msg *msg)
1177 {
1178         DECLARE_SOCKADDR(struct sockaddr_tipc *, addr, m->msg_name);
1179
1180         if (addr) {
1181                 addr->family = AF_TIPC;
1182                 addr->addrtype = TIPC_ADDR_ID;
1183                 memset(&addr->addr, 0, sizeof(addr->addr));
1184                 addr->addr.id.ref = msg_origport(msg);
1185                 addr->addr.id.node = msg_orignode(msg);
1186                 addr->addr.name.domain = 0;     /* could leave uninitialized */
1187                 addr->scope = 0;                /* could leave uninitialized */
1188                 m->msg_namelen = sizeof(struct sockaddr_tipc);
1189         }
1190 }
1191
1192 /**
1193  * tipc_sk_anc_data_recv - optionally capture ancillary data for received message
1194  * @m: descriptor for message info
1195  * @msg: received message header
1196  * @tsk: TIPC port associated with message
1197  *
1198  * Note: Ancillary data is not captured if not requested by receiver.
1199  *
1200  * Returns 0 if successful, otherwise errno
1201  */
1202 static int tipc_sk_anc_data_recv(struct msghdr *m, struct tipc_msg *msg,
1203                                  struct tipc_sock *tsk)
1204 {
1205         u32 anc_data[3];
1206         u32 err;
1207         u32 dest_type;
1208         int has_name;
1209         int res;
1210
1211         if (likely(m->msg_controllen == 0))
1212                 return 0;
1213
1214         /* Optionally capture errored message object(s) */
1215         err = msg ? msg_errcode(msg) : 0;
1216         if (unlikely(err)) {
1217                 anc_data[0] = err;
1218                 anc_data[1] = msg_data_sz(msg);
1219                 res = put_cmsg(m, SOL_TIPC, TIPC_ERRINFO, 8, anc_data);
1220                 if (res)
1221                         return res;
1222                 if (anc_data[1]) {
1223                         res = put_cmsg(m, SOL_TIPC, TIPC_RETDATA, anc_data[1],
1224                                        msg_data(msg));
1225                         if (res)
1226                                 return res;
1227                 }
1228         }
1229
1230         /* Optionally capture message destination object */
1231         dest_type = msg ? msg_type(msg) : TIPC_DIRECT_MSG;
1232         switch (dest_type) {
1233         case TIPC_NAMED_MSG:
1234                 has_name = 1;
1235                 anc_data[0] = msg_nametype(msg);
1236                 anc_data[1] = msg_namelower(msg);
1237                 anc_data[2] = msg_namelower(msg);
1238                 break;
1239         case TIPC_MCAST_MSG:
1240                 has_name = 1;
1241                 anc_data[0] = msg_nametype(msg);
1242                 anc_data[1] = msg_namelower(msg);
1243                 anc_data[2] = msg_nameupper(msg);
1244                 break;
1245         case TIPC_CONN_MSG:
1246                 has_name = (tsk->conn_type != 0);
1247                 anc_data[0] = tsk->conn_type;
1248                 anc_data[1] = tsk->conn_instance;
1249                 anc_data[2] = tsk->conn_instance;
1250                 break;
1251         default:
1252                 has_name = 0;
1253         }
1254         if (has_name) {
1255                 res = put_cmsg(m, SOL_TIPC, TIPC_DESTNAME, 12, anc_data);
1256                 if (res)
1257                         return res;
1258         }
1259
1260         return 0;
1261 }
1262
1263 static void tipc_sk_send_ack(struct tipc_sock *tsk, uint ack)
1264 {
1265         struct sk_buff *buf = NULL;
1266         struct tipc_msg *msg;
1267         u32 peer_port = tsk_peer_port(tsk);
1268         u32 dnode = tsk_peer_node(tsk);
1269
1270         if (!tsk->connected)
1271                 return;
1272         buf = tipc_msg_create(CONN_MANAGER, CONN_ACK, INT_H_SIZE, 0, dnode,
1273                               tipc_own_addr, peer_port, tsk->ref, TIPC_OK);
1274         if (!buf)
1275                 return;
1276         msg = buf_msg(buf);
1277         msg_set_msgcnt(msg, ack);
1278         tipc_link_xmit(buf, dnode, msg_link_selector(msg));
1279 }
1280
1281 static int tipc_wait_for_rcvmsg(struct socket *sock, long *timeop)
1282 {
1283         struct sock *sk = sock->sk;
1284         DEFINE_WAIT(wait);
1285         long timeo = *timeop;
1286         int err;
1287
1288         for (;;) {
1289                 prepare_to_wait(sk_sleep(sk), &wait, TASK_INTERRUPTIBLE);
1290                 if (timeo && skb_queue_empty(&sk->sk_receive_queue)) {
1291                         if (sock->state == SS_DISCONNECTING) {
1292                                 err = -ENOTCONN;
1293                                 break;
1294                         }
1295                         release_sock(sk);
1296                         timeo = schedule_timeout(timeo);
1297                         lock_sock(sk);
1298                 }
1299                 err = 0;
1300                 if (!skb_queue_empty(&sk->sk_receive_queue))
1301                         break;
1302                 err = sock_intr_errno(timeo);
1303                 if (signal_pending(current))
1304                         break;
1305                 err = -EAGAIN;
1306                 if (!timeo)
1307                         break;
1308         }
1309         finish_wait(sk_sleep(sk), &wait);
1310         *timeop = timeo;
1311         return err;
1312 }
1313
1314 /**
1315  * tipc_recvmsg - receive packet-oriented message
1316  * @iocb: (unused)
1317  * @m: descriptor for message info
1318  * @buf_len: total size of user buffer area
1319  * @flags: receive flags
1320  *
1321  * Used for SOCK_DGRAM, SOCK_RDM, and SOCK_SEQPACKET messages.
1322  * If the complete message doesn't fit in user area, truncate it.
1323  *
1324  * Returns size of returned message data, errno otherwise
1325  */
1326 static int tipc_recvmsg(struct kiocb *iocb, struct socket *sock,
1327                         struct msghdr *m, size_t buf_len, int flags)
1328 {
1329         struct sock *sk = sock->sk;
1330         struct tipc_sock *tsk = tipc_sk(sk);
1331         struct sk_buff *buf;
1332         struct tipc_msg *msg;
1333         long timeo;
1334         unsigned int sz;
1335         u32 err;
1336         int res;
1337
1338         /* Catch invalid receive requests */
1339         if (unlikely(!buf_len))
1340                 return -EINVAL;
1341
1342         lock_sock(sk);
1343
1344         if (unlikely(sock->state == SS_UNCONNECTED)) {
1345                 res = -ENOTCONN;
1346                 goto exit;
1347         }
1348
1349         timeo = sock_rcvtimeo(sk, flags & MSG_DONTWAIT);
1350 restart:
1351
1352         /* Look for a message in receive queue; wait if necessary */
1353         res = tipc_wait_for_rcvmsg(sock, &timeo);
1354         if (res)
1355                 goto exit;
1356
1357         /* Look at first message in receive queue */
1358         buf = skb_peek(&sk->sk_receive_queue);
1359         msg = buf_msg(buf);
1360         sz = msg_data_sz(msg);
1361         err = msg_errcode(msg);
1362
1363         /* Discard an empty non-errored message & try again */
1364         if ((!sz) && (!err)) {
1365                 tsk_advance_rx_queue(sk);
1366                 goto restart;
1367         }
1368
1369         /* Capture sender's address (optional) */
1370         set_orig_addr(m, msg);
1371
1372         /* Capture ancillary data (optional) */
1373         res = tipc_sk_anc_data_recv(m, msg, tsk);
1374         if (res)
1375                 goto exit;
1376
1377         /* Capture message data (if valid) & compute return value (always) */
1378         if (!err) {
1379                 if (unlikely(buf_len < sz)) {
1380                         sz = buf_len;
1381                         m->msg_flags |= MSG_TRUNC;
1382                 }
1383                 res = skb_copy_datagram_msg(buf, msg_hdr_sz(msg), m, sz);
1384                 if (res)
1385                         goto exit;
1386                 res = sz;
1387         } else {
1388                 if ((sock->state == SS_READY) ||
1389                     ((err == TIPC_CONN_SHUTDOWN) || m->msg_control))
1390                         res = 0;
1391                 else
1392                         res = -ECONNRESET;
1393         }
1394
1395         /* Consume received message (optional) */
1396         if (likely(!(flags & MSG_PEEK))) {
1397                 if ((sock->state != SS_READY) &&
1398                     (++tsk->rcv_unacked >= TIPC_CONNACK_INTV)) {
1399                         tipc_sk_send_ack(tsk, tsk->rcv_unacked);
1400                         tsk->rcv_unacked = 0;
1401                 }
1402                 tsk_advance_rx_queue(sk);
1403         }
1404 exit:
1405         release_sock(sk);
1406         return res;
1407 }
1408
1409 /**
1410  * tipc_recv_stream - receive stream-oriented data
1411  * @iocb: (unused)
1412  * @m: descriptor for message info
1413  * @buf_len: total size of user buffer area
1414  * @flags: receive flags
1415  *
1416  * Used for SOCK_STREAM messages only.  If not enough data is available
1417  * will optionally wait for more; never truncates data.
1418  *
1419  * Returns size of returned message data, errno otherwise
1420  */
1421 static int tipc_recv_stream(struct kiocb *iocb, struct socket *sock,
1422                             struct msghdr *m, size_t buf_len, int flags)
1423 {
1424         struct sock *sk = sock->sk;
1425         struct tipc_sock *tsk = tipc_sk(sk);
1426         struct sk_buff *buf;
1427         struct tipc_msg *msg;
1428         long timeo;
1429         unsigned int sz;
1430         int sz_to_copy, target, needed;
1431         int sz_copied = 0;
1432         u32 err;
1433         int res = 0;
1434
1435         /* Catch invalid receive attempts */
1436         if (unlikely(!buf_len))
1437                 return -EINVAL;
1438
1439         lock_sock(sk);
1440
1441         if (unlikely(sock->state == SS_UNCONNECTED)) {
1442                 res = -ENOTCONN;
1443                 goto exit;
1444         }
1445
1446         target = sock_rcvlowat(sk, flags & MSG_WAITALL, buf_len);
1447         timeo = sock_rcvtimeo(sk, flags & MSG_DONTWAIT);
1448
1449 restart:
1450         /* Look for a message in receive queue; wait if necessary */
1451         res = tipc_wait_for_rcvmsg(sock, &timeo);
1452         if (res)
1453                 goto exit;
1454
1455         /* Look at first message in receive queue */
1456         buf = skb_peek(&sk->sk_receive_queue);
1457         msg = buf_msg(buf);
1458         sz = msg_data_sz(msg);
1459         err = msg_errcode(msg);
1460
1461         /* Discard an empty non-errored message & try again */
1462         if ((!sz) && (!err)) {
1463                 tsk_advance_rx_queue(sk);
1464                 goto restart;
1465         }
1466
1467         /* Optionally capture sender's address & ancillary data of first msg */
1468         if (sz_copied == 0) {
1469                 set_orig_addr(m, msg);
1470                 res = tipc_sk_anc_data_recv(m, msg, tsk);
1471                 if (res)
1472                         goto exit;
1473         }
1474
1475         /* Capture message data (if valid) & compute return value (always) */
1476         if (!err) {
1477                 u32 offset = (u32)(unsigned long)(TIPC_SKB_CB(buf)->handle);
1478
1479                 sz -= offset;
1480                 needed = (buf_len - sz_copied);
1481                 sz_to_copy = (sz <= needed) ? sz : needed;
1482
1483                 res = skb_copy_datagram_msg(buf, msg_hdr_sz(msg) + offset,
1484                                             m, sz_to_copy);
1485                 if (res)
1486                         goto exit;
1487
1488                 sz_copied += sz_to_copy;
1489
1490                 if (sz_to_copy < sz) {
1491                         if (!(flags & MSG_PEEK))
1492                                 TIPC_SKB_CB(buf)->handle =
1493                                 (void *)(unsigned long)(offset + sz_to_copy);
1494                         goto exit;
1495                 }
1496         } else {
1497                 if (sz_copied != 0)
1498                         goto exit; /* can't add error msg to valid data */
1499
1500                 if ((err == TIPC_CONN_SHUTDOWN) || m->msg_control)
1501                         res = 0;
1502                 else
1503                         res = -ECONNRESET;
1504         }
1505
1506         /* Consume received message (optional) */
1507         if (likely(!(flags & MSG_PEEK))) {
1508                 if (unlikely(++tsk->rcv_unacked >= TIPC_CONNACK_INTV)) {
1509                         tipc_sk_send_ack(tsk, tsk->rcv_unacked);
1510                         tsk->rcv_unacked = 0;
1511                 }
1512                 tsk_advance_rx_queue(sk);
1513         }
1514
1515         /* Loop around if more data is required */
1516         if ((sz_copied < buf_len) &&    /* didn't get all requested data */
1517             (!skb_queue_empty(&sk->sk_receive_queue) ||
1518             (sz_copied < target)) &&    /* and more is ready or required */
1519             (!(flags & MSG_PEEK)) &&    /* and aren't just peeking at data */
1520             (!err))                     /* and haven't reached a FIN */
1521                 goto restart;
1522
1523 exit:
1524         release_sock(sk);
1525         return sz_copied ? sz_copied : res;
1526 }
1527
1528 /**
1529  * tipc_write_space - wake up thread if port congestion is released
1530  * @sk: socket
1531  */
1532 static void tipc_write_space(struct sock *sk)
1533 {
1534         struct socket_wq *wq;
1535
1536         rcu_read_lock();
1537         wq = rcu_dereference(sk->sk_wq);
1538         if (wq_has_sleeper(wq))
1539                 wake_up_interruptible_sync_poll(&wq->wait, POLLOUT |
1540                                                 POLLWRNORM | POLLWRBAND);
1541         rcu_read_unlock();
1542 }
1543
1544 /**
1545  * tipc_data_ready - wake up threads to indicate messages have been received
1546  * @sk: socket
1547  * @len: the length of messages
1548  */
1549 static void tipc_data_ready(struct sock *sk)
1550 {
1551         struct socket_wq *wq;
1552
1553         rcu_read_lock();
1554         wq = rcu_dereference(sk->sk_wq);
1555         if (wq_has_sleeper(wq))
1556                 wake_up_interruptible_sync_poll(&wq->wait, POLLIN |
1557                                                 POLLRDNORM | POLLRDBAND);
1558         rcu_read_unlock();
1559 }
1560
1561 /**
1562  * filter_connect - Handle all incoming messages for a connection-based socket
1563  * @tsk: TIPC socket
1564  * @msg: message
1565  *
1566  * Returns 0 (TIPC_OK) if everything ok, -TIPC_ERR_NO_PORT otherwise
1567  */
1568 static int filter_connect(struct tipc_sock *tsk, struct sk_buff **buf)
1569 {
1570         struct sock *sk = &tsk->sk;
1571         struct socket *sock = sk->sk_socket;
1572         struct tipc_msg *msg = buf_msg(*buf);
1573         int retval = -TIPC_ERR_NO_PORT;
1574
1575         if (msg_mcast(msg))
1576                 return retval;
1577
1578         switch ((int)sock->state) {
1579         case SS_CONNECTED:
1580                 /* Accept only connection-based messages sent by peer */
1581                 if (tsk_peer_msg(tsk, msg)) {
1582                         if (unlikely(msg_errcode(msg))) {
1583                                 sock->state = SS_DISCONNECTING;
1584                                 tsk->connected = 0;
1585                                 /* let timer expire on it's own */
1586                                 tipc_node_remove_conn(tsk_peer_node(tsk),
1587                                                       tsk->ref);
1588                         }
1589                         retval = TIPC_OK;
1590                 }
1591                 break;
1592         case SS_CONNECTING:
1593                 /* Accept only ACK or NACK message */
1594
1595                 if (unlikely(!msg_connected(msg)))
1596                         break;
1597
1598                 if (unlikely(msg_errcode(msg))) {
1599                         sock->state = SS_DISCONNECTING;
1600                         sk->sk_err = ECONNREFUSED;
1601                         retval = TIPC_OK;
1602                         break;
1603                 }
1604
1605                 if (unlikely(msg_importance(msg) > TIPC_CRITICAL_IMPORTANCE)) {
1606                         sock->state = SS_DISCONNECTING;
1607                         sk->sk_err = EINVAL;
1608                         retval = TIPC_OK;
1609                         break;
1610                 }
1611
1612                 tipc_sk_finish_conn(tsk, msg_origport(msg), msg_orignode(msg));
1613                 msg_set_importance(&tsk->phdr, msg_importance(msg));
1614                 sock->state = SS_CONNECTED;
1615
1616                 /* If an incoming message is an 'ACK-', it should be
1617                  * discarded here because it doesn't contain useful
1618                  * data. In addition, we should try to wake up
1619                  * connect() routine if sleeping.
1620                  */
1621                 if (msg_data_sz(msg) == 0) {
1622                         kfree_skb(*buf);
1623                         *buf = NULL;
1624                         if (waitqueue_active(sk_sleep(sk)))
1625                                 wake_up_interruptible(sk_sleep(sk));
1626                 }
1627                 retval = TIPC_OK;
1628                 break;
1629         case SS_LISTENING:
1630         case SS_UNCONNECTED:
1631                 /* Accept only SYN message */
1632                 if (!msg_connected(msg) && !(msg_errcode(msg)))
1633                         retval = TIPC_OK;
1634                 break;
1635         case SS_DISCONNECTING:
1636                 break;
1637         default:
1638                 pr_err("Unknown socket state %u\n", sock->state);
1639         }
1640         return retval;
1641 }
1642
1643 /**
1644  * rcvbuf_limit - get proper overload limit of socket receive queue
1645  * @sk: socket
1646  * @buf: message
1647  *
1648  * For all connection oriented messages, irrespective of importance,
1649  * the default overload value (i.e. 67MB) is set as limit.
1650  *
1651  * For all connectionless messages, by default new queue limits are
1652  * as belows:
1653  *
1654  * TIPC_LOW_IMPORTANCE       (4 MB)
1655  * TIPC_MEDIUM_IMPORTANCE    (8 MB)
1656  * TIPC_HIGH_IMPORTANCE      (16 MB)
1657  * TIPC_CRITICAL_IMPORTANCE  (32 MB)
1658  *
1659  * Returns overload limit according to corresponding message importance
1660  */
1661 static unsigned int rcvbuf_limit(struct sock *sk, struct sk_buff *buf)
1662 {
1663         struct tipc_msg *msg = buf_msg(buf);
1664
1665         if (msg_connected(msg))
1666                 return sysctl_tipc_rmem[2];
1667
1668         return sk->sk_rcvbuf >> TIPC_CRITICAL_IMPORTANCE <<
1669                 msg_importance(msg);
1670 }
1671
1672 /**
1673  * filter_rcv - validate incoming message
1674  * @sk: socket
1675  * @buf: message
1676  *
1677  * Enqueues message on receive queue if acceptable; optionally handles
1678  * disconnect indication for a connected socket.
1679  *
1680  * Called with socket lock already taken; port lock may also be taken.
1681  *
1682  * Returns 0 (TIPC_OK) if message was consumed, -TIPC error code if message
1683  * to be rejected, 1 (TIPC_FWD_MSG) if (CONN_MANAGER) message to be forwarded
1684  */
1685 static int filter_rcv(struct sock *sk, struct sk_buff *buf)
1686 {
1687         struct socket *sock = sk->sk_socket;
1688         struct tipc_sock *tsk = tipc_sk(sk);
1689         struct tipc_msg *msg = buf_msg(buf);
1690         unsigned int limit = rcvbuf_limit(sk, buf);
1691         u32 onode;
1692         int rc = TIPC_OK;
1693
1694         if (unlikely(msg_user(msg) == CONN_MANAGER))
1695                 return tipc_sk_proto_rcv(tsk, &onode, buf);
1696
1697         if (unlikely(msg_user(msg) == SOCK_WAKEUP)) {
1698                 kfree_skb(buf);
1699                 tsk->link_cong = 0;
1700                 sk->sk_write_space(sk);
1701                 return TIPC_OK;
1702         }
1703
1704         /* Reject message if it is wrong sort of message for socket */
1705         if (msg_type(msg) > TIPC_DIRECT_MSG)
1706                 return -TIPC_ERR_NO_PORT;
1707
1708         if (sock->state == SS_READY) {
1709                 if (msg_connected(msg))
1710                         return -TIPC_ERR_NO_PORT;
1711         } else {
1712                 rc = filter_connect(tsk, &buf);
1713                 if (rc != TIPC_OK || buf == NULL)
1714                         return rc;
1715         }
1716
1717         /* Reject message if there isn't room to queue it */
1718         if (sk_rmem_alloc_get(sk) + buf->truesize >= limit)
1719                 return -TIPC_ERR_OVERLOAD;
1720
1721         /* Enqueue message */
1722         TIPC_SKB_CB(buf)->handle = NULL;
1723         __skb_queue_tail(&sk->sk_receive_queue, buf);
1724         skb_set_owner_r(buf, sk);
1725
1726         sk->sk_data_ready(sk);
1727         return TIPC_OK;
1728 }
1729
1730 /**
1731  * tipc_backlog_rcv - handle incoming message from backlog queue
1732  * @sk: socket
1733  * @buf: message
1734  *
1735  * Caller must hold socket lock, but not port lock.
1736  *
1737  * Returns 0
1738  */
1739 static int tipc_backlog_rcv(struct sock *sk, struct sk_buff *buf)
1740 {
1741         int rc;
1742         u32 onode;
1743         struct tipc_sock *tsk = tipc_sk(sk);
1744         uint truesize = buf->truesize;
1745
1746         rc = filter_rcv(sk, buf);
1747
1748         if (likely(!rc)) {
1749                 if (atomic_read(&tsk->dupl_rcvcnt) < TIPC_CONN_OVERLOAD_LIMIT)
1750                         atomic_add(truesize, &tsk->dupl_rcvcnt);
1751                 return 0;
1752         }
1753
1754         if ((rc < 0) && !tipc_msg_reverse(buf, &onode, -rc))
1755                 return 0;
1756
1757         tipc_link_xmit(buf, onode, 0);
1758
1759         return 0;
1760 }
1761
1762 /**
1763  * tipc_sk_rcv - handle incoming message
1764  * @buf: buffer containing arriving message
1765  * Consumes buffer
1766  * Returns 0 if success, or errno: -EHOSTUNREACH
1767  */
1768 int tipc_sk_rcv(struct sk_buff *buf)
1769 {
1770         struct tipc_sock *tsk;
1771         struct sock *sk;
1772         u32 dport = msg_destport(buf_msg(buf));
1773         int rc = TIPC_OK;
1774         uint limit;
1775         u32 dnode;
1776
1777         /* Validate destination and message */
1778         tsk = tipc_sk_get(dport);
1779         if (unlikely(!tsk)) {
1780                 rc = tipc_msg_eval(buf, &dnode);
1781                 goto exit;
1782         }
1783         sk = &tsk->sk;
1784
1785         /* Queue message */
1786         spin_lock_bh(&sk->sk_lock.slock);
1787
1788         if (!sock_owned_by_user(sk)) {
1789                 rc = filter_rcv(sk, buf);
1790         } else {
1791                 if (sk->sk_backlog.len == 0)
1792                         atomic_set(&tsk->dupl_rcvcnt, 0);
1793                 limit = rcvbuf_limit(sk, buf) + atomic_read(&tsk->dupl_rcvcnt);
1794                 if (sk_add_backlog(sk, buf, limit))
1795                         rc = -TIPC_ERR_OVERLOAD;
1796         }
1797         spin_unlock_bh(&sk->sk_lock.slock);
1798         tipc_sk_put(tsk);
1799         if (likely(!rc))
1800                 return 0;
1801 exit:
1802         if ((rc < 0) && !tipc_msg_reverse(buf, &dnode, -rc))
1803                 return -EHOSTUNREACH;
1804
1805         tipc_link_xmit(buf, dnode, 0);
1806         return (rc < 0) ? -EHOSTUNREACH : 0;
1807 }
1808
1809 static int tipc_wait_for_connect(struct socket *sock, long *timeo_p)
1810 {
1811         struct sock *sk = sock->sk;
1812         DEFINE_WAIT(wait);
1813         int done;
1814
1815         do {
1816                 int err = sock_error(sk);
1817                 if (err)
1818                         return err;
1819                 if (!*timeo_p)
1820                         return -ETIMEDOUT;
1821                 if (signal_pending(current))
1822                         return sock_intr_errno(*timeo_p);
1823
1824                 prepare_to_wait(sk_sleep(sk), &wait, TASK_INTERRUPTIBLE);
1825                 done = sk_wait_event(sk, timeo_p, sock->state != SS_CONNECTING);
1826                 finish_wait(sk_sleep(sk), &wait);
1827         } while (!done);
1828         return 0;
1829 }
1830
1831 /**
1832  * tipc_connect - establish a connection to another TIPC port
1833  * @sock: socket structure
1834  * @dest: socket address for destination port
1835  * @destlen: size of socket address data structure
1836  * @flags: file-related flags associated with socket
1837  *
1838  * Returns 0 on success, errno otherwise
1839  */
1840 static int tipc_connect(struct socket *sock, struct sockaddr *dest,
1841                         int destlen, int flags)
1842 {
1843         struct sock *sk = sock->sk;
1844         struct sockaddr_tipc *dst = (struct sockaddr_tipc *)dest;
1845         struct msghdr m = {NULL,};
1846         long timeout = (flags & O_NONBLOCK) ? 0 : tipc_sk(sk)->conn_timeout;
1847         socket_state previous;
1848         int res;
1849
1850         lock_sock(sk);
1851
1852         /* For now, TIPC does not allow use of connect() with DGRAM/RDM types */
1853         if (sock->state == SS_READY) {
1854                 res = -EOPNOTSUPP;
1855                 goto exit;
1856         }
1857
1858         /*
1859          * Reject connection attempt using multicast address
1860          *
1861          * Note: send_msg() validates the rest of the address fields,
1862          *       so there's no need to do it here
1863          */
1864         if (dst->addrtype == TIPC_ADDR_MCAST) {
1865                 res = -EINVAL;
1866                 goto exit;
1867         }
1868
1869         previous = sock->state;
1870         switch (sock->state) {
1871         case SS_UNCONNECTED:
1872                 /* Send a 'SYN-' to destination */
1873                 m.msg_name = dest;
1874                 m.msg_namelen = destlen;
1875
1876                 /* If connect is in non-blocking case, set MSG_DONTWAIT to
1877                  * indicate send_msg() is never blocked.
1878                  */
1879                 if (!timeout)
1880                         m.msg_flags = MSG_DONTWAIT;
1881
1882                 res = tipc_sendmsg(NULL, sock, &m, 0);
1883                 if ((res < 0) && (res != -EWOULDBLOCK))
1884                         goto exit;
1885
1886                 /* Just entered SS_CONNECTING state; the only
1887                  * difference is that return value in non-blocking
1888                  * case is EINPROGRESS, rather than EALREADY.
1889                  */
1890                 res = -EINPROGRESS;
1891         case SS_CONNECTING:
1892                 if (previous == SS_CONNECTING)
1893                         res = -EALREADY;
1894                 if (!timeout)
1895                         goto exit;
1896                 timeout = msecs_to_jiffies(timeout);
1897                 /* Wait until an 'ACK' or 'RST' arrives, or a timeout occurs */
1898                 res = tipc_wait_for_connect(sock, &timeout);
1899                 break;
1900         case SS_CONNECTED:
1901                 res = -EISCONN;
1902                 break;
1903         default:
1904                 res = -EINVAL;
1905                 break;
1906         }
1907 exit:
1908         release_sock(sk);
1909         return res;
1910 }
1911
1912 /**
1913  * tipc_listen - allow socket to listen for incoming connections
1914  * @sock: socket structure
1915  * @len: (unused)
1916  *
1917  * Returns 0 on success, errno otherwise
1918  */
1919 static int tipc_listen(struct socket *sock, int len)
1920 {
1921         struct sock *sk = sock->sk;
1922         int res;
1923
1924         lock_sock(sk);
1925
1926         if (sock->state != SS_UNCONNECTED)
1927                 res = -EINVAL;
1928         else {
1929                 sock->state = SS_LISTENING;
1930                 res = 0;
1931         }
1932
1933         release_sock(sk);
1934         return res;
1935 }
1936
1937 static int tipc_wait_for_accept(struct socket *sock, long timeo)
1938 {
1939         struct sock *sk = sock->sk;
1940         DEFINE_WAIT(wait);
1941         int err;
1942
1943         /* True wake-one mechanism for incoming connections: only
1944          * one process gets woken up, not the 'whole herd'.
1945          * Since we do not 'race & poll' for established sockets
1946          * anymore, the common case will execute the loop only once.
1947         */
1948         for (;;) {
1949                 prepare_to_wait_exclusive(sk_sleep(sk), &wait,
1950                                           TASK_INTERRUPTIBLE);
1951                 if (timeo && skb_queue_empty(&sk->sk_receive_queue)) {
1952                         release_sock(sk);
1953                         timeo = schedule_timeout(timeo);
1954                         lock_sock(sk);
1955                 }
1956                 err = 0;
1957                 if (!skb_queue_empty(&sk->sk_receive_queue))
1958                         break;
1959                 err = -EINVAL;
1960                 if (sock->state != SS_LISTENING)
1961                         break;
1962                 err = sock_intr_errno(timeo);
1963                 if (signal_pending(current))
1964                         break;
1965                 err = -EAGAIN;
1966                 if (!timeo)
1967                         break;
1968         }
1969         finish_wait(sk_sleep(sk), &wait);
1970         return err;
1971 }
1972
1973 /**
1974  * tipc_accept - wait for connection request
1975  * @sock: listening socket
1976  * @newsock: new socket that is to be connected
1977  * @flags: file-related flags associated with socket
1978  *
1979  * Returns 0 on success, errno otherwise
1980  */
1981 static int tipc_accept(struct socket *sock, struct socket *new_sock, int flags)
1982 {
1983         struct sock *new_sk, *sk = sock->sk;
1984         struct sk_buff *buf;
1985         struct tipc_sock *new_tsock;
1986         struct tipc_msg *msg;
1987         long timeo;
1988         int res;
1989
1990         lock_sock(sk);
1991
1992         if (sock->state != SS_LISTENING) {
1993                 res = -EINVAL;
1994                 goto exit;
1995         }
1996         timeo = sock_rcvtimeo(sk, flags & O_NONBLOCK);
1997         res = tipc_wait_for_accept(sock, timeo);
1998         if (res)
1999                 goto exit;
2000
2001         buf = skb_peek(&sk->sk_receive_queue);
2002
2003         res = tipc_sk_create(sock_net(sock->sk), new_sock, 0, 1);
2004         if (res)
2005                 goto exit;
2006
2007         new_sk = new_sock->sk;
2008         new_tsock = tipc_sk(new_sk);
2009         msg = buf_msg(buf);
2010
2011         /* we lock on new_sk; but lockdep sees the lock on sk */
2012         lock_sock_nested(new_sk, SINGLE_DEPTH_NESTING);
2013
2014         /*
2015          * Reject any stray messages received by new socket
2016          * before the socket lock was taken (very, very unlikely)
2017          */
2018         tsk_rej_rx_queue(new_sk);
2019
2020         /* Connect new socket to it's peer */
2021         tipc_sk_finish_conn(new_tsock, msg_origport(msg), msg_orignode(msg));
2022         new_sock->state = SS_CONNECTED;
2023
2024         tsk_set_importance(new_tsock, msg_importance(msg));
2025         if (msg_named(msg)) {
2026                 new_tsock->conn_type = msg_nametype(msg);
2027                 new_tsock->conn_instance = msg_nameinst(msg);
2028         }
2029
2030         /*
2031          * Respond to 'SYN-' by discarding it & returning 'ACK'-.
2032          * Respond to 'SYN+' by queuing it on new socket.
2033          */
2034         if (!msg_data_sz(msg)) {
2035                 struct msghdr m = {NULL,};
2036
2037                 tsk_advance_rx_queue(sk);
2038                 tipc_send_packet(NULL, new_sock, &m, 0);
2039         } else {
2040                 __skb_dequeue(&sk->sk_receive_queue);
2041                 __skb_queue_head(&new_sk->sk_receive_queue, buf);
2042                 skb_set_owner_r(buf, new_sk);
2043         }
2044         release_sock(new_sk);
2045 exit:
2046         release_sock(sk);
2047         return res;
2048 }
2049
2050 /**
2051  * tipc_shutdown - shutdown socket connection
2052  * @sock: socket structure
2053  * @how: direction to close (must be SHUT_RDWR)
2054  *
2055  * Terminates connection (if necessary), then purges socket's receive queue.
2056  *
2057  * Returns 0 on success, errno otherwise
2058  */
2059 static int tipc_shutdown(struct socket *sock, int how)
2060 {
2061         struct sock *sk = sock->sk;
2062         struct tipc_sock *tsk = tipc_sk(sk);
2063         struct sk_buff *buf;
2064         u32 dnode;
2065         int res;
2066
2067         if (how != SHUT_RDWR)
2068                 return -EINVAL;
2069
2070         lock_sock(sk);
2071
2072         switch (sock->state) {
2073         case SS_CONNECTING:
2074         case SS_CONNECTED:
2075
2076 restart:
2077                 /* Disconnect and send a 'FIN+' or 'FIN-' message to peer */
2078                 buf = __skb_dequeue(&sk->sk_receive_queue);
2079                 if (buf) {
2080                         if (TIPC_SKB_CB(buf)->handle != NULL) {
2081                                 kfree_skb(buf);
2082                                 goto restart;
2083                         }
2084                         if (tipc_msg_reverse(buf, &dnode, TIPC_CONN_SHUTDOWN))
2085                                 tipc_link_xmit(buf, dnode, tsk->ref);
2086                         tipc_node_remove_conn(dnode, tsk->ref);
2087                 } else {
2088                         dnode = tsk_peer_node(tsk);
2089                         buf = tipc_msg_create(TIPC_CRITICAL_IMPORTANCE,
2090                                               TIPC_CONN_MSG, SHORT_H_SIZE,
2091                                               0, dnode, tipc_own_addr,
2092                                               tsk_peer_port(tsk),
2093                                               tsk->ref, TIPC_CONN_SHUTDOWN);
2094                         tipc_link_xmit(buf, dnode, tsk->ref);
2095                 }
2096                 tsk->connected = 0;
2097                 sock->state = SS_DISCONNECTING;
2098                 tipc_node_remove_conn(dnode, tsk->ref);
2099                 /* fall through */
2100
2101         case SS_DISCONNECTING:
2102
2103                 /* Discard any unreceived messages */
2104                 __skb_queue_purge(&sk->sk_receive_queue);
2105
2106                 /* Wake up anyone sleeping in poll */
2107                 sk->sk_state_change(sk);
2108                 res = 0;
2109                 break;
2110
2111         default:
2112                 res = -ENOTCONN;
2113         }
2114
2115         release_sock(sk);
2116         return res;
2117 }
2118
2119 static void tipc_sk_timeout(unsigned long ref)
2120 {
2121         struct tipc_sock *tsk;
2122         struct sock *sk;
2123         struct sk_buff *buf = NULL;
2124         u32 peer_port, peer_node;
2125
2126         tsk = tipc_sk_get(ref);
2127         if (!tsk)
2128                 return;
2129
2130         sk = &tsk->sk;
2131         bh_lock_sock(sk);
2132         if (!tsk->connected) {
2133                 bh_unlock_sock(sk);
2134                 goto exit;
2135         }
2136         peer_port = tsk_peer_port(tsk);
2137         peer_node = tsk_peer_node(tsk);
2138
2139         if (tsk->probing_state == TIPC_CONN_PROBING) {
2140                 /* Previous probe not answered -> self abort */
2141                 buf = tipc_msg_create(TIPC_CRITICAL_IMPORTANCE, TIPC_CONN_MSG,
2142                                       SHORT_H_SIZE, 0, tipc_own_addr,
2143                                       peer_node, ref, peer_port,
2144                                       TIPC_ERR_NO_PORT);
2145         } else {
2146                 buf = tipc_msg_create(CONN_MANAGER, CONN_PROBE, INT_H_SIZE,
2147                                       0, peer_node, tipc_own_addr,
2148                                       peer_port, ref, TIPC_OK);
2149                 tsk->probing_state = TIPC_CONN_PROBING;
2150                 k_start_timer(&tsk->timer, tsk->probing_interval);
2151         }
2152         bh_unlock_sock(sk);
2153         if (buf)
2154                 tipc_link_xmit(buf, peer_node, ref);
2155 exit:
2156         tipc_sk_put(tsk);
2157 }
2158
2159 static int tipc_sk_publish(struct tipc_sock *tsk, uint scope,
2160                            struct tipc_name_seq const *seq)
2161 {
2162         struct publication *publ;
2163         u32 key;
2164
2165         if (tsk->connected)
2166                 return -EINVAL;
2167         key = tsk->ref + tsk->pub_count + 1;
2168         if (key == tsk->ref)
2169                 return -EADDRINUSE;
2170
2171         publ = tipc_nametbl_publish(seq->type, seq->lower, seq->upper,
2172                                     scope, tsk->ref, key);
2173         if (unlikely(!publ))
2174                 return -EINVAL;
2175
2176         list_add(&publ->pport_list, &tsk->publications);
2177         tsk->pub_count++;
2178         tsk->published = 1;
2179         return 0;
2180 }
2181
2182 static int tipc_sk_withdraw(struct tipc_sock *tsk, uint scope,
2183                             struct tipc_name_seq const *seq)
2184 {
2185         struct publication *publ;
2186         struct publication *safe;
2187         int rc = -EINVAL;
2188
2189         list_for_each_entry_safe(publ, safe, &tsk->publications, pport_list) {
2190                 if (seq) {
2191                         if (publ->scope != scope)
2192                                 continue;
2193                         if (publ->type != seq->type)
2194                                 continue;
2195                         if (publ->lower != seq->lower)
2196                                 continue;
2197                         if (publ->upper != seq->upper)
2198                                 break;
2199                         tipc_nametbl_withdraw(publ->type, publ->lower,
2200                                               publ->ref, publ->key);
2201                         rc = 0;
2202                         break;
2203                 }
2204                 tipc_nametbl_withdraw(publ->type, publ->lower,
2205                                       publ->ref, publ->key);
2206                 rc = 0;
2207         }
2208         if (list_empty(&tsk->publications))
2209                 tsk->published = 0;
2210         return rc;
2211 }
2212
2213 static int tipc_sk_show(struct tipc_sock *tsk, char *buf,
2214                         int len, int full_id)
2215 {
2216         struct publication *publ;
2217         int ret;
2218
2219         if (full_id)
2220                 ret = tipc_snprintf(buf, len, "<%u.%u.%u:%u>:",
2221                                     tipc_zone(tipc_own_addr),
2222                                     tipc_cluster(tipc_own_addr),
2223                                     tipc_node(tipc_own_addr), tsk->ref);
2224         else
2225                 ret = tipc_snprintf(buf, len, "%-10u:", tsk->ref);
2226
2227         if (tsk->connected) {
2228                 u32 dport = tsk_peer_port(tsk);
2229                 u32 destnode = tsk_peer_node(tsk);
2230
2231                 ret += tipc_snprintf(buf + ret, len - ret,
2232                                      " connected to <%u.%u.%u:%u>",
2233                                      tipc_zone(destnode),
2234                                      tipc_cluster(destnode),
2235                                      tipc_node(destnode), dport);
2236                 if (tsk->conn_type != 0)
2237                         ret += tipc_snprintf(buf + ret, len - ret,
2238                                              " via {%u,%u}", tsk->conn_type,
2239                                              tsk->conn_instance);
2240         } else if (tsk->published) {
2241                 ret += tipc_snprintf(buf + ret, len - ret, " bound to");
2242                 list_for_each_entry(publ, &tsk->publications, pport_list) {
2243                         if (publ->lower == publ->upper)
2244                                 ret += tipc_snprintf(buf + ret, len - ret,
2245                                                      " {%u,%u}", publ->type,
2246                                                      publ->lower);
2247                         else
2248                                 ret += tipc_snprintf(buf + ret, len - ret,
2249                                                      " {%u,%u,%u}", publ->type,
2250                                                      publ->lower, publ->upper);
2251                 }
2252         }
2253         ret += tipc_snprintf(buf + ret, len - ret, "\n");
2254         return ret;
2255 }
2256
2257 struct sk_buff *tipc_sk_socks_show(void)
2258 {
2259         struct sk_buff *buf;
2260         struct tlv_desc *rep_tlv;
2261         char *pb;
2262         int pb_len;
2263         struct tipc_sock *tsk;
2264         int str_len = 0;
2265         u32 ref = 0;
2266
2267         buf = tipc_cfg_reply_alloc(TLV_SPACE(ULTRA_STRING_MAX_LEN));
2268         if (!buf)
2269                 return NULL;
2270         rep_tlv = (struct tlv_desc *)buf->data;
2271         pb = TLV_DATA(rep_tlv);
2272         pb_len = ULTRA_STRING_MAX_LEN;
2273
2274         tsk = tipc_sk_get_next(&ref);
2275         for (; tsk; tsk = tipc_sk_get_next(&ref)) {
2276                 lock_sock(&tsk->sk);
2277                 str_len += tipc_sk_show(tsk, pb + str_len,
2278                                         pb_len - str_len, 0);
2279                 release_sock(&tsk->sk);
2280                 tipc_sk_put(tsk);
2281         }
2282         str_len += 1;   /* for "\0" */
2283         skb_put(buf, TLV_SPACE(str_len));
2284         TLV_SET(rep_tlv, TIPC_TLV_ULTRA_STRING, NULL, str_len);
2285
2286         return buf;
2287 }
2288
2289 /* tipc_sk_reinit: set non-zero address in all existing sockets
2290  *                 when we go from standalone to network mode.
2291  */
2292 void tipc_sk_reinit(void)
2293 {
2294         struct tipc_msg *msg;
2295         u32 ref = 0;
2296         struct tipc_sock *tsk = tipc_sk_get_next(&ref);
2297
2298         for (; tsk; tsk = tipc_sk_get_next(&ref)) {
2299                 lock_sock(&tsk->sk);
2300                 msg = &tsk->phdr;
2301                 msg_set_prevnode(msg, tipc_own_addr);
2302                 msg_set_orignode(msg, tipc_own_addr);
2303                 release_sock(&tsk->sk);
2304                 tipc_sk_put(tsk);
2305         }
2306 }
2307
2308 /**
2309  * struct reference - TIPC socket reference entry
2310  * @tsk: pointer to socket associated with reference entry
2311  * @ref: reference value for socket (combines instance & array index info)
2312  */
2313 struct reference {
2314         struct tipc_sock *tsk;
2315         u32 ref;
2316 };
2317
2318 /**
2319  * struct tipc_ref_table - table of TIPC socket reference entries
2320  * @entries: pointer to array of reference entries
2321  * @capacity: array index of first unusable entry
2322  * @init_point: array index of first uninitialized entry
2323  * @first_free: array index of first unused socket reference entry
2324  * @last_free: array index of last unused socket reference entry
2325  * @index_mask: bitmask for array index portion of reference values
2326  * @start_mask: initial value for instance value portion of reference values
2327  */
2328 struct ref_table {
2329         struct reference *entries;
2330         u32 capacity;
2331         u32 init_point;
2332         u32 first_free;
2333         u32 last_free;
2334         u32 index_mask;
2335         u32 start_mask;
2336 };
2337
2338 /* Socket reference table consists of 2**N entries.
2339  *
2340  * State        Socket ptr      Reference
2341  * -----        ----------      ---------
2342  * In use        non-NULL       XXXX|own index
2343  *                              (XXXX changes each time entry is acquired)
2344  * Free            NULL         YYYY|next free index
2345  *                              (YYYY is one more than last used XXXX)
2346  * Uninitialized   NULL         0
2347  *
2348  * Entry 0 is not used; this allows index 0 to denote the end of the free list.
2349  *
2350  * Note that a reference value of 0 does not necessarily indicate that an
2351  * entry is uninitialized, since the last entry in the free list could also
2352  * have a reference value of 0 (although this is unlikely).
2353  */
2354
2355 static struct ref_table tipc_ref_table;
2356
2357 static DEFINE_RWLOCK(ref_table_lock);
2358
2359 /**
2360  * tipc_ref_table_init - create reference table for sockets
2361  */
2362 int tipc_sk_ref_table_init(u32 req_sz, u32 start)
2363 {
2364         struct reference *table;
2365         u32 actual_sz;
2366
2367         /* account for unused entry, then round up size to a power of 2 */
2368
2369         req_sz++;
2370         for (actual_sz = 16; actual_sz < req_sz; actual_sz <<= 1) {
2371                 /* do nothing */
2372         };
2373
2374         /* allocate table & mark all entries as uninitialized */
2375         table = vzalloc(actual_sz * sizeof(struct reference));
2376         if (table == NULL)
2377                 return -ENOMEM;
2378
2379         tipc_ref_table.entries = table;
2380         tipc_ref_table.capacity = req_sz;
2381         tipc_ref_table.init_point = 1;
2382         tipc_ref_table.first_free = 0;
2383         tipc_ref_table.last_free = 0;
2384         tipc_ref_table.index_mask = actual_sz - 1;
2385         tipc_ref_table.start_mask = start & ~tipc_ref_table.index_mask;
2386
2387         return 0;
2388 }
2389
2390 /**
2391  * tipc_ref_table_stop - destroy reference table for sockets
2392  */
2393 void tipc_sk_ref_table_stop(void)
2394 {
2395         if (!tipc_ref_table.entries)
2396                 return;
2397         vfree(tipc_ref_table.entries);
2398         tipc_ref_table.entries = NULL;
2399 }
2400
2401 /* tipc_ref_acquire - create reference to a socket
2402  *
2403  * Register an socket pointer in the reference table.
2404  * Returns a unique reference value that is used from then on to retrieve the
2405  * socket pointer, or to determine if the socket has been deregistered.
2406  */
2407 u32 tipc_sk_ref_acquire(struct tipc_sock *tsk)
2408 {
2409         u32 index;
2410         u32 index_mask;
2411         u32 next_plus_upper;
2412         u32 ref = 0;
2413         struct reference *entry;
2414
2415         if (unlikely(!tsk)) {
2416                 pr_err("Attempt to acquire ref. to non-existent obj\n");
2417                 return 0;
2418         }
2419         if (unlikely(!tipc_ref_table.entries)) {
2420                 pr_err("Ref. table not found in acquisition attempt\n");
2421                 return 0;
2422         }
2423
2424         /* Take a free entry, if available; otherwise initialize a new one */
2425         write_lock_bh(&ref_table_lock);
2426         index = tipc_ref_table.first_free;
2427         entry = &tipc_ref_table.entries[index];
2428
2429         if (likely(index)) {
2430                 index = tipc_ref_table.first_free;
2431                 entry = &tipc_ref_table.entries[index];
2432                 index_mask = tipc_ref_table.index_mask;
2433                 next_plus_upper = entry->ref;
2434                 tipc_ref_table.first_free = next_plus_upper & index_mask;
2435                 ref = (next_plus_upper & ~index_mask) + index;
2436                 entry->tsk = tsk;
2437         } else if (tipc_ref_table.init_point < tipc_ref_table.capacity) {
2438                 index = tipc_ref_table.init_point++;
2439                 entry = &tipc_ref_table.entries[index];
2440                 ref = tipc_ref_table.start_mask + index;
2441         }
2442
2443         if (ref) {
2444                 entry->ref = ref;
2445                 entry->tsk = tsk;
2446         }
2447         write_unlock_bh(&ref_table_lock);
2448         return ref;
2449 }
2450
2451 /* tipc_sk_ref_discard - invalidate reference to an socket
2452  *
2453  * Disallow future references to an socket and free up the entry for re-use.
2454  */
2455 void tipc_sk_ref_discard(u32 ref)
2456 {
2457         struct reference *entry;
2458         u32 index;
2459         u32 index_mask;
2460
2461         if (unlikely(!tipc_ref_table.entries)) {
2462                 pr_err("Ref. table not found during discard attempt\n");
2463                 return;
2464         }
2465
2466         index_mask = tipc_ref_table.index_mask;
2467         index = ref & index_mask;
2468         entry = &tipc_ref_table.entries[index];
2469
2470         write_lock_bh(&ref_table_lock);
2471
2472         if (unlikely(!entry->tsk)) {
2473                 pr_err("Attempt to discard ref. to non-existent socket\n");
2474                 goto exit;
2475         }
2476         if (unlikely(entry->ref != ref)) {
2477                 pr_err("Attempt to discard non-existent reference\n");
2478                 goto exit;
2479         }
2480
2481         /* Mark entry as unused; increment instance part of entry's
2482          *   reference to invalidate any subsequent references
2483          */
2484
2485         entry->tsk = NULL;
2486         entry->ref = (ref & ~index_mask) + (index_mask + 1);
2487
2488         /* Append entry to free entry list */
2489         if (unlikely(tipc_ref_table.first_free == 0))
2490                 tipc_ref_table.first_free = index;
2491         else
2492                 tipc_ref_table.entries[tipc_ref_table.last_free].ref |= index;
2493         tipc_ref_table.last_free = index;
2494 exit:
2495         write_unlock_bh(&ref_table_lock);
2496 }
2497
2498 /* tipc_sk_get - find referenced socket and return pointer to it
2499  */
2500 struct tipc_sock *tipc_sk_get(u32 ref)
2501 {
2502         struct reference *entry;
2503         struct tipc_sock *tsk;
2504
2505         if (unlikely(!tipc_ref_table.entries))
2506                 return NULL;
2507         read_lock_bh(&ref_table_lock);
2508         entry = &tipc_ref_table.entries[ref & tipc_ref_table.index_mask];
2509         tsk = entry->tsk;
2510         if (likely(tsk && (entry->ref == ref)))
2511                 sock_hold(&tsk->sk);
2512         else
2513                 tsk = NULL;
2514         read_unlock_bh(&ref_table_lock);
2515         return tsk;
2516 }
2517
2518 /* tipc_sk_get_next - lock & return next socket after referenced one
2519 */
2520 struct tipc_sock *tipc_sk_get_next(u32 *ref)
2521 {
2522         struct reference *entry;
2523         struct tipc_sock *tsk = NULL;
2524         uint index = *ref & tipc_ref_table.index_mask;
2525
2526         read_lock_bh(&ref_table_lock);
2527         while (++index < tipc_ref_table.capacity) {
2528                 entry = &tipc_ref_table.entries[index];
2529                 if (!entry->tsk)
2530                         continue;
2531                 tsk = entry->tsk;
2532                 sock_hold(&tsk->sk);
2533                 *ref = entry->ref;
2534                 break;
2535         }
2536         read_unlock_bh(&ref_table_lock);
2537         return tsk;
2538 }
2539
2540 static void tipc_sk_put(struct tipc_sock *tsk)
2541 {
2542         sock_put(&tsk->sk);
2543 }
2544
2545 /**
2546  * tipc_setsockopt - set socket option
2547  * @sock: socket structure
2548  * @lvl: option level
2549  * @opt: option identifier
2550  * @ov: pointer to new option value
2551  * @ol: length of option value
2552  *
2553  * For stream sockets only, accepts and ignores all IPPROTO_TCP options
2554  * (to ease compatibility).
2555  *
2556  * Returns 0 on success, errno otherwise
2557  */
2558 static int tipc_setsockopt(struct socket *sock, int lvl, int opt,
2559                            char __user *ov, unsigned int ol)
2560 {
2561         struct sock *sk = sock->sk;
2562         struct tipc_sock *tsk = tipc_sk(sk);
2563         u32 value;
2564         int res;
2565
2566         if ((lvl == IPPROTO_TCP) && (sock->type == SOCK_STREAM))
2567                 return 0;
2568         if (lvl != SOL_TIPC)
2569                 return -ENOPROTOOPT;
2570         if (ol < sizeof(value))
2571                 return -EINVAL;
2572         res = get_user(value, (u32 __user *)ov);
2573         if (res)
2574                 return res;
2575
2576         lock_sock(sk);
2577
2578         switch (opt) {
2579         case TIPC_IMPORTANCE:
2580                 res = tsk_set_importance(tsk, value);
2581                 break;
2582         case TIPC_SRC_DROPPABLE:
2583                 if (sock->type != SOCK_STREAM)
2584                         tsk_set_unreliable(tsk, value);
2585                 else
2586                         res = -ENOPROTOOPT;
2587                 break;
2588         case TIPC_DEST_DROPPABLE:
2589                 tsk_set_unreturnable(tsk, value);
2590                 break;
2591         case TIPC_CONN_TIMEOUT:
2592                 tipc_sk(sk)->conn_timeout = value;
2593                 /* no need to set "res", since already 0 at this point */
2594                 break;
2595         default:
2596                 res = -EINVAL;
2597         }
2598
2599         release_sock(sk);
2600
2601         return res;
2602 }
2603
2604 /**
2605  * tipc_getsockopt - get socket option
2606  * @sock: socket structure
2607  * @lvl: option level
2608  * @opt: option identifier
2609  * @ov: receptacle for option value
2610  * @ol: receptacle for length of option value
2611  *
2612  * For stream sockets only, returns 0 length result for all IPPROTO_TCP options
2613  * (to ease compatibility).
2614  *
2615  * Returns 0 on success, errno otherwise
2616  */
2617 static int tipc_getsockopt(struct socket *sock, int lvl, int opt,
2618                            char __user *ov, int __user *ol)
2619 {
2620         struct sock *sk = sock->sk;
2621         struct tipc_sock *tsk = tipc_sk(sk);
2622         int len;
2623         u32 value;
2624         int res;
2625
2626         if ((lvl == IPPROTO_TCP) && (sock->type == SOCK_STREAM))
2627                 return put_user(0, ol);
2628         if (lvl != SOL_TIPC)
2629                 return -ENOPROTOOPT;
2630         res = get_user(len, ol);
2631         if (res)
2632                 return res;
2633
2634         lock_sock(sk);
2635
2636         switch (opt) {
2637         case TIPC_IMPORTANCE:
2638                 value = tsk_importance(tsk);
2639                 break;
2640         case TIPC_SRC_DROPPABLE:
2641                 value = tsk_unreliable(tsk);
2642                 break;
2643         case TIPC_DEST_DROPPABLE:
2644                 value = tsk_unreturnable(tsk);
2645                 break;
2646         case TIPC_CONN_TIMEOUT:
2647                 value = tsk->conn_timeout;
2648                 /* no need to set "res", since already 0 at this point */
2649                 break;
2650         case TIPC_NODE_RECVQ_DEPTH:
2651                 value = 0; /* was tipc_queue_size, now obsolete */
2652                 break;
2653         case TIPC_SOCK_RECVQ_DEPTH:
2654                 value = skb_queue_len(&sk->sk_receive_queue);
2655                 break;
2656         default:
2657                 res = -EINVAL;
2658         }
2659
2660         release_sock(sk);
2661
2662         if (res)
2663                 return res;     /* "get" failed */
2664
2665         if (len < sizeof(value))
2666                 return -EINVAL;
2667
2668         if (copy_to_user(ov, &value, sizeof(value)))
2669                 return -EFAULT;
2670
2671         return put_user(sizeof(value), ol);
2672 }
2673
2674 static int tipc_ioctl(struct socket *sk, unsigned int cmd, unsigned long arg)
2675 {
2676         struct tipc_sioc_ln_req lnr;
2677         void __user *argp = (void __user *)arg;
2678
2679         switch (cmd) {
2680         case SIOCGETLINKNAME:
2681                 if (copy_from_user(&lnr, argp, sizeof(lnr)))
2682                         return -EFAULT;
2683                 if (!tipc_node_get_linkname(lnr.bearer_id & 0xffff, lnr.peer,
2684                                             lnr.linkname, TIPC_MAX_LINK_NAME)) {
2685                         if (copy_to_user(argp, &lnr, sizeof(lnr)))
2686                                 return -EFAULT;
2687                         return 0;
2688                 }
2689                 return -EADDRNOTAVAIL;
2690         default:
2691                 return -ENOIOCTLCMD;
2692         }
2693 }
2694
2695 /* Protocol switches for the various types of TIPC sockets */
2696
2697 static const struct proto_ops msg_ops = {
2698         .owner          = THIS_MODULE,
2699         .family         = AF_TIPC,
2700         .release        = tipc_release,
2701         .bind           = tipc_bind,
2702         .connect        = tipc_connect,
2703         .socketpair     = sock_no_socketpair,
2704         .accept         = sock_no_accept,
2705         .getname        = tipc_getname,
2706         .poll           = tipc_poll,
2707         .ioctl          = tipc_ioctl,
2708         .listen         = sock_no_listen,
2709         .shutdown       = tipc_shutdown,
2710         .setsockopt     = tipc_setsockopt,
2711         .getsockopt     = tipc_getsockopt,
2712         .sendmsg        = tipc_sendmsg,
2713         .recvmsg        = tipc_recvmsg,
2714         .mmap           = sock_no_mmap,
2715         .sendpage       = sock_no_sendpage
2716 };
2717
2718 static const struct proto_ops packet_ops = {
2719         .owner          = THIS_MODULE,
2720         .family         = AF_TIPC,
2721         .release        = tipc_release,
2722         .bind           = tipc_bind,
2723         .connect        = tipc_connect,
2724         .socketpair     = sock_no_socketpair,
2725         .accept         = tipc_accept,
2726         .getname        = tipc_getname,
2727         .poll           = tipc_poll,
2728         .ioctl          = tipc_ioctl,
2729         .listen         = tipc_listen,
2730         .shutdown       = tipc_shutdown,
2731         .setsockopt     = tipc_setsockopt,
2732         .getsockopt     = tipc_getsockopt,
2733         .sendmsg        = tipc_send_packet,
2734         .recvmsg        = tipc_recvmsg,
2735         .mmap           = sock_no_mmap,
2736         .sendpage       = sock_no_sendpage
2737 };
2738
2739 static const struct proto_ops stream_ops = {
2740         .owner          = THIS_MODULE,
2741         .family         = AF_TIPC,
2742         .release        = tipc_release,
2743         .bind           = tipc_bind,
2744         .connect        = tipc_connect,
2745         .socketpair     = sock_no_socketpair,
2746         .accept         = tipc_accept,
2747         .getname        = tipc_getname,
2748         .poll           = tipc_poll,
2749         .ioctl          = tipc_ioctl,
2750         .listen         = tipc_listen,
2751         .shutdown       = tipc_shutdown,
2752         .setsockopt     = tipc_setsockopt,
2753         .getsockopt     = tipc_getsockopt,
2754         .sendmsg        = tipc_send_stream,
2755         .recvmsg        = tipc_recv_stream,
2756         .mmap           = sock_no_mmap,
2757         .sendpage       = sock_no_sendpage
2758 };
2759
2760 static const struct net_proto_family tipc_family_ops = {
2761         .owner          = THIS_MODULE,
2762         .family         = AF_TIPC,
2763         .create         = tipc_sk_create
2764 };
2765
2766 static struct proto tipc_proto = {
2767         .name           = "TIPC",
2768         .owner          = THIS_MODULE,
2769         .obj_size       = sizeof(struct tipc_sock),
2770         .sysctl_rmem    = sysctl_tipc_rmem
2771 };
2772
2773 static struct proto tipc_proto_kern = {
2774         .name           = "TIPC",
2775         .obj_size       = sizeof(struct tipc_sock),
2776         .sysctl_rmem    = sysctl_tipc_rmem
2777 };
2778
2779 /**
2780  * tipc_socket_init - initialize TIPC socket interface
2781  *
2782  * Returns 0 on success, errno otherwise
2783  */
2784 int tipc_socket_init(void)
2785 {
2786         int res;
2787
2788         res = proto_register(&tipc_proto, 1);
2789         if (res) {
2790                 pr_err("Failed to register TIPC protocol type\n");
2791                 goto out;
2792         }
2793
2794         res = sock_register(&tipc_family_ops);
2795         if (res) {
2796                 pr_err("Failed to register TIPC socket type\n");
2797                 proto_unregister(&tipc_proto);
2798                 goto out;
2799         }
2800  out:
2801         return res;
2802 }
2803
2804 /**
2805  * tipc_socket_stop - stop TIPC socket interface
2806  */
2807 void tipc_socket_stop(void)
2808 {
2809         sock_unregister(tipc_family_ops.family);
2810         proto_unregister(&tipc_proto);
2811 }
2812
2813 /* Caller should hold socket lock for the passed tipc socket. */
2814 int __tipc_nl_add_sk_con(struct sk_buff *skb, struct tipc_sock *tsk)
2815 {
2816         u32 peer_node;
2817         u32 peer_port;
2818         struct nlattr *nest;
2819
2820         peer_node = tsk_peer_node(tsk);
2821         peer_port = tsk_peer_port(tsk);
2822
2823         nest = nla_nest_start(skb, TIPC_NLA_SOCK_CON);
2824
2825         if (nla_put_u32(skb, TIPC_NLA_CON_NODE, peer_node))
2826                 goto msg_full;
2827         if (nla_put_u32(skb, TIPC_NLA_CON_SOCK, peer_port))
2828                 goto msg_full;
2829
2830         if (tsk->conn_type != 0) {
2831                 if (nla_put_flag(skb, TIPC_NLA_CON_FLAG))
2832                         goto msg_full;
2833                 if (nla_put_u32(skb, TIPC_NLA_CON_TYPE, tsk->conn_type))
2834                         goto msg_full;
2835                 if (nla_put_u32(skb, TIPC_NLA_CON_INST, tsk->conn_instance))
2836                         goto msg_full;
2837         }
2838         nla_nest_end(skb, nest);
2839
2840         return 0;
2841
2842 msg_full:
2843         nla_nest_cancel(skb, nest);
2844
2845         return -EMSGSIZE;
2846 }
2847
2848 /* Caller should hold socket lock for the passed tipc socket. */
2849 int __tipc_nl_add_sk(struct sk_buff *skb, struct netlink_callback *cb,
2850                      struct tipc_sock *tsk)
2851 {
2852         int err;
2853         void *hdr;
2854         struct nlattr *attrs;
2855
2856         hdr = genlmsg_put(skb, NETLINK_CB(cb->skb).portid, cb->nlh->nlmsg_seq,
2857                           &tipc_genl_v2_family, NLM_F_MULTI, TIPC_NL_SOCK_GET);
2858         if (!hdr)
2859                 goto msg_cancel;
2860
2861         attrs = nla_nest_start(skb, TIPC_NLA_SOCK);
2862         if (!attrs)
2863                 goto genlmsg_cancel;
2864         if (nla_put_u32(skb, TIPC_NLA_SOCK_REF, tsk->ref))
2865                 goto attr_msg_cancel;
2866         if (nla_put_u32(skb, TIPC_NLA_SOCK_ADDR, tipc_own_addr))
2867                 goto attr_msg_cancel;
2868
2869         if (tsk->connected) {
2870                 err = __tipc_nl_add_sk_con(skb, tsk);
2871                 if (err)
2872                         goto attr_msg_cancel;
2873         } else if (!list_empty(&tsk->publications)) {
2874                 if (nla_put_flag(skb, TIPC_NLA_SOCK_HAS_PUBL))
2875                         goto attr_msg_cancel;
2876         }
2877         nla_nest_end(skb, attrs);
2878         genlmsg_end(skb, hdr);
2879
2880         return 0;
2881
2882 attr_msg_cancel:
2883         nla_nest_cancel(skb, attrs);
2884 genlmsg_cancel:
2885         genlmsg_cancel(skb, hdr);
2886 msg_cancel:
2887         return -EMSGSIZE;
2888 }
2889
2890 int tipc_nl_sk_dump(struct sk_buff *skb, struct netlink_callback *cb)
2891 {
2892         int err;
2893         struct tipc_sock *tsk;
2894         u32 prev_ref = cb->args[0];
2895         u32 ref = prev_ref;
2896
2897         tsk = tipc_sk_get_next(&ref);
2898         for (; tsk; tsk = tipc_sk_get_next(&ref)) {
2899                 lock_sock(&tsk->sk);
2900                 err = __tipc_nl_add_sk(skb, cb, tsk);
2901                 release_sock(&tsk->sk);
2902                 tipc_sk_put(tsk);
2903                 if (err)
2904                         break;
2905
2906                 prev_ref = ref;
2907         }
2908
2909         cb->args[0] = prev_ref;
2910
2911         return skb->len;
2912 }
2913
2914 /* Caller should hold socket lock for the passed tipc socket. */
2915 int __tipc_nl_add_sk_publ(struct sk_buff *skb, struct netlink_callback *cb,
2916                           struct publication *publ)
2917 {
2918         void *hdr;
2919         struct nlattr *attrs;
2920
2921         hdr = genlmsg_put(skb, NETLINK_CB(cb->skb).portid, cb->nlh->nlmsg_seq,
2922                           &tipc_genl_v2_family, NLM_F_MULTI, TIPC_NL_PUBL_GET);
2923         if (!hdr)
2924                 goto msg_cancel;
2925
2926         attrs = nla_nest_start(skb, TIPC_NLA_PUBL);
2927         if (!attrs)
2928                 goto genlmsg_cancel;
2929
2930         if (nla_put_u32(skb, TIPC_NLA_PUBL_KEY, publ->key))
2931                 goto attr_msg_cancel;
2932         if (nla_put_u32(skb, TIPC_NLA_PUBL_TYPE, publ->type))
2933                 goto attr_msg_cancel;
2934         if (nla_put_u32(skb, TIPC_NLA_PUBL_LOWER, publ->lower))
2935                 goto attr_msg_cancel;
2936         if (nla_put_u32(skb, TIPC_NLA_PUBL_UPPER, publ->upper))
2937                 goto attr_msg_cancel;
2938
2939         nla_nest_end(skb, attrs);
2940         genlmsg_end(skb, hdr);
2941
2942         return 0;
2943
2944 attr_msg_cancel:
2945         nla_nest_cancel(skb, attrs);
2946 genlmsg_cancel:
2947         genlmsg_cancel(skb, hdr);
2948 msg_cancel:
2949         return -EMSGSIZE;
2950 }
2951
2952 /* Caller should hold socket lock for the passed tipc socket. */
2953 int __tipc_nl_list_sk_publ(struct sk_buff *skb, struct netlink_callback *cb,
2954                            struct tipc_sock *tsk, u32 *last_publ)
2955 {
2956         int err;
2957         struct publication *p;
2958
2959         if (*last_publ) {
2960                 list_for_each_entry(p, &tsk->publications, pport_list) {
2961                         if (p->key == *last_publ)
2962                                 break;
2963                 }
2964                 if (p->key != *last_publ) {
2965                         /* We never set seq or call nl_dump_check_consistent()
2966                          * this means that setting prev_seq here will cause the
2967                          * consistence check to fail in the netlink callback
2968                          * handler. Resulting in the last NLMSG_DONE message
2969                          * having the NLM_F_DUMP_INTR flag set.
2970                          */
2971                         cb->prev_seq = 1;
2972                         *last_publ = 0;
2973                         return -EPIPE;
2974                 }
2975         } else {
2976                 p = list_first_entry(&tsk->publications, struct publication,
2977                                      pport_list);
2978         }
2979
2980         list_for_each_entry_from(p, &tsk->publications, pport_list) {
2981                 err = __tipc_nl_add_sk_publ(skb, cb, p);
2982                 if (err) {
2983                         *last_publ = p->key;
2984                         return err;
2985                 }
2986         }
2987         *last_publ = 0;
2988
2989         return 0;
2990 }
2991
2992 int tipc_nl_publ_dump(struct sk_buff *skb, struct netlink_callback *cb)
2993 {
2994         int err;
2995         u32 tsk_ref = cb->args[0];
2996         u32 last_publ = cb->args[1];
2997         u32 done = cb->args[2];
2998         struct tipc_sock *tsk;
2999
3000         if (!tsk_ref) {
3001                 struct nlattr **attrs;
3002                 struct nlattr *sock[TIPC_NLA_SOCK_MAX + 1];
3003
3004                 err = tipc_nlmsg_parse(cb->nlh, &attrs);
3005                 if (err)
3006                         return err;
3007
3008                 err = nla_parse_nested(sock, TIPC_NLA_SOCK_MAX,
3009                                        attrs[TIPC_NLA_SOCK],
3010                                        tipc_nl_sock_policy);
3011                 if (err)
3012                         return err;
3013
3014                 if (!sock[TIPC_NLA_SOCK_REF])
3015                         return -EINVAL;
3016
3017                 tsk_ref = nla_get_u32(sock[TIPC_NLA_SOCK_REF]);
3018         }
3019
3020         if (done)
3021                 return 0;
3022
3023         tsk = tipc_sk_get(tsk_ref);
3024         if (!tsk)
3025                 return -EINVAL;
3026
3027         lock_sock(&tsk->sk);
3028         err = __tipc_nl_list_sk_publ(skb, cb, tsk, &last_publ);
3029         if (!err)
3030                 done = 1;
3031         release_sock(&tsk->sk);
3032         tipc_sk_put(tsk);
3033
3034         cb->args[0] = tsk_ref;
3035         cb->args[1] = last_publ;
3036         cb->args[2] = done;
3037
3038         return skb->len;
3039 }