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