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