GNU Linux-libre 5.10.153-gnu1
[releases.git] / net / tipc / socket.c
1 /*
2  * net/tipc/socket.c: TIPC socket API
3  *
4  * Copyright (c) 2001-2007, 2012-2017, 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 #include "group.h"
49 #include "trace.h"
50
51 #define NAGLE_START_INIT        4
52 #define NAGLE_START_MAX         1024
53 #define CONN_TIMEOUT_DEFAULT    8000    /* default connect timeout = 8s */
54 #define CONN_PROBING_INTV       msecs_to_jiffies(3600000)  /* [ms] => 1 h */
55 #define TIPC_MAX_PORT           0xffffffff
56 #define TIPC_MIN_PORT           1
57 #define TIPC_ACK_RATE           4       /* ACK at 1/4 of rcv window size */
58
59 enum {
60         TIPC_LISTEN = TCP_LISTEN,
61         TIPC_ESTABLISHED = TCP_ESTABLISHED,
62         TIPC_OPEN = TCP_CLOSE,
63         TIPC_DISCONNECTING = TCP_CLOSE_WAIT,
64         TIPC_CONNECTING = TCP_SYN_SENT,
65 };
66
67 struct sockaddr_pair {
68         struct sockaddr_tipc sock;
69         struct sockaddr_tipc member;
70 };
71
72 /**
73  * struct tipc_sock - TIPC socket structure
74  * @sk: socket - interacts with 'port' and with user via the socket API
75  * @conn_type: TIPC type used when connection was established
76  * @conn_instance: TIPC instance used when connection was established
77  * @published: non-zero if port has one or more associated names
78  * @max_pkt: maximum packet size "hint" used when building messages sent by port
79  * @maxnagle: maximum size of msg which can be subject to nagle
80  * @portid: unique port identity in TIPC socket hash table
81  * @phdr: preformatted message header used when sending messages
82  * #cong_links: list of congested links
83  * @publications: list of publications for port
84  * @blocking_link: address of the congested link we are currently sleeping on
85  * @pub_count: total # of publications port has made during its lifetime
86  * @conn_timeout: the time we can wait for an unresponded setup request
87  * @dupl_rcvcnt: number of bytes counted twice, in both backlog and rcv queue
88  * @cong_link_cnt: number of congested links
89  * @snt_unacked: # messages sent by socket, and not yet acked by peer
90  * @rcv_unacked: # messages read by user, but not yet acked back to peer
91  * @peer: 'connected' peer for dgram/rdm
92  * @node: hash table node
93  * @mc_method: cookie for use between socket and broadcast layer
94  * @rcu: rcu struct for tipc_sock
95  */
96 struct tipc_sock {
97         struct sock sk;
98         u32 conn_type;
99         u32 conn_instance;
100         int published;
101         u32 max_pkt;
102         u32 maxnagle;
103         u32 portid;
104         struct tipc_msg phdr;
105         struct list_head cong_links;
106         struct list_head publications;
107         u32 pub_count;
108         atomic_t dupl_rcvcnt;
109         u16 conn_timeout;
110         bool probe_unacked;
111         u16 cong_link_cnt;
112         u16 snt_unacked;
113         u16 snd_win;
114         u16 peer_caps;
115         u16 rcv_unacked;
116         u16 rcv_win;
117         struct sockaddr_tipc peer;
118         struct rhash_head node;
119         struct tipc_mc_method mc_method;
120         struct rcu_head rcu;
121         struct tipc_group *group;
122         u32 oneway;
123         u32 nagle_start;
124         u16 snd_backlog;
125         u16 msg_acc;
126         u16 pkt_cnt;
127         bool expect_ack;
128         bool nodelay;
129         bool group_is_open;
130 };
131
132 static int tipc_sk_backlog_rcv(struct sock *sk, struct sk_buff *skb);
133 static void tipc_data_ready(struct sock *sk);
134 static void tipc_write_space(struct sock *sk);
135 static void tipc_sock_destruct(struct sock *sk);
136 static int tipc_release(struct socket *sock);
137 static int tipc_accept(struct socket *sock, struct socket *new_sock, int flags,
138                        bool kern);
139 static void tipc_sk_timeout(struct timer_list *t);
140 static int tipc_sk_publish(struct tipc_sock *tsk, uint scope,
141                            struct tipc_name_seq const *seq);
142 static int tipc_sk_withdraw(struct tipc_sock *tsk, uint scope,
143                             struct tipc_name_seq const *seq);
144 static int tipc_sk_leave(struct tipc_sock *tsk);
145 static struct tipc_sock *tipc_sk_lookup(struct net *net, u32 portid);
146 static int tipc_sk_insert(struct tipc_sock *tsk);
147 static void tipc_sk_remove(struct tipc_sock *tsk);
148 static int __tipc_sendstream(struct socket *sock, struct msghdr *m, size_t dsz);
149 static int __tipc_sendmsg(struct socket *sock, struct msghdr *m, size_t dsz);
150 static void tipc_sk_push_backlog(struct tipc_sock *tsk, bool nagle_ack);
151 static int tipc_wait_for_connect(struct socket *sock, long *timeo_p);
152
153 static const struct proto_ops packet_ops;
154 static const struct proto_ops stream_ops;
155 static const struct proto_ops msg_ops;
156 static struct proto tipc_proto;
157 static const struct rhashtable_params tsk_rht_params;
158
159 static u32 tsk_own_node(struct tipc_sock *tsk)
160 {
161         return msg_prevnode(&tsk->phdr);
162 }
163
164 static u32 tsk_peer_node(struct tipc_sock *tsk)
165 {
166         return msg_destnode(&tsk->phdr);
167 }
168
169 static u32 tsk_peer_port(struct tipc_sock *tsk)
170 {
171         return msg_destport(&tsk->phdr);
172 }
173
174 static  bool tsk_unreliable(struct tipc_sock *tsk)
175 {
176         return msg_src_droppable(&tsk->phdr) != 0;
177 }
178
179 static void tsk_set_unreliable(struct tipc_sock *tsk, bool unreliable)
180 {
181         msg_set_src_droppable(&tsk->phdr, unreliable ? 1 : 0);
182 }
183
184 static bool tsk_unreturnable(struct tipc_sock *tsk)
185 {
186         return msg_dest_droppable(&tsk->phdr) != 0;
187 }
188
189 static void tsk_set_unreturnable(struct tipc_sock *tsk, bool unreturnable)
190 {
191         msg_set_dest_droppable(&tsk->phdr, unreturnable ? 1 : 0);
192 }
193
194 static int tsk_importance(struct tipc_sock *tsk)
195 {
196         return msg_importance(&tsk->phdr);
197 }
198
199 static struct tipc_sock *tipc_sk(const struct sock *sk)
200 {
201         return container_of(sk, struct tipc_sock, sk);
202 }
203
204 int tsk_set_importance(struct sock *sk, int imp)
205 {
206         if (imp > TIPC_CRITICAL_IMPORTANCE)
207                 return -EINVAL;
208         msg_set_importance(&tipc_sk(sk)->phdr, (u32)imp);
209         return 0;
210 }
211
212 static bool tsk_conn_cong(struct tipc_sock *tsk)
213 {
214         return tsk->snt_unacked > tsk->snd_win;
215 }
216
217 static u16 tsk_blocks(int len)
218 {
219         return ((len / FLOWCTL_BLK_SZ) + 1);
220 }
221
222 /* tsk_blocks(): translate a buffer size in bytes to number of
223  * advertisable blocks, taking into account the ratio truesize(len)/len
224  * We can trust that this ratio is always < 4 for len >= FLOWCTL_BLK_SZ
225  */
226 static u16 tsk_adv_blocks(int len)
227 {
228         return len / FLOWCTL_BLK_SZ / 4;
229 }
230
231 /* tsk_inc(): increment counter for sent or received data
232  * - If block based flow control is not supported by peer we
233  *   fall back to message based ditto, incrementing the counter
234  */
235 static u16 tsk_inc(struct tipc_sock *tsk, int msglen)
236 {
237         if (likely(tsk->peer_caps & TIPC_BLOCK_FLOWCTL))
238                 return ((msglen / FLOWCTL_BLK_SZ) + 1);
239         return 1;
240 }
241
242 /* tsk_set_nagle - enable/disable nagle property by manipulating maxnagle
243  */
244 static void tsk_set_nagle(struct tipc_sock *tsk)
245 {
246         struct sock *sk = &tsk->sk;
247
248         tsk->maxnagle = 0;
249         if (sk->sk_type != SOCK_STREAM)
250                 return;
251         if (tsk->nodelay)
252                 return;
253         if (!(tsk->peer_caps & TIPC_NAGLE))
254                 return;
255         /* Limit node local buffer size to avoid receive queue overflow */
256         if (tsk->max_pkt == MAX_MSG_SIZE)
257                 tsk->maxnagle = 1500;
258         else
259                 tsk->maxnagle = tsk->max_pkt;
260 }
261
262 /**
263  * tsk_advance_rx_queue - discard first buffer in socket receive queue
264  *
265  * Caller must hold socket lock
266  */
267 static void tsk_advance_rx_queue(struct sock *sk)
268 {
269         trace_tipc_sk_advance_rx(sk, NULL, TIPC_DUMP_SK_RCVQ, " ");
270         kfree_skb(__skb_dequeue(&sk->sk_receive_queue));
271 }
272
273 /* tipc_sk_respond() : send response message back to sender
274  */
275 static void tipc_sk_respond(struct sock *sk, struct sk_buff *skb, int err)
276 {
277         u32 selector;
278         u32 dnode;
279         u32 onode = tipc_own_addr(sock_net(sk));
280
281         if (!tipc_msg_reverse(onode, &skb, err))
282                 return;
283
284         trace_tipc_sk_rej_msg(sk, skb, TIPC_DUMP_NONE, "@sk_respond!");
285         dnode = msg_destnode(buf_msg(skb));
286         selector = msg_origport(buf_msg(skb));
287         tipc_node_xmit_skb(sock_net(sk), skb, dnode, selector);
288 }
289
290 /**
291  * tsk_rej_rx_queue - reject all buffers in socket receive queue
292  *
293  * Caller must hold socket lock
294  */
295 static void tsk_rej_rx_queue(struct sock *sk, int error)
296 {
297         struct sk_buff *skb;
298
299         while ((skb = __skb_dequeue(&sk->sk_receive_queue)))
300                 tipc_sk_respond(sk, skb, error);
301 }
302
303 static bool tipc_sk_connected(struct sock *sk)
304 {
305         return sk->sk_state == TIPC_ESTABLISHED;
306 }
307
308 /* tipc_sk_type_connectionless - check if the socket is datagram socket
309  * @sk: socket
310  *
311  * Returns true if connection less, false otherwise
312  */
313 static bool tipc_sk_type_connectionless(struct sock *sk)
314 {
315         return sk->sk_type == SOCK_RDM || sk->sk_type == SOCK_DGRAM;
316 }
317
318 /* tsk_peer_msg - verify if message was sent by connected port's peer
319  *
320  * Handles cases where the node's network address has changed from
321  * the default of <0.0.0> to its configured setting.
322  */
323 static bool tsk_peer_msg(struct tipc_sock *tsk, struct tipc_msg *msg)
324 {
325         struct sock *sk = &tsk->sk;
326         u32 self = tipc_own_addr(sock_net(sk));
327         u32 peer_port = tsk_peer_port(tsk);
328         u32 orig_node, peer_node;
329
330         if (unlikely(!tipc_sk_connected(sk)))
331                 return false;
332
333         if (unlikely(msg_origport(msg) != peer_port))
334                 return false;
335
336         orig_node = msg_orignode(msg);
337         peer_node = tsk_peer_node(tsk);
338
339         if (likely(orig_node == peer_node))
340                 return true;
341
342         if (!orig_node && peer_node == self)
343                 return true;
344
345         if (!peer_node && orig_node == self)
346                 return true;
347
348         return false;
349 }
350
351 /* tipc_set_sk_state - set the sk_state of the socket
352  * @sk: socket
353  *
354  * Caller must hold socket lock
355  *
356  * Returns 0 on success, errno otherwise
357  */
358 static int tipc_set_sk_state(struct sock *sk, int state)
359 {
360         int oldsk_state = sk->sk_state;
361         int res = -EINVAL;
362
363         switch (state) {
364         case TIPC_OPEN:
365                 res = 0;
366                 break;
367         case TIPC_LISTEN:
368         case TIPC_CONNECTING:
369                 if (oldsk_state == TIPC_OPEN)
370                         res = 0;
371                 break;
372         case TIPC_ESTABLISHED:
373                 if (oldsk_state == TIPC_CONNECTING ||
374                     oldsk_state == TIPC_OPEN)
375                         res = 0;
376                 break;
377         case TIPC_DISCONNECTING:
378                 if (oldsk_state == TIPC_CONNECTING ||
379                     oldsk_state == TIPC_ESTABLISHED)
380                         res = 0;
381                 break;
382         }
383
384         if (!res)
385                 sk->sk_state = state;
386
387         return res;
388 }
389
390 static int tipc_sk_sock_err(struct socket *sock, long *timeout)
391 {
392         struct sock *sk = sock->sk;
393         int err = sock_error(sk);
394         int typ = sock->type;
395
396         if (err)
397                 return err;
398         if (typ == SOCK_STREAM || typ == SOCK_SEQPACKET) {
399                 if (sk->sk_state == TIPC_DISCONNECTING)
400                         return -EPIPE;
401                 else if (!tipc_sk_connected(sk))
402                         return -ENOTCONN;
403         }
404         if (!*timeout)
405                 return -EAGAIN;
406         if (signal_pending(current))
407                 return sock_intr_errno(*timeout);
408
409         return 0;
410 }
411
412 #define tipc_wait_for_cond(sock_, timeo_, condition_)                          \
413 ({                                                                             \
414         DEFINE_WAIT_FUNC(wait_, woken_wake_function);                          \
415         struct sock *sk_;                                                      \
416         int rc_;                                                               \
417                                                                                \
418         while ((rc_ = !(condition_))) {                                        \
419                 /* coupled with smp_wmb() in tipc_sk_proto_rcv() */            \
420                 smp_rmb();                                                     \
421                 sk_ = (sock_)->sk;                                             \
422                 rc_ = tipc_sk_sock_err((sock_), timeo_);                       \
423                 if (rc_)                                                       \
424                         break;                                                 \
425                 add_wait_queue(sk_sleep(sk_), &wait_);                         \
426                 release_sock(sk_);                                             \
427                 *(timeo_) = wait_woken(&wait_, TASK_INTERRUPTIBLE, *(timeo_)); \
428                 sched_annotate_sleep();                                        \
429                 lock_sock(sk_);                                                \
430                 remove_wait_queue(sk_sleep(sk_), &wait_);                      \
431         }                                                                      \
432         rc_;                                                                   \
433 })
434
435 /**
436  * tipc_sk_create - create a TIPC socket
437  * @net: network namespace (must be default network)
438  * @sock: pre-allocated socket structure
439  * @protocol: protocol indicator (must be 0)
440  * @kern: caused by kernel or by userspace?
441  *
442  * This routine creates additional data structures used by the TIPC socket,
443  * initializes them, and links them together.
444  *
445  * Returns 0 on success, errno otherwise
446  */
447 static int tipc_sk_create(struct net *net, struct socket *sock,
448                           int protocol, int kern)
449 {
450         const struct proto_ops *ops;
451         struct sock *sk;
452         struct tipc_sock *tsk;
453         struct tipc_msg *msg;
454
455         /* Validate arguments */
456         if (unlikely(protocol != 0))
457                 return -EPROTONOSUPPORT;
458
459         switch (sock->type) {
460         case SOCK_STREAM:
461                 ops = &stream_ops;
462                 break;
463         case SOCK_SEQPACKET:
464                 ops = &packet_ops;
465                 break;
466         case SOCK_DGRAM:
467         case SOCK_RDM:
468                 ops = &msg_ops;
469                 break;
470         default:
471                 return -EPROTOTYPE;
472         }
473
474         /* Allocate socket's protocol area */
475         sk = sk_alloc(net, AF_TIPC, GFP_KERNEL, &tipc_proto, kern);
476         if (sk == NULL)
477                 return -ENOMEM;
478
479         tsk = tipc_sk(sk);
480         tsk->max_pkt = MAX_PKT_DEFAULT;
481         tsk->maxnagle = 0;
482         tsk->nagle_start = NAGLE_START_INIT;
483         INIT_LIST_HEAD(&tsk->publications);
484         INIT_LIST_HEAD(&tsk->cong_links);
485         msg = &tsk->phdr;
486
487         /* Finish initializing socket data structures */
488         sock->ops = ops;
489         sock_init_data(sock, sk);
490         tipc_set_sk_state(sk, TIPC_OPEN);
491         if (tipc_sk_insert(tsk)) {
492                 sk_free(sk);
493                 pr_warn("Socket create failed; port number exhausted\n");
494                 return -EINVAL;
495         }
496
497         /* Ensure tsk is visible before we read own_addr. */
498         smp_mb();
499
500         tipc_msg_init(tipc_own_addr(net), msg, TIPC_LOW_IMPORTANCE,
501                       TIPC_NAMED_MSG, NAMED_H_SIZE, 0);
502
503         msg_set_origport(msg, tsk->portid);
504         timer_setup(&sk->sk_timer, tipc_sk_timeout, 0);
505         sk->sk_shutdown = 0;
506         sk->sk_backlog_rcv = tipc_sk_backlog_rcv;
507         sk->sk_rcvbuf = READ_ONCE(sysctl_tipc_rmem[1]);
508         sk->sk_data_ready = tipc_data_ready;
509         sk->sk_write_space = tipc_write_space;
510         sk->sk_destruct = tipc_sock_destruct;
511         tsk->conn_timeout = CONN_TIMEOUT_DEFAULT;
512         tsk->group_is_open = true;
513         atomic_set(&tsk->dupl_rcvcnt, 0);
514
515         /* Start out with safe limits until we receive an advertised window */
516         tsk->snd_win = tsk_adv_blocks(RCVBUF_MIN);
517         tsk->rcv_win = tsk->snd_win;
518
519         if (tipc_sk_type_connectionless(sk)) {
520                 tsk_set_unreturnable(tsk, true);
521                 if (sock->type == SOCK_DGRAM)
522                         tsk_set_unreliable(tsk, true);
523         }
524         __skb_queue_head_init(&tsk->mc_method.deferredq);
525         trace_tipc_sk_create(sk, NULL, TIPC_DUMP_NONE, " ");
526         return 0;
527 }
528
529 static void tipc_sk_callback(struct rcu_head *head)
530 {
531         struct tipc_sock *tsk = container_of(head, struct tipc_sock, rcu);
532
533         sock_put(&tsk->sk);
534 }
535
536 /* Caller should hold socket lock for the socket. */
537 static void __tipc_shutdown(struct socket *sock, int error)
538 {
539         struct sock *sk = sock->sk;
540         struct tipc_sock *tsk = tipc_sk(sk);
541         struct net *net = sock_net(sk);
542         long timeout = msecs_to_jiffies(CONN_TIMEOUT_DEFAULT);
543         u32 dnode = tsk_peer_node(tsk);
544         struct sk_buff *skb;
545
546         /* Avoid that hi-prio shutdown msgs bypass msgs in link wakeup queue */
547         tipc_wait_for_cond(sock, &timeout, (!tsk->cong_link_cnt &&
548                                             !tsk_conn_cong(tsk)));
549
550         /* Push out delayed messages if in Nagle mode */
551         tipc_sk_push_backlog(tsk, false);
552         /* Remove pending SYN */
553         __skb_queue_purge(&sk->sk_write_queue);
554
555         /* Remove partially received buffer if any */
556         skb = skb_peek(&sk->sk_receive_queue);
557         if (skb && TIPC_SKB_CB(skb)->bytes_read) {
558                 __skb_unlink(skb, &sk->sk_receive_queue);
559                 kfree_skb(skb);
560         }
561
562         /* Reject all unreceived messages if connectionless */
563         if (tipc_sk_type_connectionless(sk)) {
564                 tsk_rej_rx_queue(sk, error);
565                 return;
566         }
567
568         switch (sk->sk_state) {
569         case TIPC_CONNECTING:
570         case TIPC_ESTABLISHED:
571                 tipc_set_sk_state(sk, TIPC_DISCONNECTING);
572                 tipc_node_remove_conn(net, dnode, tsk->portid);
573                 /* Send a FIN+/- to its peer */
574                 skb = __skb_dequeue(&sk->sk_receive_queue);
575                 if (skb) {
576                         __skb_queue_purge(&sk->sk_receive_queue);
577                         tipc_sk_respond(sk, skb, error);
578                         break;
579                 }
580                 skb = tipc_msg_create(TIPC_CRITICAL_IMPORTANCE,
581                                       TIPC_CONN_MSG, SHORT_H_SIZE, 0, dnode,
582                                       tsk_own_node(tsk), tsk_peer_port(tsk),
583                                       tsk->portid, error);
584                 if (skb)
585                         tipc_node_xmit_skb(net, skb, dnode, tsk->portid);
586                 break;
587         case TIPC_LISTEN:
588                 /* Reject all SYN messages */
589                 tsk_rej_rx_queue(sk, error);
590                 break;
591         default:
592                 __skb_queue_purge(&sk->sk_receive_queue);
593                 break;
594         }
595 }
596
597 /**
598  * tipc_release - destroy a TIPC socket
599  * @sock: socket to destroy
600  *
601  * This routine cleans up any messages that are still queued on the socket.
602  * For DGRAM and RDM socket types, all queued messages are rejected.
603  * For SEQPACKET and STREAM socket types, the first message is rejected
604  * and any others are discarded.  (If the first message on a STREAM socket
605  * is partially-read, it is discarded and the next one is rejected instead.)
606  *
607  * NOTE: Rejected messages are not necessarily returned to the sender!  They
608  * are returned or discarded according to the "destination droppable" setting
609  * specified for the message by the sender.
610  *
611  * Returns 0 on success, errno otherwise
612  */
613 static int tipc_release(struct socket *sock)
614 {
615         struct sock *sk = sock->sk;
616         struct tipc_sock *tsk;
617
618         /*
619          * Exit if socket isn't fully initialized (occurs when a failed accept()
620          * releases a pre-allocated child socket that was never used)
621          */
622         if (sk == NULL)
623                 return 0;
624
625         tsk = tipc_sk(sk);
626         lock_sock(sk);
627
628         trace_tipc_sk_release(sk, NULL, TIPC_DUMP_ALL, " ");
629         __tipc_shutdown(sock, TIPC_ERR_NO_PORT);
630         sk->sk_shutdown = SHUTDOWN_MASK;
631         tipc_sk_leave(tsk);
632         tipc_sk_withdraw(tsk, 0, NULL);
633         __skb_queue_purge(&tsk->mc_method.deferredq);
634         sk_stop_timer(sk, &sk->sk_timer);
635         tipc_sk_remove(tsk);
636
637         sock_orphan(sk);
638         /* Reject any messages that accumulated in backlog queue */
639         release_sock(sk);
640         tipc_dest_list_purge(&tsk->cong_links);
641         tsk->cong_link_cnt = 0;
642         call_rcu(&tsk->rcu, tipc_sk_callback);
643         sock->sk = NULL;
644
645         return 0;
646 }
647
648 /**
649  * tipc_bind - associate or disassocate TIPC name(s) with a socket
650  * @sock: socket structure
651  * @uaddr: socket address describing name(s) and desired operation
652  * @uaddr_len: size of socket address data structure
653  *
654  * Name and name sequence binding is indicated using a positive scope value;
655  * a negative scope value unbinds the specified name.  Specifying no name
656  * (i.e. a socket address length of 0) unbinds all names from the socket.
657  *
658  * Returns 0 on success, errno otherwise
659  *
660  * NOTE: This routine doesn't need to take the socket lock since it doesn't
661  *       access any non-constant socket information.
662  */
663 static int tipc_bind(struct socket *sock, struct sockaddr *uaddr,
664                      int uaddr_len)
665 {
666         struct sock *sk = sock->sk;
667         struct sockaddr_tipc *addr = (struct sockaddr_tipc *)uaddr;
668         struct tipc_sock *tsk = tipc_sk(sk);
669         int res = -EINVAL;
670
671         lock_sock(sk);
672         if (unlikely(!uaddr_len)) {
673                 res = tipc_sk_withdraw(tsk, 0, NULL);
674                 goto exit;
675         }
676         if (tsk->group) {
677                 res = -EACCES;
678                 goto exit;
679         }
680         if (uaddr_len < sizeof(struct sockaddr_tipc)) {
681                 res = -EINVAL;
682                 goto exit;
683         }
684         if (addr->family != AF_TIPC) {
685                 res = -EAFNOSUPPORT;
686                 goto exit;
687         }
688
689         if (addr->addrtype == TIPC_ADDR_NAME)
690                 addr->addr.nameseq.upper = addr->addr.nameseq.lower;
691         else if (addr->addrtype != TIPC_ADDR_NAMESEQ) {
692                 res = -EAFNOSUPPORT;
693                 goto exit;
694         }
695
696         if ((addr->addr.nameseq.type < TIPC_RESERVED_TYPES) &&
697             (addr->addr.nameseq.type != TIPC_TOP_SRV) &&
698             (addr->addr.nameseq.type != TIPC_CFG_SRV)) {
699                 res = -EACCES;
700                 goto exit;
701         }
702
703         res = (addr->scope >= 0) ?
704                 tipc_sk_publish(tsk, addr->scope, &addr->addr.nameseq) :
705                 tipc_sk_withdraw(tsk, -addr->scope, &addr->addr.nameseq);
706 exit:
707         release_sock(sk);
708         return res;
709 }
710
711 /**
712  * tipc_getname - get port ID of socket or peer socket
713  * @sock: socket structure
714  * @uaddr: area for returned socket address
715  * @peer: 0 = own ID, 1 = current peer ID, 2 = current/former peer ID
716  *
717  * Returns 0 on success, errno otherwise
718  *
719  * NOTE: This routine doesn't need to take the socket lock since it only
720  *       accesses socket information that is unchanging (or which changes in
721  *       a completely predictable manner).
722  */
723 static int tipc_getname(struct socket *sock, struct sockaddr *uaddr,
724                         int peer)
725 {
726         struct sockaddr_tipc *addr = (struct sockaddr_tipc *)uaddr;
727         struct sock *sk = sock->sk;
728         struct tipc_sock *tsk = tipc_sk(sk);
729
730         memset(addr, 0, sizeof(*addr));
731         if (peer) {
732                 if ((!tipc_sk_connected(sk)) &&
733                     ((peer != 2) || (sk->sk_state != TIPC_DISCONNECTING)))
734                         return -ENOTCONN;
735                 addr->addr.id.ref = tsk_peer_port(tsk);
736                 addr->addr.id.node = tsk_peer_node(tsk);
737         } else {
738                 addr->addr.id.ref = tsk->portid;
739                 addr->addr.id.node = tipc_own_addr(sock_net(sk));
740         }
741
742         addr->addrtype = TIPC_ADDR_ID;
743         addr->family = AF_TIPC;
744         addr->scope = 0;
745         addr->addr.name.domain = 0;
746
747         return sizeof(*addr);
748 }
749
750 /**
751  * tipc_poll - read and possibly block on pollmask
752  * @file: file structure associated with the socket
753  * @sock: socket for which to calculate the poll bits
754  * @wait: ???
755  *
756  * Returns pollmask value
757  *
758  * COMMENTARY:
759  * It appears that the usual socket locking mechanisms are not useful here
760  * since the pollmask info is potentially out-of-date the moment this routine
761  * exits.  TCP and other protocols seem to rely on higher level poll routines
762  * to handle any preventable race conditions, so TIPC will do the same ...
763  *
764  * IMPORTANT: The fact that a read or write operation is indicated does NOT
765  * imply that the operation will succeed, merely that it should be performed
766  * and will not block.
767  */
768 static __poll_t tipc_poll(struct file *file, struct socket *sock,
769                               poll_table *wait)
770 {
771         struct sock *sk = sock->sk;
772         struct tipc_sock *tsk = tipc_sk(sk);
773         __poll_t revents = 0;
774
775         sock_poll_wait(file, sock, wait);
776         trace_tipc_sk_poll(sk, NULL, TIPC_DUMP_ALL, " ");
777
778         if (sk->sk_shutdown & RCV_SHUTDOWN)
779                 revents |= EPOLLRDHUP | EPOLLIN | EPOLLRDNORM;
780         if (sk->sk_shutdown == SHUTDOWN_MASK)
781                 revents |= EPOLLHUP;
782
783         switch (sk->sk_state) {
784         case TIPC_ESTABLISHED:
785                 if (!tsk->cong_link_cnt && !tsk_conn_cong(tsk))
786                         revents |= EPOLLOUT;
787                 fallthrough;
788         case TIPC_LISTEN:
789         case TIPC_CONNECTING:
790                 if (!skb_queue_empty_lockless(&sk->sk_receive_queue))
791                         revents |= EPOLLIN | EPOLLRDNORM;
792                 break;
793         case TIPC_OPEN:
794                 if (tsk->group_is_open && !tsk->cong_link_cnt)
795                         revents |= EPOLLOUT;
796                 if (!tipc_sk_type_connectionless(sk))
797                         break;
798                 if (skb_queue_empty_lockless(&sk->sk_receive_queue))
799                         break;
800                 revents |= EPOLLIN | EPOLLRDNORM;
801                 break;
802         case TIPC_DISCONNECTING:
803                 revents = EPOLLIN | EPOLLRDNORM | EPOLLHUP;
804                 break;
805         }
806         return revents;
807 }
808
809 /**
810  * tipc_sendmcast - send multicast message
811  * @sock: socket structure
812  * @seq: destination address
813  * @msg: message to send
814  * @dlen: length of data to send
815  * @timeout: timeout to wait for wakeup
816  *
817  * Called from function tipc_sendmsg(), which has done all sanity checks
818  * Returns the number of bytes sent on success, or errno
819  */
820 static int tipc_sendmcast(struct  socket *sock, struct tipc_name_seq *seq,
821                           struct msghdr *msg, size_t dlen, long timeout)
822 {
823         struct sock *sk = sock->sk;
824         struct tipc_sock *tsk = tipc_sk(sk);
825         struct tipc_msg *hdr = &tsk->phdr;
826         struct net *net = sock_net(sk);
827         int mtu = tipc_bcast_get_mtu(net);
828         struct tipc_mc_method *method = &tsk->mc_method;
829         struct sk_buff_head pkts;
830         struct tipc_nlist dsts;
831         int rc;
832
833         if (tsk->group)
834                 return -EACCES;
835
836         /* Block or return if any destination link is congested */
837         rc = tipc_wait_for_cond(sock, &timeout, !tsk->cong_link_cnt);
838         if (unlikely(rc))
839                 return rc;
840
841         /* Lookup destination nodes */
842         tipc_nlist_init(&dsts, tipc_own_addr(net));
843         tipc_nametbl_lookup_dst_nodes(net, seq->type, seq->lower,
844                                       seq->upper, &dsts);
845         if (!dsts.local && !dsts.remote)
846                 return -EHOSTUNREACH;
847
848         /* Build message header */
849         msg_set_type(hdr, TIPC_MCAST_MSG);
850         msg_set_hdr_sz(hdr, MCAST_H_SIZE);
851         msg_set_lookup_scope(hdr, TIPC_CLUSTER_SCOPE);
852         msg_set_destport(hdr, 0);
853         msg_set_destnode(hdr, 0);
854         msg_set_nametype(hdr, seq->type);
855         msg_set_namelower(hdr, seq->lower);
856         msg_set_nameupper(hdr, seq->upper);
857
858         /* Build message as chain of buffers */
859         __skb_queue_head_init(&pkts);
860         rc = tipc_msg_build(hdr, msg, 0, dlen, mtu, &pkts);
861
862         /* Send message if build was successful */
863         if (unlikely(rc == dlen)) {
864                 trace_tipc_sk_sendmcast(sk, skb_peek(&pkts),
865                                         TIPC_DUMP_SK_SNDQ, " ");
866                 rc = tipc_mcast_xmit(net, &pkts, method, &dsts,
867                                      &tsk->cong_link_cnt);
868         }
869
870         tipc_nlist_purge(&dsts);
871
872         return rc ? rc : dlen;
873 }
874
875 /**
876  * tipc_send_group_msg - send a message to a member in the group
877  * @net: network namespace
878  * @m: message to send
879  * @mb: group member
880  * @dnode: destination node
881  * @dport: destination port
882  * @dlen: total length of message data
883  */
884 static int tipc_send_group_msg(struct net *net, struct tipc_sock *tsk,
885                                struct msghdr *m, struct tipc_member *mb,
886                                u32 dnode, u32 dport, int dlen)
887 {
888         u16 bc_snd_nxt = tipc_group_bc_snd_nxt(tsk->group);
889         struct tipc_mc_method *method = &tsk->mc_method;
890         int blks = tsk_blocks(GROUP_H_SIZE + dlen);
891         struct tipc_msg *hdr = &tsk->phdr;
892         struct sk_buff_head pkts;
893         int mtu, rc;
894
895         /* Complete message header */
896         msg_set_type(hdr, TIPC_GRP_UCAST_MSG);
897         msg_set_hdr_sz(hdr, GROUP_H_SIZE);
898         msg_set_destport(hdr, dport);
899         msg_set_destnode(hdr, dnode);
900         msg_set_grp_bc_seqno(hdr, bc_snd_nxt);
901
902         /* Build message as chain of buffers */
903         __skb_queue_head_init(&pkts);
904         mtu = tipc_node_get_mtu(net, dnode, tsk->portid, false);
905         rc = tipc_msg_build(hdr, m, 0, dlen, mtu, &pkts);
906         if (unlikely(rc != dlen))
907                 return rc;
908
909         /* Send message */
910         rc = tipc_node_xmit(net, &pkts, dnode, tsk->portid);
911         if (unlikely(rc == -ELINKCONG)) {
912                 tipc_dest_push(&tsk->cong_links, dnode, 0);
913                 tsk->cong_link_cnt++;
914         }
915
916         /* Update send window */
917         tipc_group_update_member(mb, blks);
918
919         /* A broadcast sent within next EXPIRE period must follow same path */
920         method->rcast = true;
921         method->mandatory = true;
922         return dlen;
923 }
924
925 /**
926  * tipc_send_group_unicast - send message to a member in the group
927  * @sock: socket structure
928  * @m: message to send
929  * @dlen: total length of message data
930  * @timeout: timeout to wait for wakeup
931  *
932  * Called from function tipc_sendmsg(), which has done all sanity checks
933  * Returns the number of bytes sent on success, or errno
934  */
935 static int tipc_send_group_unicast(struct socket *sock, struct msghdr *m,
936                                    int dlen, long timeout)
937 {
938         struct sock *sk = sock->sk;
939         DECLARE_SOCKADDR(struct sockaddr_tipc *, dest, m->msg_name);
940         int blks = tsk_blocks(GROUP_H_SIZE + dlen);
941         struct tipc_sock *tsk = tipc_sk(sk);
942         struct net *net = sock_net(sk);
943         struct tipc_member *mb = NULL;
944         u32 node, port;
945         int rc;
946
947         node = dest->addr.id.node;
948         port = dest->addr.id.ref;
949         if (!port && !node)
950                 return -EHOSTUNREACH;
951
952         /* Block or return if destination link or member is congested */
953         rc = tipc_wait_for_cond(sock, &timeout,
954                                 !tipc_dest_find(&tsk->cong_links, node, 0) &&
955                                 tsk->group &&
956                                 !tipc_group_cong(tsk->group, node, port, blks,
957                                                  &mb));
958         if (unlikely(rc))
959                 return rc;
960
961         if (unlikely(!mb))
962                 return -EHOSTUNREACH;
963
964         rc = tipc_send_group_msg(net, tsk, m, mb, node, port, dlen);
965
966         return rc ? rc : dlen;
967 }
968
969 /**
970  * tipc_send_group_anycast - send message to any member with given identity
971  * @sock: socket structure
972  * @m: message to send
973  * @dlen: total length of message data
974  * @timeout: timeout to wait for wakeup
975  *
976  * Called from function tipc_sendmsg(), which has done all sanity checks
977  * Returns the number of bytes sent on success, or errno
978  */
979 static int tipc_send_group_anycast(struct socket *sock, struct msghdr *m,
980                                    int dlen, long timeout)
981 {
982         DECLARE_SOCKADDR(struct sockaddr_tipc *, dest, m->msg_name);
983         struct sock *sk = sock->sk;
984         struct tipc_sock *tsk = tipc_sk(sk);
985         struct list_head *cong_links = &tsk->cong_links;
986         int blks = tsk_blocks(GROUP_H_SIZE + dlen);
987         struct tipc_msg *hdr = &tsk->phdr;
988         struct tipc_member *first = NULL;
989         struct tipc_member *mbr = NULL;
990         struct net *net = sock_net(sk);
991         u32 node, port, exclude;
992         struct list_head dsts;
993         u32 type, inst, scope;
994         int lookups = 0;
995         int dstcnt, rc;
996         bool cong;
997
998         INIT_LIST_HEAD(&dsts);
999
1000         type = msg_nametype(hdr);
1001         inst = dest->addr.name.name.instance;
1002         scope = msg_lookup_scope(hdr);
1003
1004         while (++lookups < 4) {
1005                 exclude = tipc_group_exclude(tsk->group);
1006
1007                 first = NULL;
1008
1009                 /* Look for a non-congested destination member, if any */
1010                 while (1) {
1011                         if (!tipc_nametbl_lookup(net, type, inst, scope, &dsts,
1012                                                  &dstcnt, exclude, false))
1013                                 return -EHOSTUNREACH;
1014                         tipc_dest_pop(&dsts, &node, &port);
1015                         cong = tipc_group_cong(tsk->group, node, port, blks,
1016                                                &mbr);
1017                         if (!cong)
1018                                 break;
1019                         if (mbr == first)
1020                                 break;
1021                         if (!first)
1022                                 first = mbr;
1023                 }
1024
1025                 /* Start over if destination was not in member list */
1026                 if (unlikely(!mbr))
1027                         continue;
1028
1029                 if (likely(!cong && !tipc_dest_find(cong_links, node, 0)))
1030                         break;
1031
1032                 /* Block or return if destination link or member is congested */
1033                 rc = tipc_wait_for_cond(sock, &timeout,
1034                                         !tipc_dest_find(cong_links, node, 0) &&
1035                                         tsk->group &&
1036                                         !tipc_group_cong(tsk->group, node, port,
1037                                                          blks, &mbr));
1038                 if (unlikely(rc))
1039                         return rc;
1040
1041                 /* Send, unless destination disappeared while waiting */
1042                 if (likely(mbr))
1043                         break;
1044         }
1045
1046         if (unlikely(lookups >= 4))
1047                 return -EHOSTUNREACH;
1048
1049         rc = tipc_send_group_msg(net, tsk, m, mbr, node, port, dlen);
1050
1051         return rc ? rc : dlen;
1052 }
1053
1054 /**
1055  * tipc_send_group_bcast - send message to all members in communication group
1056  * @sock: socket structure
1057  * @m: message to send
1058  * @dlen: total length of message data
1059  * @timeout: timeout to wait for wakeup
1060  *
1061  * Called from function tipc_sendmsg(), which has done all sanity checks
1062  * Returns the number of bytes sent on success, or errno
1063  */
1064 static int tipc_send_group_bcast(struct socket *sock, struct msghdr *m,
1065                                  int dlen, long timeout)
1066 {
1067         DECLARE_SOCKADDR(struct sockaddr_tipc *, dest, m->msg_name);
1068         struct sock *sk = sock->sk;
1069         struct net *net = sock_net(sk);
1070         struct tipc_sock *tsk = tipc_sk(sk);
1071         struct tipc_nlist *dsts;
1072         struct tipc_mc_method *method = &tsk->mc_method;
1073         bool ack = method->mandatory && method->rcast;
1074         int blks = tsk_blocks(MCAST_H_SIZE + dlen);
1075         struct tipc_msg *hdr = &tsk->phdr;
1076         int mtu = tipc_bcast_get_mtu(net);
1077         struct sk_buff_head pkts;
1078         int rc = -EHOSTUNREACH;
1079
1080         /* Block or return if any destination link or member is congested */
1081         rc = tipc_wait_for_cond(sock, &timeout,
1082                                 !tsk->cong_link_cnt && tsk->group &&
1083                                 !tipc_group_bc_cong(tsk->group, blks));
1084         if (unlikely(rc))
1085                 return rc;
1086
1087         dsts = tipc_group_dests(tsk->group);
1088         if (!dsts->local && !dsts->remote)
1089                 return -EHOSTUNREACH;
1090
1091         /* Complete message header */
1092         if (dest) {
1093                 msg_set_type(hdr, TIPC_GRP_MCAST_MSG);
1094                 msg_set_nameinst(hdr, dest->addr.name.name.instance);
1095         } else {
1096                 msg_set_type(hdr, TIPC_GRP_BCAST_MSG);
1097                 msg_set_nameinst(hdr, 0);
1098         }
1099         msg_set_hdr_sz(hdr, GROUP_H_SIZE);
1100         msg_set_destport(hdr, 0);
1101         msg_set_destnode(hdr, 0);
1102         msg_set_grp_bc_seqno(hdr, tipc_group_bc_snd_nxt(tsk->group));
1103
1104         /* Avoid getting stuck with repeated forced replicasts */
1105         msg_set_grp_bc_ack_req(hdr, ack);
1106
1107         /* Build message as chain of buffers */
1108         __skb_queue_head_init(&pkts);
1109         rc = tipc_msg_build(hdr, m, 0, dlen, mtu, &pkts);
1110         if (unlikely(rc != dlen))
1111                 return rc;
1112
1113         /* Send message */
1114         rc = tipc_mcast_xmit(net, &pkts, method, dsts, &tsk->cong_link_cnt);
1115         if (unlikely(rc))
1116                 return rc;
1117
1118         /* Update broadcast sequence number and send windows */
1119         tipc_group_update_bc_members(tsk->group, blks, ack);
1120
1121         /* Broadcast link is now free to choose method for next broadcast */
1122         method->mandatory = false;
1123         method->expires = jiffies;
1124
1125         return dlen;
1126 }
1127
1128 /**
1129  * tipc_send_group_mcast - send message to all members with given identity
1130  * @sock: socket structure
1131  * @m: message to send
1132  * @dlen: total length of message data
1133  * @timeout: timeout to wait for wakeup
1134  *
1135  * Called from function tipc_sendmsg(), which has done all sanity checks
1136  * Returns the number of bytes sent on success, or errno
1137  */
1138 static int tipc_send_group_mcast(struct socket *sock, struct msghdr *m,
1139                                  int dlen, long timeout)
1140 {
1141         struct sock *sk = sock->sk;
1142         DECLARE_SOCKADDR(struct sockaddr_tipc *, dest, m->msg_name);
1143         struct tipc_sock *tsk = tipc_sk(sk);
1144         struct tipc_group *grp = tsk->group;
1145         struct tipc_msg *hdr = &tsk->phdr;
1146         struct net *net = sock_net(sk);
1147         u32 type, inst, scope, exclude;
1148         struct list_head dsts;
1149         u32 dstcnt;
1150
1151         INIT_LIST_HEAD(&dsts);
1152
1153         type = msg_nametype(hdr);
1154         inst = dest->addr.name.name.instance;
1155         scope = msg_lookup_scope(hdr);
1156         exclude = tipc_group_exclude(grp);
1157
1158         if (!tipc_nametbl_lookup(net, type, inst, scope, &dsts,
1159                                  &dstcnt, exclude, true))
1160                 return -EHOSTUNREACH;
1161
1162         if (dstcnt == 1) {
1163                 tipc_dest_pop(&dsts, &dest->addr.id.node, &dest->addr.id.ref);
1164                 return tipc_send_group_unicast(sock, m, dlen, timeout);
1165         }
1166
1167         tipc_dest_list_purge(&dsts);
1168         return tipc_send_group_bcast(sock, m, dlen, timeout);
1169 }
1170
1171 /**
1172  * tipc_sk_mcast_rcv - Deliver multicast messages to all destination sockets
1173  * @arrvq: queue with arriving messages, to be cloned after destination lookup
1174  * @inputq: queue with cloned messages, delivered to socket after dest lookup
1175  *
1176  * Multi-threaded: parallel calls with reference to same queues may occur
1177  */
1178 void tipc_sk_mcast_rcv(struct net *net, struct sk_buff_head *arrvq,
1179                        struct sk_buff_head *inputq)
1180 {
1181         u32 self = tipc_own_addr(net);
1182         u32 type, lower, upper, scope;
1183         struct sk_buff *skb, *_skb;
1184         u32 portid, onode;
1185         struct sk_buff_head tmpq;
1186         struct list_head dports;
1187         struct tipc_msg *hdr;
1188         int user, mtyp, hlen;
1189         bool exact;
1190
1191         __skb_queue_head_init(&tmpq);
1192         INIT_LIST_HEAD(&dports);
1193
1194         skb = tipc_skb_peek(arrvq, &inputq->lock);
1195         for (; skb; skb = tipc_skb_peek(arrvq, &inputq->lock)) {
1196                 hdr = buf_msg(skb);
1197                 user = msg_user(hdr);
1198                 mtyp = msg_type(hdr);
1199                 hlen = skb_headroom(skb) + msg_hdr_sz(hdr);
1200                 onode = msg_orignode(hdr);
1201                 type = msg_nametype(hdr);
1202
1203                 if (mtyp == TIPC_GRP_UCAST_MSG || user == GROUP_PROTOCOL) {
1204                         spin_lock_bh(&inputq->lock);
1205                         if (skb_peek(arrvq) == skb) {
1206                                 __skb_dequeue(arrvq);
1207                                 __skb_queue_tail(inputq, skb);
1208                         }
1209                         kfree_skb(skb);
1210                         spin_unlock_bh(&inputq->lock);
1211                         continue;
1212                 }
1213
1214                 /* Group messages require exact scope match */
1215                 if (msg_in_group(hdr)) {
1216                         lower = 0;
1217                         upper = ~0;
1218                         scope = msg_lookup_scope(hdr);
1219                         exact = true;
1220                 } else {
1221                         /* TIPC_NODE_SCOPE means "any scope" in this context */
1222                         if (onode == self)
1223                                 scope = TIPC_NODE_SCOPE;
1224                         else
1225                                 scope = TIPC_CLUSTER_SCOPE;
1226                         exact = false;
1227                         lower = msg_namelower(hdr);
1228                         upper = msg_nameupper(hdr);
1229                 }
1230
1231                 /* Create destination port list: */
1232                 tipc_nametbl_mc_lookup(net, type, lower, upper,
1233                                        scope, exact, &dports);
1234
1235                 /* Clone message per destination */
1236                 while (tipc_dest_pop(&dports, NULL, &portid)) {
1237                         _skb = __pskb_copy(skb, hlen, GFP_ATOMIC);
1238                         if (_skb) {
1239                                 msg_set_destport(buf_msg(_skb), portid);
1240                                 __skb_queue_tail(&tmpq, _skb);
1241                                 continue;
1242                         }
1243                         pr_warn("Failed to clone mcast rcv buffer\n");
1244                 }
1245                 /* Append to inputq if not already done by other thread */
1246                 spin_lock_bh(&inputq->lock);
1247                 if (skb_peek(arrvq) == skb) {
1248                         skb_queue_splice_tail_init(&tmpq, inputq);
1249                         /* Decrease the skb's refcnt as increasing in the
1250                          * function tipc_skb_peek
1251                          */
1252                         kfree_skb(__skb_dequeue(arrvq));
1253                 }
1254                 spin_unlock_bh(&inputq->lock);
1255                 __skb_queue_purge(&tmpq);
1256                 kfree_skb(skb);
1257         }
1258         tipc_sk_rcv(net, inputq);
1259 }
1260
1261 /* tipc_sk_push_backlog(): send accumulated buffers in socket write queue
1262  *                         when socket is in Nagle mode
1263  */
1264 static void tipc_sk_push_backlog(struct tipc_sock *tsk, bool nagle_ack)
1265 {
1266         struct sk_buff_head *txq = &tsk->sk.sk_write_queue;
1267         struct sk_buff *skb = skb_peek_tail(txq);
1268         struct net *net = sock_net(&tsk->sk);
1269         u32 dnode = tsk_peer_node(tsk);
1270         int rc;
1271
1272         if (nagle_ack) {
1273                 tsk->pkt_cnt += skb_queue_len(txq);
1274                 if (!tsk->pkt_cnt || tsk->msg_acc / tsk->pkt_cnt < 2) {
1275                         tsk->oneway = 0;
1276                         if (tsk->nagle_start < NAGLE_START_MAX)
1277                                 tsk->nagle_start *= 2;
1278                         tsk->expect_ack = false;
1279                         pr_debug("tsk %10u: bad nagle %u -> %u, next start %u!\n",
1280                                  tsk->portid, tsk->msg_acc, tsk->pkt_cnt,
1281                                  tsk->nagle_start);
1282                 } else {
1283                         tsk->nagle_start = NAGLE_START_INIT;
1284                         if (skb) {
1285                                 msg_set_ack_required(buf_msg(skb));
1286                                 tsk->expect_ack = true;
1287                         } else {
1288                                 tsk->expect_ack = false;
1289                         }
1290                 }
1291                 tsk->msg_acc = 0;
1292                 tsk->pkt_cnt = 0;
1293         }
1294
1295         if (!skb || tsk->cong_link_cnt)
1296                 return;
1297
1298         /* Do not send SYN again after congestion */
1299         if (msg_is_syn(buf_msg(skb)))
1300                 return;
1301
1302         if (tsk->msg_acc)
1303                 tsk->pkt_cnt += skb_queue_len(txq);
1304         tsk->snt_unacked += tsk->snd_backlog;
1305         tsk->snd_backlog = 0;
1306         rc = tipc_node_xmit(net, txq, dnode, tsk->portid);
1307         if (rc == -ELINKCONG)
1308                 tsk->cong_link_cnt = 1;
1309 }
1310
1311 /**
1312  * tipc_sk_conn_proto_rcv - receive a connection mng protocol message
1313  * @tsk: receiving socket
1314  * @skb: pointer to message buffer.
1315  */
1316 static void tipc_sk_conn_proto_rcv(struct tipc_sock *tsk, struct sk_buff *skb,
1317                                    struct sk_buff_head *inputq,
1318                                    struct sk_buff_head *xmitq)
1319 {
1320         struct tipc_msg *hdr = buf_msg(skb);
1321         u32 onode = tsk_own_node(tsk);
1322         struct sock *sk = &tsk->sk;
1323         int mtyp = msg_type(hdr);
1324         bool was_cong;
1325
1326         /* Ignore if connection cannot be validated: */
1327         if (!tsk_peer_msg(tsk, hdr)) {
1328                 trace_tipc_sk_drop_msg(sk, skb, TIPC_DUMP_NONE, "@proto_rcv!");
1329                 goto exit;
1330         }
1331
1332         if (unlikely(msg_errcode(hdr))) {
1333                 tipc_set_sk_state(sk, TIPC_DISCONNECTING);
1334                 tipc_node_remove_conn(sock_net(sk), tsk_peer_node(tsk),
1335                                       tsk_peer_port(tsk));
1336                 sk->sk_state_change(sk);
1337
1338                 /* State change is ignored if socket already awake,
1339                  * - convert msg to abort msg and add to inqueue
1340                  */
1341                 msg_set_user(hdr, TIPC_CRITICAL_IMPORTANCE);
1342                 msg_set_type(hdr, TIPC_CONN_MSG);
1343                 msg_set_size(hdr, BASIC_H_SIZE);
1344                 msg_set_hdr_sz(hdr, BASIC_H_SIZE);
1345                 __skb_queue_tail(inputq, skb);
1346                 return;
1347         }
1348
1349         tsk->probe_unacked = false;
1350
1351         if (mtyp == CONN_PROBE) {
1352                 msg_set_type(hdr, CONN_PROBE_REPLY);
1353                 if (tipc_msg_reverse(onode, &skb, TIPC_OK))
1354                         __skb_queue_tail(xmitq, skb);
1355                 return;
1356         } else if (mtyp == CONN_ACK) {
1357                 was_cong = tsk_conn_cong(tsk);
1358                 tipc_sk_push_backlog(tsk, msg_nagle_ack(hdr));
1359                 tsk->snt_unacked -= msg_conn_ack(hdr);
1360                 if (tsk->peer_caps & TIPC_BLOCK_FLOWCTL)
1361                         tsk->snd_win = msg_adv_win(hdr);
1362                 if (was_cong && !tsk_conn_cong(tsk))
1363                         sk->sk_write_space(sk);
1364         } else if (mtyp != CONN_PROBE_REPLY) {
1365                 pr_warn("Received unknown CONN_PROTO msg\n");
1366         }
1367 exit:
1368         kfree_skb(skb);
1369 }
1370
1371 /**
1372  * tipc_sendmsg - send message in connectionless manner
1373  * @sock: socket structure
1374  * @m: message to send
1375  * @dsz: amount of user data to be sent
1376  *
1377  * Message must have an destination specified explicitly.
1378  * Used for SOCK_RDM and SOCK_DGRAM messages,
1379  * and for 'SYN' messages on SOCK_SEQPACKET and SOCK_STREAM connections.
1380  * (Note: 'SYN+' is prohibited on SOCK_STREAM.)
1381  *
1382  * Returns the number of bytes sent on success, or errno otherwise
1383  */
1384 static int tipc_sendmsg(struct socket *sock,
1385                         struct msghdr *m, size_t dsz)
1386 {
1387         struct sock *sk = sock->sk;
1388         int ret;
1389
1390         lock_sock(sk);
1391         ret = __tipc_sendmsg(sock, m, dsz);
1392         release_sock(sk);
1393
1394         return ret;
1395 }
1396
1397 static int __tipc_sendmsg(struct socket *sock, struct msghdr *m, size_t dlen)
1398 {
1399         struct sock *sk = sock->sk;
1400         struct net *net = sock_net(sk);
1401         struct tipc_sock *tsk = tipc_sk(sk);
1402         DECLARE_SOCKADDR(struct sockaddr_tipc *, dest, m->msg_name);
1403         long timeout = sock_sndtimeo(sk, m->msg_flags & MSG_DONTWAIT);
1404         struct list_head *clinks = &tsk->cong_links;
1405         bool syn = !tipc_sk_type_connectionless(sk);
1406         struct tipc_group *grp = tsk->group;
1407         struct tipc_msg *hdr = &tsk->phdr;
1408         struct tipc_name_seq *seq;
1409         struct sk_buff_head pkts;
1410         u32 dport = 0, dnode = 0;
1411         u32 type = 0, inst = 0;
1412         int mtu, rc;
1413
1414         if (unlikely(dlen > TIPC_MAX_USER_MSG_SIZE))
1415                 return -EMSGSIZE;
1416
1417         if (likely(dest)) {
1418                 if (unlikely(m->msg_namelen < sizeof(*dest)))
1419                         return -EINVAL;
1420                 if (unlikely(dest->family != AF_TIPC))
1421                         return -EINVAL;
1422         }
1423
1424         if (grp) {
1425                 if (!dest)
1426                         return tipc_send_group_bcast(sock, m, dlen, timeout);
1427                 if (dest->addrtype == TIPC_ADDR_NAME)
1428                         return tipc_send_group_anycast(sock, m, dlen, timeout);
1429                 if (dest->addrtype == TIPC_ADDR_ID)
1430                         return tipc_send_group_unicast(sock, m, dlen, timeout);
1431                 if (dest->addrtype == TIPC_ADDR_MCAST)
1432                         return tipc_send_group_mcast(sock, m, dlen, timeout);
1433                 return -EINVAL;
1434         }
1435
1436         if (unlikely(!dest)) {
1437                 dest = &tsk->peer;
1438                 if (!syn && dest->family != AF_TIPC)
1439                         return -EDESTADDRREQ;
1440         }
1441
1442         if (unlikely(syn)) {
1443                 if (sk->sk_state == TIPC_LISTEN)
1444                         return -EPIPE;
1445                 if (sk->sk_state != TIPC_OPEN)
1446                         return -EISCONN;
1447                 if (tsk->published)
1448                         return -EOPNOTSUPP;
1449                 if (dest->addrtype == TIPC_ADDR_NAME) {
1450                         tsk->conn_type = dest->addr.name.name.type;
1451                         tsk->conn_instance = dest->addr.name.name.instance;
1452                 }
1453                 msg_set_syn(hdr, 1);
1454         }
1455
1456         seq = &dest->addr.nameseq;
1457         if (dest->addrtype == TIPC_ADDR_MCAST)
1458                 return tipc_sendmcast(sock, seq, m, dlen, timeout);
1459
1460         if (dest->addrtype == TIPC_ADDR_NAME) {
1461                 type = dest->addr.name.name.type;
1462                 inst = dest->addr.name.name.instance;
1463                 dnode = dest->addr.name.domain;
1464                 dport = tipc_nametbl_translate(net, type, inst, &dnode);
1465                 if (unlikely(!dport && !dnode))
1466                         return -EHOSTUNREACH;
1467         } else if (dest->addrtype == TIPC_ADDR_ID) {
1468                 dnode = dest->addr.id.node;
1469         } else {
1470                 return -EINVAL;
1471         }
1472
1473         /* Block or return if destination link is congested */
1474         rc = tipc_wait_for_cond(sock, &timeout,
1475                                 !tipc_dest_find(clinks, dnode, 0));
1476         if (unlikely(rc))
1477                 return rc;
1478
1479         if (dest->addrtype == TIPC_ADDR_NAME) {
1480                 msg_set_type(hdr, TIPC_NAMED_MSG);
1481                 msg_set_hdr_sz(hdr, NAMED_H_SIZE);
1482                 msg_set_nametype(hdr, type);
1483                 msg_set_nameinst(hdr, inst);
1484                 msg_set_lookup_scope(hdr, tipc_node2scope(dnode));
1485                 msg_set_destnode(hdr, dnode);
1486                 msg_set_destport(hdr, dport);
1487         } else { /* TIPC_ADDR_ID */
1488                 msg_set_type(hdr, TIPC_DIRECT_MSG);
1489                 msg_set_lookup_scope(hdr, 0);
1490                 msg_set_destnode(hdr, dnode);
1491                 msg_set_destport(hdr, dest->addr.id.ref);
1492                 msg_set_hdr_sz(hdr, BASIC_H_SIZE);
1493         }
1494
1495         __skb_queue_head_init(&pkts);
1496         mtu = tipc_node_get_mtu(net, dnode, tsk->portid, true);
1497         rc = tipc_msg_build(hdr, m, 0, dlen, mtu, &pkts);
1498         if (unlikely(rc != dlen))
1499                 return rc;
1500         if (unlikely(syn && !tipc_msg_skb_clone(&pkts, &sk->sk_write_queue))) {
1501                 __skb_queue_purge(&pkts);
1502                 return -ENOMEM;
1503         }
1504
1505         trace_tipc_sk_sendmsg(sk, skb_peek(&pkts), TIPC_DUMP_SK_SNDQ, " ");
1506         rc = tipc_node_xmit(net, &pkts, dnode, tsk->portid);
1507         if (unlikely(rc == -ELINKCONG)) {
1508                 tipc_dest_push(clinks, dnode, 0);
1509                 tsk->cong_link_cnt++;
1510                 rc = 0;
1511         }
1512
1513         if (unlikely(syn && !rc)) {
1514                 tipc_set_sk_state(sk, TIPC_CONNECTING);
1515                 if (dlen && timeout) {
1516                         timeout = msecs_to_jiffies(timeout);
1517                         tipc_wait_for_connect(sock, &timeout);
1518                 }
1519         }
1520
1521         return rc ? rc : dlen;
1522 }
1523
1524 /**
1525  * tipc_sendstream - send stream-oriented data
1526  * @sock: socket structure
1527  * @m: data to send
1528  * @dsz: total length of data to be transmitted
1529  *
1530  * Used for SOCK_STREAM data.
1531  *
1532  * Returns the number of bytes sent on success (or partial success),
1533  * or errno if no data sent
1534  */
1535 static int tipc_sendstream(struct socket *sock, struct msghdr *m, size_t dsz)
1536 {
1537         struct sock *sk = sock->sk;
1538         int ret;
1539
1540         lock_sock(sk);
1541         ret = __tipc_sendstream(sock, m, dsz);
1542         release_sock(sk);
1543
1544         return ret;
1545 }
1546
1547 static int __tipc_sendstream(struct socket *sock, struct msghdr *m, size_t dlen)
1548 {
1549         struct sock *sk = sock->sk;
1550         DECLARE_SOCKADDR(struct sockaddr_tipc *, dest, m->msg_name);
1551         long timeout = sock_sndtimeo(sk, m->msg_flags & MSG_DONTWAIT);
1552         struct sk_buff_head *txq = &sk->sk_write_queue;
1553         struct tipc_sock *tsk = tipc_sk(sk);
1554         struct tipc_msg *hdr = &tsk->phdr;
1555         struct net *net = sock_net(sk);
1556         struct sk_buff *skb;
1557         u32 dnode = tsk_peer_node(tsk);
1558         int maxnagle = tsk->maxnagle;
1559         int maxpkt = tsk->max_pkt;
1560         int send, sent = 0;
1561         int blocks, rc = 0;
1562
1563         if (unlikely(dlen > INT_MAX))
1564                 return -EMSGSIZE;
1565
1566         /* Handle implicit connection setup */
1567         if (unlikely(dest && sk->sk_state == TIPC_OPEN)) {
1568                 rc = __tipc_sendmsg(sock, m, dlen);
1569                 if (dlen && dlen == rc) {
1570                         tsk->peer_caps = tipc_node_get_capabilities(net, dnode);
1571                         tsk->snt_unacked = tsk_inc(tsk, dlen + msg_hdr_sz(hdr));
1572                 }
1573                 return rc;
1574         }
1575
1576         do {
1577                 rc = tipc_wait_for_cond(sock, &timeout,
1578                                         (!tsk->cong_link_cnt &&
1579                                          !tsk_conn_cong(tsk) &&
1580                                          tipc_sk_connected(sk)));
1581                 if (unlikely(rc))
1582                         break;
1583                 send = min_t(size_t, dlen - sent, TIPC_MAX_USER_MSG_SIZE);
1584                 blocks = tsk->snd_backlog;
1585                 if (tsk->oneway++ >= tsk->nagle_start && maxnagle &&
1586                     send <= maxnagle) {
1587                         rc = tipc_msg_append(hdr, m, send, maxnagle, txq);
1588                         if (unlikely(rc < 0))
1589                                 break;
1590                         blocks += rc;
1591                         tsk->msg_acc++;
1592                         if (blocks <= 64 && tsk->expect_ack) {
1593                                 tsk->snd_backlog = blocks;
1594                                 sent += send;
1595                                 break;
1596                         } else if (blocks > 64) {
1597                                 tsk->pkt_cnt += skb_queue_len(txq);
1598                         } else {
1599                                 skb = skb_peek_tail(txq);
1600                                 if (skb) {
1601                                         msg_set_ack_required(buf_msg(skb));
1602                                         tsk->expect_ack = true;
1603                                 } else {
1604                                         tsk->expect_ack = false;
1605                                 }
1606                                 tsk->msg_acc = 0;
1607                                 tsk->pkt_cnt = 0;
1608                         }
1609                 } else {
1610                         rc = tipc_msg_build(hdr, m, sent, send, maxpkt, txq);
1611                         if (unlikely(rc != send))
1612                                 break;
1613                         blocks += tsk_inc(tsk, send + MIN_H_SIZE);
1614                 }
1615                 trace_tipc_sk_sendstream(sk, skb_peek(txq),
1616                                          TIPC_DUMP_SK_SNDQ, " ");
1617                 rc = tipc_node_xmit(net, txq, dnode, tsk->portid);
1618                 if (unlikely(rc == -ELINKCONG)) {
1619                         tsk->cong_link_cnt = 1;
1620                         rc = 0;
1621                 }
1622                 if (likely(!rc)) {
1623                         tsk->snt_unacked += blocks;
1624                         tsk->snd_backlog = 0;
1625                         sent += send;
1626                 }
1627         } while (sent < dlen && !rc);
1628
1629         return sent ? sent : rc;
1630 }
1631
1632 /**
1633  * tipc_send_packet - send a connection-oriented message
1634  * @sock: socket structure
1635  * @m: message to send
1636  * @dsz: length of data to be transmitted
1637  *
1638  * Used for SOCK_SEQPACKET messages.
1639  *
1640  * Returns the number of bytes sent on success, or errno otherwise
1641  */
1642 static int tipc_send_packet(struct socket *sock, struct msghdr *m, size_t dsz)
1643 {
1644         if (dsz > TIPC_MAX_USER_MSG_SIZE)
1645                 return -EMSGSIZE;
1646
1647         return tipc_sendstream(sock, m, dsz);
1648 }
1649
1650 /* tipc_sk_finish_conn - complete the setup of a connection
1651  */
1652 static void tipc_sk_finish_conn(struct tipc_sock *tsk, u32 peer_port,
1653                                 u32 peer_node)
1654 {
1655         struct sock *sk = &tsk->sk;
1656         struct net *net = sock_net(sk);
1657         struct tipc_msg *msg = &tsk->phdr;
1658
1659         msg_set_syn(msg, 0);
1660         msg_set_destnode(msg, peer_node);
1661         msg_set_destport(msg, peer_port);
1662         msg_set_type(msg, TIPC_CONN_MSG);
1663         msg_set_lookup_scope(msg, 0);
1664         msg_set_hdr_sz(msg, SHORT_H_SIZE);
1665
1666         sk_reset_timer(sk, &sk->sk_timer, jiffies + CONN_PROBING_INTV);
1667         tipc_set_sk_state(sk, TIPC_ESTABLISHED);
1668         tipc_node_add_conn(net, peer_node, tsk->portid, peer_port);
1669         tsk->max_pkt = tipc_node_get_mtu(net, peer_node, tsk->portid, true);
1670         tsk->peer_caps = tipc_node_get_capabilities(net, peer_node);
1671         tsk_set_nagle(tsk);
1672         __skb_queue_purge(&sk->sk_write_queue);
1673         if (tsk->peer_caps & TIPC_BLOCK_FLOWCTL)
1674                 return;
1675
1676         /* Fall back to message based flow control */
1677         tsk->rcv_win = FLOWCTL_MSG_WIN;
1678         tsk->snd_win = FLOWCTL_MSG_WIN;
1679 }
1680
1681 /**
1682  * tipc_sk_set_orig_addr - capture sender's address for received message
1683  * @m: descriptor for message info
1684  * @skb: received message
1685  *
1686  * Note: Address is not captured if not requested by receiver.
1687  */
1688 static void tipc_sk_set_orig_addr(struct msghdr *m, struct sk_buff *skb)
1689 {
1690         DECLARE_SOCKADDR(struct sockaddr_pair *, srcaddr, m->msg_name);
1691         struct tipc_msg *hdr = buf_msg(skb);
1692
1693         if (!srcaddr)
1694                 return;
1695
1696         srcaddr->sock.family = AF_TIPC;
1697         srcaddr->sock.addrtype = TIPC_ADDR_ID;
1698         srcaddr->sock.scope = 0;
1699         srcaddr->sock.addr.id.ref = msg_origport(hdr);
1700         srcaddr->sock.addr.id.node = msg_orignode(hdr);
1701         srcaddr->sock.addr.name.domain = 0;
1702         m->msg_namelen = sizeof(struct sockaddr_tipc);
1703
1704         if (!msg_in_group(hdr))
1705                 return;
1706
1707         /* Group message users may also want to know sending member's id */
1708         srcaddr->member.family = AF_TIPC;
1709         srcaddr->member.addrtype = TIPC_ADDR_NAME;
1710         srcaddr->member.scope = 0;
1711         srcaddr->member.addr.name.name.type = msg_nametype(hdr);
1712         srcaddr->member.addr.name.name.instance = TIPC_SKB_CB(skb)->orig_member;
1713         srcaddr->member.addr.name.domain = 0;
1714         m->msg_namelen = sizeof(*srcaddr);
1715 }
1716
1717 /**
1718  * tipc_sk_anc_data_recv - optionally capture ancillary data for received message
1719  * @m: descriptor for message info
1720  * @skb: received message buffer
1721  * @tsk: TIPC port associated with message
1722  *
1723  * Note: Ancillary data is not captured if not requested by receiver.
1724  *
1725  * Returns 0 if successful, otherwise errno
1726  */
1727 static int tipc_sk_anc_data_recv(struct msghdr *m, struct sk_buff *skb,
1728                                  struct tipc_sock *tsk)
1729 {
1730         struct tipc_msg *msg;
1731         u32 anc_data[3];
1732         u32 err;
1733         u32 dest_type;
1734         int has_name;
1735         int res;
1736
1737         if (likely(m->msg_controllen == 0))
1738                 return 0;
1739         msg = buf_msg(skb);
1740
1741         /* Optionally capture errored message object(s) */
1742         err = msg ? msg_errcode(msg) : 0;
1743         if (unlikely(err)) {
1744                 anc_data[0] = err;
1745                 anc_data[1] = msg_data_sz(msg);
1746                 res = put_cmsg(m, SOL_TIPC, TIPC_ERRINFO, 8, anc_data);
1747                 if (res)
1748                         return res;
1749                 if (anc_data[1]) {
1750                         if (skb_linearize(skb))
1751                                 return -ENOMEM;
1752                         msg = buf_msg(skb);
1753                         res = put_cmsg(m, SOL_TIPC, TIPC_RETDATA, anc_data[1],
1754                                        msg_data(msg));
1755                         if (res)
1756                                 return res;
1757                 }
1758         }
1759
1760         /* Optionally capture message destination object */
1761         dest_type = msg ? msg_type(msg) : TIPC_DIRECT_MSG;
1762         switch (dest_type) {
1763         case TIPC_NAMED_MSG:
1764                 has_name = 1;
1765                 anc_data[0] = msg_nametype(msg);
1766                 anc_data[1] = msg_namelower(msg);
1767                 anc_data[2] = msg_namelower(msg);
1768                 break;
1769         case TIPC_MCAST_MSG:
1770                 has_name = 1;
1771                 anc_data[0] = msg_nametype(msg);
1772                 anc_data[1] = msg_namelower(msg);
1773                 anc_data[2] = msg_nameupper(msg);
1774                 break;
1775         case TIPC_CONN_MSG:
1776                 has_name = (tsk->conn_type != 0);
1777                 anc_data[0] = tsk->conn_type;
1778                 anc_data[1] = tsk->conn_instance;
1779                 anc_data[2] = tsk->conn_instance;
1780                 break;
1781         default:
1782                 has_name = 0;
1783         }
1784         if (has_name) {
1785                 res = put_cmsg(m, SOL_TIPC, TIPC_DESTNAME, 12, anc_data);
1786                 if (res)
1787                         return res;
1788         }
1789
1790         return 0;
1791 }
1792
1793 static struct sk_buff *tipc_sk_build_ack(struct tipc_sock *tsk)
1794 {
1795         struct sock *sk = &tsk->sk;
1796         struct sk_buff *skb = NULL;
1797         struct tipc_msg *msg;
1798         u32 peer_port = tsk_peer_port(tsk);
1799         u32 dnode = tsk_peer_node(tsk);
1800
1801         if (!tipc_sk_connected(sk))
1802                 return NULL;
1803         skb = tipc_msg_create(CONN_MANAGER, CONN_ACK, INT_H_SIZE, 0,
1804                               dnode, tsk_own_node(tsk), peer_port,
1805                               tsk->portid, TIPC_OK);
1806         if (!skb)
1807                 return NULL;
1808         msg = buf_msg(skb);
1809         msg_set_conn_ack(msg, tsk->rcv_unacked);
1810         tsk->rcv_unacked = 0;
1811
1812         /* Adjust to and advertize the correct window limit */
1813         if (tsk->peer_caps & TIPC_BLOCK_FLOWCTL) {
1814                 tsk->rcv_win = tsk_adv_blocks(tsk->sk.sk_rcvbuf);
1815                 msg_set_adv_win(msg, tsk->rcv_win);
1816         }
1817         return skb;
1818 }
1819
1820 static void tipc_sk_send_ack(struct tipc_sock *tsk)
1821 {
1822         struct sk_buff *skb;
1823
1824         skb = tipc_sk_build_ack(tsk);
1825         if (!skb)
1826                 return;
1827
1828         tipc_node_xmit_skb(sock_net(&tsk->sk), skb, tsk_peer_node(tsk),
1829                            msg_link_selector(buf_msg(skb)));
1830 }
1831
1832 static int tipc_wait_for_rcvmsg(struct socket *sock, long *timeop)
1833 {
1834         struct sock *sk = sock->sk;
1835         DEFINE_WAIT_FUNC(wait, woken_wake_function);
1836         long timeo = *timeop;
1837         int err = sock_error(sk);
1838
1839         if (err)
1840                 return err;
1841
1842         for (;;) {
1843                 if (timeo && skb_queue_empty(&sk->sk_receive_queue)) {
1844                         if (sk->sk_shutdown & RCV_SHUTDOWN) {
1845                                 err = -ENOTCONN;
1846                                 break;
1847                         }
1848                         add_wait_queue(sk_sleep(sk), &wait);
1849                         release_sock(sk);
1850                         timeo = wait_woken(&wait, TASK_INTERRUPTIBLE, timeo);
1851                         sched_annotate_sleep();
1852                         lock_sock(sk);
1853                         remove_wait_queue(sk_sleep(sk), &wait);
1854                 }
1855                 err = 0;
1856                 if (!skb_queue_empty(&sk->sk_receive_queue))
1857                         break;
1858                 err = -EAGAIN;
1859                 if (!timeo)
1860                         break;
1861                 err = sock_intr_errno(timeo);
1862                 if (signal_pending(current))
1863                         break;
1864
1865                 err = sock_error(sk);
1866                 if (err)
1867                         break;
1868         }
1869         *timeop = timeo;
1870         return err;
1871 }
1872
1873 /**
1874  * tipc_recvmsg - receive packet-oriented message
1875  * @m: descriptor for message info
1876  * @buflen: length of user buffer area
1877  * @flags: receive flags
1878  *
1879  * Used for SOCK_DGRAM, SOCK_RDM, and SOCK_SEQPACKET messages.
1880  * If the complete message doesn't fit in user area, truncate it.
1881  *
1882  * Returns size of returned message data, errno otherwise
1883  */
1884 static int tipc_recvmsg(struct socket *sock, struct msghdr *m,
1885                         size_t buflen,  int flags)
1886 {
1887         struct sock *sk = sock->sk;
1888         bool connected = !tipc_sk_type_connectionless(sk);
1889         struct tipc_sock *tsk = tipc_sk(sk);
1890         int rc, err, hlen, dlen, copy;
1891         struct tipc_skb_cb *skb_cb;
1892         struct sk_buff_head xmitq;
1893         struct tipc_msg *hdr;
1894         struct sk_buff *skb;
1895         bool grp_evt;
1896         long timeout;
1897
1898         /* Catch invalid receive requests */
1899         if (unlikely(!buflen))
1900                 return -EINVAL;
1901
1902         lock_sock(sk);
1903         if (unlikely(connected && sk->sk_state == TIPC_OPEN)) {
1904                 rc = -ENOTCONN;
1905                 goto exit;
1906         }
1907         timeout = sock_rcvtimeo(sk, flags & MSG_DONTWAIT);
1908
1909         /* Step rcv queue to first msg with data or error; wait if necessary */
1910         do {
1911                 rc = tipc_wait_for_rcvmsg(sock, &timeout);
1912                 if (unlikely(rc))
1913                         goto exit;
1914                 skb = skb_peek(&sk->sk_receive_queue);
1915                 skb_cb = TIPC_SKB_CB(skb);
1916                 hdr = buf_msg(skb);
1917                 dlen = msg_data_sz(hdr);
1918                 hlen = msg_hdr_sz(hdr);
1919                 err = msg_errcode(hdr);
1920                 grp_evt = msg_is_grp_evt(hdr);
1921                 if (likely(dlen || err))
1922                         break;
1923                 tsk_advance_rx_queue(sk);
1924         } while (1);
1925
1926         /* Collect msg meta data, including error code and rejected data */
1927         tipc_sk_set_orig_addr(m, skb);
1928         rc = tipc_sk_anc_data_recv(m, skb, tsk);
1929         if (unlikely(rc))
1930                 goto exit;
1931         hdr = buf_msg(skb);
1932
1933         /* Capture data if non-error msg, otherwise just set return value */
1934         if (likely(!err)) {
1935                 int offset = skb_cb->bytes_read;
1936
1937                 copy = min_t(int, dlen - offset, buflen);
1938                 rc = skb_copy_datagram_msg(skb, hlen + offset, m, copy);
1939                 if (unlikely(rc))
1940                         goto exit;
1941                 if (unlikely(offset + copy < dlen)) {
1942                         if (flags & MSG_EOR) {
1943                                 if (!(flags & MSG_PEEK))
1944                                         skb_cb->bytes_read = offset + copy;
1945                         } else {
1946                                 m->msg_flags |= MSG_TRUNC;
1947                                 skb_cb->bytes_read = 0;
1948                         }
1949                 } else {
1950                         if (flags & MSG_EOR)
1951                                 m->msg_flags |= MSG_EOR;
1952                         skb_cb->bytes_read = 0;
1953                 }
1954         } else {
1955                 copy = 0;
1956                 rc = 0;
1957                 if (err != TIPC_CONN_SHUTDOWN && connected && !m->msg_control) {
1958                         rc = -ECONNRESET;
1959                         goto exit;
1960                 }
1961         }
1962
1963         /* Mark message as group event if applicable */
1964         if (unlikely(grp_evt)) {
1965                 if (msg_grp_evt(hdr) == TIPC_WITHDRAWN)
1966                         m->msg_flags |= MSG_EOR;
1967                 m->msg_flags |= MSG_OOB;
1968                 copy = 0;
1969         }
1970
1971         /* Caption of data or error code/rejected data was successful */
1972         if (unlikely(flags & MSG_PEEK))
1973                 goto exit;
1974
1975         /* Send group flow control advertisement when applicable */
1976         if (tsk->group && msg_in_group(hdr) && !grp_evt) {
1977                 __skb_queue_head_init(&xmitq);
1978                 tipc_group_update_rcv_win(tsk->group, tsk_blocks(hlen + dlen),
1979                                           msg_orignode(hdr), msg_origport(hdr),
1980                                           &xmitq);
1981                 tipc_node_distr_xmit(sock_net(sk), &xmitq);
1982         }
1983
1984         if (skb_cb->bytes_read)
1985                 goto exit;
1986
1987         tsk_advance_rx_queue(sk);
1988
1989         if (likely(!connected))
1990                 goto exit;
1991
1992         /* Send connection flow control advertisement when applicable */
1993         tsk->rcv_unacked += tsk_inc(tsk, hlen + dlen);
1994         if (tsk->rcv_unacked >= tsk->rcv_win / TIPC_ACK_RATE)
1995                 tipc_sk_send_ack(tsk);
1996 exit:
1997         release_sock(sk);
1998         return rc ? rc : copy;
1999 }
2000
2001 /**
2002  * tipc_recvstream - receive stream-oriented data
2003  * @m: descriptor for message info
2004  * @buflen: total size of user buffer area
2005  * @flags: receive flags
2006  *
2007  * Used for SOCK_STREAM messages only.  If not enough data is available
2008  * will optionally wait for more; never truncates data.
2009  *
2010  * Returns size of returned message data, errno otherwise
2011  */
2012 static int tipc_recvstream(struct socket *sock, struct msghdr *m,
2013                            size_t buflen, int flags)
2014 {
2015         struct sock *sk = sock->sk;
2016         struct tipc_sock *tsk = tipc_sk(sk);
2017         struct sk_buff *skb;
2018         struct tipc_msg *hdr;
2019         struct tipc_skb_cb *skb_cb;
2020         bool peek = flags & MSG_PEEK;
2021         int offset, required, copy, copied = 0;
2022         int hlen, dlen, err, rc;
2023         long timeout;
2024
2025         /* Catch invalid receive attempts */
2026         if (unlikely(!buflen))
2027                 return -EINVAL;
2028
2029         lock_sock(sk);
2030
2031         if (unlikely(sk->sk_state == TIPC_OPEN)) {
2032                 rc = -ENOTCONN;
2033                 goto exit;
2034         }
2035         required = sock_rcvlowat(sk, flags & MSG_WAITALL, buflen);
2036         timeout = sock_rcvtimeo(sk, flags & MSG_DONTWAIT);
2037
2038         do {
2039                 /* Look at first msg in receive queue; wait if necessary */
2040                 rc = tipc_wait_for_rcvmsg(sock, &timeout);
2041                 if (unlikely(rc))
2042                         break;
2043                 skb = skb_peek(&sk->sk_receive_queue);
2044                 skb_cb = TIPC_SKB_CB(skb);
2045                 hdr = buf_msg(skb);
2046                 dlen = msg_data_sz(hdr);
2047                 hlen = msg_hdr_sz(hdr);
2048                 err = msg_errcode(hdr);
2049
2050                 /* Discard any empty non-errored (SYN-) message */
2051                 if (unlikely(!dlen && !err)) {
2052                         tsk_advance_rx_queue(sk);
2053                         continue;
2054                 }
2055
2056                 /* Collect msg meta data, incl. error code and rejected data */
2057                 if (!copied) {
2058                         tipc_sk_set_orig_addr(m, skb);
2059                         rc = tipc_sk_anc_data_recv(m, skb, tsk);
2060                         if (rc)
2061                                 break;
2062                         hdr = buf_msg(skb);
2063                 }
2064
2065                 /* Copy data if msg ok, otherwise return error/partial data */
2066                 if (likely(!err)) {
2067                         offset = skb_cb->bytes_read;
2068                         copy = min_t(int, dlen - offset, buflen - copied);
2069                         rc = skb_copy_datagram_msg(skb, hlen + offset, m, copy);
2070                         if (unlikely(rc))
2071                                 break;
2072                         copied += copy;
2073                         offset += copy;
2074                         if (unlikely(offset < dlen)) {
2075                                 if (!peek)
2076                                         skb_cb->bytes_read = offset;
2077                                 break;
2078                         }
2079                 } else {
2080                         rc = 0;
2081                         if ((err != TIPC_CONN_SHUTDOWN) && !m->msg_control)
2082                                 rc = -ECONNRESET;
2083                         if (copied || rc)
2084                                 break;
2085                 }
2086
2087                 if (unlikely(peek))
2088                         break;
2089
2090                 tsk_advance_rx_queue(sk);
2091
2092                 /* Send connection flow control advertisement when applicable */
2093                 tsk->rcv_unacked += tsk_inc(tsk, hlen + dlen);
2094                 if (tsk->rcv_unacked >= tsk->rcv_win / TIPC_ACK_RATE)
2095                         tipc_sk_send_ack(tsk);
2096
2097                 /* Exit if all requested data or FIN/error received */
2098                 if (copied == buflen || err)
2099                         break;
2100
2101         } while (!skb_queue_empty(&sk->sk_receive_queue) || copied < required);
2102 exit:
2103         release_sock(sk);
2104         return copied ? copied : rc;
2105 }
2106
2107 /**
2108  * tipc_write_space - wake up thread if port congestion is released
2109  * @sk: socket
2110  */
2111 static void tipc_write_space(struct sock *sk)
2112 {
2113         struct socket_wq *wq;
2114
2115         rcu_read_lock();
2116         wq = rcu_dereference(sk->sk_wq);
2117         if (skwq_has_sleeper(wq))
2118                 wake_up_interruptible_sync_poll(&wq->wait, EPOLLOUT |
2119                                                 EPOLLWRNORM | EPOLLWRBAND);
2120         rcu_read_unlock();
2121 }
2122
2123 /**
2124  * tipc_data_ready - wake up threads to indicate messages have been received
2125  * @sk: socket
2126  */
2127 static void tipc_data_ready(struct sock *sk)
2128 {
2129         struct socket_wq *wq;
2130
2131         rcu_read_lock();
2132         wq = rcu_dereference(sk->sk_wq);
2133         if (skwq_has_sleeper(wq))
2134                 wake_up_interruptible_sync_poll(&wq->wait, EPOLLIN |
2135                                                 EPOLLRDNORM | EPOLLRDBAND);
2136         rcu_read_unlock();
2137 }
2138
2139 static void tipc_sock_destruct(struct sock *sk)
2140 {
2141         __skb_queue_purge(&sk->sk_receive_queue);
2142 }
2143
2144 static void tipc_sk_proto_rcv(struct sock *sk,
2145                               struct sk_buff_head *inputq,
2146                               struct sk_buff_head *xmitq)
2147 {
2148         struct sk_buff *skb = __skb_dequeue(inputq);
2149         struct tipc_sock *tsk = tipc_sk(sk);
2150         struct tipc_msg *hdr = buf_msg(skb);
2151         struct tipc_group *grp = tsk->group;
2152         bool wakeup = false;
2153
2154         switch (msg_user(hdr)) {
2155         case CONN_MANAGER:
2156                 tipc_sk_conn_proto_rcv(tsk, skb, inputq, xmitq);
2157                 return;
2158         case SOCK_WAKEUP:
2159                 tipc_dest_del(&tsk->cong_links, msg_orignode(hdr), 0);
2160                 /* coupled with smp_rmb() in tipc_wait_for_cond() */
2161                 smp_wmb();
2162                 tsk->cong_link_cnt--;
2163                 wakeup = true;
2164                 tipc_sk_push_backlog(tsk, false);
2165                 break;
2166         case GROUP_PROTOCOL:
2167                 tipc_group_proto_rcv(grp, &wakeup, hdr, inputq, xmitq);
2168                 break;
2169         case TOP_SRV:
2170                 tipc_group_member_evt(tsk->group, &wakeup, &sk->sk_rcvbuf,
2171                                       hdr, inputq, xmitq);
2172                 break;
2173         default:
2174                 break;
2175         }
2176
2177         if (wakeup)
2178                 sk->sk_write_space(sk);
2179
2180         kfree_skb(skb);
2181 }
2182
2183 /**
2184  * tipc_sk_filter_connect - check incoming message for a connection-based socket
2185  * @tsk: TIPC socket
2186  * @skb: pointer to message buffer.
2187  * @xmitq: for Nagle ACK if any
2188  * Returns true if message should be added to receive queue, false otherwise
2189  */
2190 static bool tipc_sk_filter_connect(struct tipc_sock *tsk, struct sk_buff *skb,
2191                                    struct sk_buff_head *xmitq)
2192 {
2193         struct sock *sk = &tsk->sk;
2194         struct net *net = sock_net(sk);
2195         struct tipc_msg *hdr = buf_msg(skb);
2196         bool con_msg = msg_connected(hdr);
2197         u32 pport = tsk_peer_port(tsk);
2198         u32 pnode = tsk_peer_node(tsk);
2199         u32 oport = msg_origport(hdr);
2200         u32 onode = msg_orignode(hdr);
2201         int err = msg_errcode(hdr);
2202         unsigned long delay;
2203
2204         if (unlikely(msg_mcast(hdr)))
2205                 return false;
2206         tsk->oneway = 0;
2207
2208         switch (sk->sk_state) {
2209         case TIPC_CONNECTING:
2210                 /* Setup ACK */
2211                 if (likely(con_msg)) {
2212                         if (err)
2213                                 break;
2214                         tipc_sk_finish_conn(tsk, oport, onode);
2215                         msg_set_importance(&tsk->phdr, msg_importance(hdr));
2216                         /* ACK+ message with data is added to receive queue */
2217                         if (msg_data_sz(hdr))
2218                                 return true;
2219                         /* Empty ACK-, - wake up sleeping connect() and drop */
2220                         sk->sk_state_change(sk);
2221                         msg_set_dest_droppable(hdr, 1);
2222                         return false;
2223                 }
2224                 /* Ignore connectionless message if not from listening socket */
2225                 if (oport != pport || onode != pnode)
2226                         return false;
2227
2228                 /* Rejected SYN */
2229                 if (err != TIPC_ERR_OVERLOAD)
2230                         break;
2231
2232                 /* Prepare for new setup attempt if we have a SYN clone */
2233                 if (skb_queue_empty(&sk->sk_write_queue))
2234                         break;
2235                 get_random_bytes(&delay, 2);
2236                 delay %= (tsk->conn_timeout / 4);
2237                 delay = msecs_to_jiffies(delay + 100);
2238                 sk_reset_timer(sk, &sk->sk_timer, jiffies + delay);
2239                 return false;
2240         case TIPC_OPEN:
2241         case TIPC_DISCONNECTING:
2242                 return false;
2243         case TIPC_LISTEN:
2244                 /* Accept only SYN message */
2245                 if (!msg_is_syn(hdr) &&
2246                     tipc_node_get_capabilities(net, onode) & TIPC_SYN_BIT)
2247                         return false;
2248                 if (!con_msg && !err)
2249                         return true;
2250                 return false;
2251         case TIPC_ESTABLISHED:
2252                 if (!skb_queue_empty(&sk->sk_write_queue))
2253                         tipc_sk_push_backlog(tsk, false);
2254                 /* Accept only connection-based messages sent by peer */
2255                 if (likely(con_msg && !err && pport == oport &&
2256                            pnode == onode)) {
2257                         if (msg_ack_required(hdr)) {
2258                                 struct sk_buff *skb;
2259
2260                                 skb = tipc_sk_build_ack(tsk);
2261                                 if (skb) {
2262                                         msg_set_nagle_ack(buf_msg(skb));
2263                                         __skb_queue_tail(xmitq, skb);
2264                                 }
2265                         }
2266                         return true;
2267                 }
2268                 if (!tsk_peer_msg(tsk, hdr))
2269                         return false;
2270                 if (!err)
2271                         return true;
2272                 tipc_set_sk_state(sk, TIPC_DISCONNECTING);
2273                 tipc_node_remove_conn(net, pnode, tsk->portid);
2274                 sk->sk_state_change(sk);
2275                 return true;
2276         default:
2277                 pr_err("Unknown sk_state %u\n", sk->sk_state);
2278         }
2279         /* Abort connection setup attempt */
2280         tipc_set_sk_state(sk, TIPC_DISCONNECTING);
2281         sk->sk_err = ECONNREFUSED;
2282         sk->sk_state_change(sk);
2283         return true;
2284 }
2285
2286 /**
2287  * rcvbuf_limit - get proper overload limit of socket receive queue
2288  * @sk: socket
2289  * @skb: message
2290  *
2291  * For connection oriented messages, irrespective of importance,
2292  * default queue limit is 2 MB.
2293  *
2294  * For connectionless messages, queue limits are based on message
2295  * importance as follows:
2296  *
2297  * TIPC_LOW_IMPORTANCE       (2 MB)
2298  * TIPC_MEDIUM_IMPORTANCE    (4 MB)
2299  * TIPC_HIGH_IMPORTANCE      (8 MB)
2300  * TIPC_CRITICAL_IMPORTANCE  (16 MB)
2301  *
2302  * Returns overload limit according to corresponding message importance
2303  */
2304 static unsigned int rcvbuf_limit(struct sock *sk, struct sk_buff *skb)
2305 {
2306         struct tipc_sock *tsk = tipc_sk(sk);
2307         struct tipc_msg *hdr = buf_msg(skb);
2308
2309         if (unlikely(msg_in_group(hdr)))
2310                 return READ_ONCE(sk->sk_rcvbuf);
2311
2312         if (unlikely(!msg_connected(hdr)))
2313                 return READ_ONCE(sk->sk_rcvbuf) << msg_importance(hdr);
2314
2315         if (likely(tsk->peer_caps & TIPC_BLOCK_FLOWCTL))
2316                 return READ_ONCE(sk->sk_rcvbuf);
2317
2318         return FLOWCTL_MSG_LIM;
2319 }
2320
2321 /**
2322  * tipc_sk_filter_rcv - validate incoming message
2323  * @sk: socket
2324  * @skb: pointer to message.
2325  *
2326  * Enqueues message on receive queue if acceptable; optionally handles
2327  * disconnect indication for a connected socket.
2328  *
2329  * Called with socket lock already taken
2330  *
2331  */
2332 static void tipc_sk_filter_rcv(struct sock *sk, struct sk_buff *skb,
2333                                struct sk_buff_head *xmitq)
2334 {
2335         bool sk_conn = !tipc_sk_type_connectionless(sk);
2336         struct tipc_sock *tsk = tipc_sk(sk);
2337         struct tipc_group *grp = tsk->group;
2338         struct tipc_msg *hdr = buf_msg(skb);
2339         struct net *net = sock_net(sk);
2340         struct sk_buff_head inputq;
2341         int mtyp = msg_type(hdr);
2342         int limit, err = TIPC_OK;
2343
2344         trace_tipc_sk_filter_rcv(sk, skb, TIPC_DUMP_ALL, " ");
2345         TIPC_SKB_CB(skb)->bytes_read = 0;
2346         __skb_queue_head_init(&inputq);
2347         __skb_queue_tail(&inputq, skb);
2348
2349         if (unlikely(!msg_isdata(hdr)))
2350                 tipc_sk_proto_rcv(sk, &inputq, xmitq);
2351
2352         if (unlikely(grp))
2353                 tipc_group_filter_msg(grp, &inputq, xmitq);
2354
2355         if (unlikely(!grp) && mtyp == TIPC_MCAST_MSG)
2356                 tipc_mcast_filter_msg(net, &tsk->mc_method.deferredq, &inputq);
2357
2358         /* Validate and add to receive buffer if there is space */
2359         while ((skb = __skb_dequeue(&inputq))) {
2360                 hdr = buf_msg(skb);
2361                 limit = rcvbuf_limit(sk, skb);
2362                 if ((sk_conn && !tipc_sk_filter_connect(tsk, skb, xmitq)) ||
2363                     (!sk_conn && msg_connected(hdr)) ||
2364                     (!grp && msg_in_group(hdr)))
2365                         err = TIPC_ERR_NO_PORT;
2366                 else if (sk_rmem_alloc_get(sk) + skb->truesize >= limit) {
2367                         trace_tipc_sk_dump(sk, skb, TIPC_DUMP_ALL,
2368                                            "err_overload2!");
2369                         atomic_inc(&sk->sk_drops);
2370                         err = TIPC_ERR_OVERLOAD;
2371                 }
2372
2373                 if (unlikely(err)) {
2374                         if (tipc_msg_reverse(tipc_own_addr(net), &skb, err)) {
2375                                 trace_tipc_sk_rej_msg(sk, skb, TIPC_DUMP_NONE,
2376                                                       "@filter_rcv!");
2377                                 __skb_queue_tail(xmitq, skb);
2378                         }
2379                         err = TIPC_OK;
2380                         continue;
2381                 }
2382                 __skb_queue_tail(&sk->sk_receive_queue, skb);
2383                 skb_set_owner_r(skb, sk);
2384                 trace_tipc_sk_overlimit2(sk, skb, TIPC_DUMP_ALL,
2385                                          "rcvq >90% allocated!");
2386                 sk->sk_data_ready(sk);
2387         }
2388 }
2389
2390 /**
2391  * tipc_sk_backlog_rcv - handle incoming message from backlog queue
2392  * @sk: socket
2393  * @skb: message
2394  *
2395  * Caller must hold socket lock
2396  */
2397 static int tipc_sk_backlog_rcv(struct sock *sk, struct sk_buff *skb)
2398 {
2399         unsigned int before = sk_rmem_alloc_get(sk);
2400         struct sk_buff_head xmitq;
2401         unsigned int added;
2402
2403         __skb_queue_head_init(&xmitq);
2404
2405         tipc_sk_filter_rcv(sk, skb, &xmitq);
2406         added = sk_rmem_alloc_get(sk) - before;
2407         atomic_add(added, &tipc_sk(sk)->dupl_rcvcnt);
2408
2409         /* Send pending response/rejected messages, if any */
2410         tipc_node_distr_xmit(sock_net(sk), &xmitq);
2411         return 0;
2412 }
2413
2414 /**
2415  * tipc_sk_enqueue - extract all buffers with destination 'dport' from
2416  *                   inputq and try adding them to socket or backlog queue
2417  * @inputq: list of incoming buffers with potentially different destinations
2418  * @sk: socket where the buffers should be enqueued
2419  * @dport: port number for the socket
2420  *
2421  * Caller must hold socket lock
2422  */
2423 static void tipc_sk_enqueue(struct sk_buff_head *inputq, struct sock *sk,
2424                             u32 dport, struct sk_buff_head *xmitq)
2425 {
2426         unsigned long time_limit = jiffies + usecs_to_jiffies(20000);
2427         struct sk_buff *skb;
2428         unsigned int lim;
2429         atomic_t *dcnt;
2430         u32 onode;
2431
2432         while (skb_queue_len(inputq)) {
2433                 if (unlikely(time_after_eq(jiffies, time_limit)))
2434                         return;
2435
2436                 skb = tipc_skb_dequeue(inputq, dport);
2437                 if (unlikely(!skb))
2438                         return;
2439
2440                 /* Add message directly to receive queue if possible */
2441                 if (!sock_owned_by_user(sk)) {
2442                         tipc_sk_filter_rcv(sk, skb, xmitq);
2443                         continue;
2444                 }
2445
2446                 /* Try backlog, compensating for double-counted bytes */
2447                 dcnt = &tipc_sk(sk)->dupl_rcvcnt;
2448                 if (!sk->sk_backlog.len)
2449                         atomic_set(dcnt, 0);
2450                 lim = rcvbuf_limit(sk, skb) + atomic_read(dcnt);
2451                 if (likely(!sk_add_backlog(sk, skb, lim))) {
2452                         trace_tipc_sk_overlimit1(sk, skb, TIPC_DUMP_ALL,
2453                                                  "bklg & rcvq >90% allocated!");
2454                         continue;
2455                 }
2456
2457                 trace_tipc_sk_dump(sk, skb, TIPC_DUMP_ALL, "err_overload!");
2458                 /* Overload => reject message back to sender */
2459                 onode = tipc_own_addr(sock_net(sk));
2460                 atomic_inc(&sk->sk_drops);
2461                 if (tipc_msg_reverse(onode, &skb, TIPC_ERR_OVERLOAD)) {
2462                         trace_tipc_sk_rej_msg(sk, skb, TIPC_DUMP_ALL,
2463                                               "@sk_enqueue!");
2464                         __skb_queue_tail(xmitq, skb);
2465                 }
2466                 break;
2467         }
2468 }
2469
2470 /**
2471  * tipc_sk_rcv - handle a chain of incoming buffers
2472  * @inputq: buffer list containing the buffers
2473  * Consumes all buffers in list until inputq is empty
2474  * Note: may be called in multiple threads referring to the same queue
2475  */
2476 void tipc_sk_rcv(struct net *net, struct sk_buff_head *inputq)
2477 {
2478         struct sk_buff_head xmitq;
2479         u32 dnode, dport = 0;
2480         int err;
2481         struct tipc_sock *tsk;
2482         struct sock *sk;
2483         struct sk_buff *skb;
2484
2485         __skb_queue_head_init(&xmitq);
2486         while (skb_queue_len(inputq)) {
2487                 dport = tipc_skb_peek_port(inputq, dport);
2488                 tsk = tipc_sk_lookup(net, dport);
2489
2490                 if (likely(tsk)) {
2491                         sk = &tsk->sk;
2492                         if (likely(spin_trylock_bh(&sk->sk_lock.slock))) {
2493                                 tipc_sk_enqueue(inputq, sk, dport, &xmitq);
2494                                 spin_unlock_bh(&sk->sk_lock.slock);
2495                         }
2496                         /* Send pending response/rejected messages, if any */
2497                         tipc_node_distr_xmit(sock_net(sk), &xmitq);
2498                         sock_put(sk);
2499                         continue;
2500                 }
2501                 /* No destination socket => dequeue skb if still there */
2502                 skb = tipc_skb_dequeue(inputq, dport);
2503                 if (!skb)
2504                         return;
2505
2506                 /* Try secondary lookup if unresolved named message */
2507                 err = TIPC_ERR_NO_PORT;
2508                 if (tipc_msg_lookup_dest(net, skb, &err))
2509                         goto xmit;
2510
2511                 /* Prepare for message rejection */
2512                 if (!tipc_msg_reverse(tipc_own_addr(net), &skb, err))
2513                         continue;
2514
2515                 trace_tipc_sk_rej_msg(NULL, skb, TIPC_DUMP_NONE, "@sk_rcv!");
2516 xmit:
2517                 dnode = msg_destnode(buf_msg(skb));
2518                 tipc_node_xmit_skb(net, skb, dnode, dport);
2519         }
2520 }
2521
2522 static int tipc_wait_for_connect(struct socket *sock, long *timeo_p)
2523 {
2524         DEFINE_WAIT_FUNC(wait, woken_wake_function);
2525         struct sock *sk = sock->sk;
2526         int done;
2527
2528         do {
2529                 int err = sock_error(sk);
2530                 if (err)
2531                         return err;
2532                 if (!*timeo_p)
2533                         return -ETIMEDOUT;
2534                 if (signal_pending(current))
2535                         return sock_intr_errno(*timeo_p);
2536                 if (sk->sk_state == TIPC_DISCONNECTING)
2537                         break;
2538
2539                 add_wait_queue(sk_sleep(sk), &wait);
2540                 done = sk_wait_event(sk, timeo_p, tipc_sk_connected(sk),
2541                                      &wait);
2542                 remove_wait_queue(sk_sleep(sk), &wait);
2543         } while (!done);
2544         return 0;
2545 }
2546
2547 static bool tipc_sockaddr_is_sane(struct sockaddr_tipc *addr)
2548 {
2549         if (addr->family != AF_TIPC)
2550                 return false;
2551         if (addr->addrtype == TIPC_SERVICE_RANGE)
2552                 return (addr->addr.nameseq.lower <= addr->addr.nameseq.upper);
2553         return (addr->addrtype == TIPC_SERVICE_ADDR ||
2554                 addr->addrtype == TIPC_SOCKET_ADDR);
2555 }
2556
2557 /**
2558  * tipc_connect - establish a connection to another TIPC port
2559  * @sock: socket structure
2560  * @dest: socket address for destination port
2561  * @destlen: size of socket address data structure
2562  * @flags: file-related flags associated with socket
2563  *
2564  * Returns 0 on success, errno otherwise
2565  */
2566 static int tipc_connect(struct socket *sock, struct sockaddr *dest,
2567                         int destlen, int flags)
2568 {
2569         struct sock *sk = sock->sk;
2570         struct tipc_sock *tsk = tipc_sk(sk);
2571         struct sockaddr_tipc *dst = (struct sockaddr_tipc *)dest;
2572         struct msghdr m = {NULL,};
2573         long timeout = (flags & O_NONBLOCK) ? 0 : tsk->conn_timeout;
2574         int previous;
2575         int res = 0;
2576
2577         if (destlen != sizeof(struct sockaddr_tipc))
2578                 return -EINVAL;
2579
2580         lock_sock(sk);
2581
2582         if (tsk->group) {
2583                 res = -EINVAL;
2584                 goto exit;
2585         }
2586
2587         if (dst->family == AF_UNSPEC) {
2588                 memset(&tsk->peer, 0, sizeof(struct sockaddr_tipc));
2589                 if (!tipc_sk_type_connectionless(sk))
2590                         res = -EINVAL;
2591                 goto exit;
2592         }
2593         if (!tipc_sockaddr_is_sane(dst)) {
2594                 res = -EINVAL;
2595                 goto exit;
2596         }
2597         /* DGRAM/RDM connect(), just save the destaddr */
2598         if (tipc_sk_type_connectionless(sk)) {
2599                 memcpy(&tsk->peer, dest, destlen);
2600                 goto exit;
2601         } else if (dst->addrtype == TIPC_SERVICE_RANGE) {
2602                 res = -EINVAL;
2603                 goto exit;
2604         }
2605
2606         previous = sk->sk_state;
2607
2608         switch (sk->sk_state) {
2609         case TIPC_OPEN:
2610                 /* Send a 'SYN-' to destination */
2611                 m.msg_name = dest;
2612                 m.msg_namelen = destlen;
2613
2614                 /* If connect is in non-blocking case, set MSG_DONTWAIT to
2615                  * indicate send_msg() is never blocked.
2616                  */
2617                 if (!timeout)
2618                         m.msg_flags = MSG_DONTWAIT;
2619
2620                 res = __tipc_sendmsg(sock, &m, 0);
2621                 if ((res < 0) && (res != -EWOULDBLOCK))
2622                         goto exit;
2623
2624                 /* Just entered TIPC_CONNECTING state; the only
2625                  * difference is that return value in non-blocking
2626                  * case is EINPROGRESS, rather than EALREADY.
2627                  */
2628                 res = -EINPROGRESS;
2629                 fallthrough;
2630         case TIPC_CONNECTING:
2631                 if (!timeout) {
2632                         if (previous == TIPC_CONNECTING)
2633                                 res = -EALREADY;
2634                         goto exit;
2635                 }
2636                 timeout = msecs_to_jiffies(timeout);
2637                 /* Wait until an 'ACK' or 'RST' arrives, or a timeout occurs */
2638                 res = tipc_wait_for_connect(sock, &timeout);
2639                 break;
2640         case TIPC_ESTABLISHED:
2641                 res = -EISCONN;
2642                 break;
2643         default:
2644                 res = -EINVAL;
2645         }
2646
2647 exit:
2648         release_sock(sk);
2649         return res;
2650 }
2651
2652 /**
2653  * tipc_listen - allow socket to listen for incoming connections
2654  * @sock: socket structure
2655  * @len: (unused)
2656  *
2657  * Returns 0 on success, errno otherwise
2658  */
2659 static int tipc_listen(struct socket *sock, int len)
2660 {
2661         struct sock *sk = sock->sk;
2662         int res;
2663
2664         lock_sock(sk);
2665         res = tipc_set_sk_state(sk, TIPC_LISTEN);
2666         release_sock(sk);
2667
2668         return res;
2669 }
2670
2671 static int tipc_wait_for_accept(struct socket *sock, long timeo)
2672 {
2673         struct sock *sk = sock->sk;
2674         DEFINE_WAIT_FUNC(wait, woken_wake_function);
2675         int err;
2676
2677         /* True wake-one mechanism for incoming connections: only
2678          * one process gets woken up, not the 'whole herd'.
2679          * Since we do not 'race & poll' for established sockets
2680          * anymore, the common case will execute the loop only once.
2681         */
2682         for (;;) {
2683                 if (timeo && skb_queue_empty(&sk->sk_receive_queue)) {
2684                         add_wait_queue(sk_sleep(sk), &wait);
2685                         release_sock(sk);
2686                         timeo = wait_woken(&wait, TASK_INTERRUPTIBLE, timeo);
2687                         lock_sock(sk);
2688                         remove_wait_queue(sk_sleep(sk), &wait);
2689                 }
2690                 err = 0;
2691                 if (!skb_queue_empty(&sk->sk_receive_queue))
2692                         break;
2693                 err = -EAGAIN;
2694                 if (!timeo)
2695                         break;
2696                 err = sock_intr_errno(timeo);
2697                 if (signal_pending(current))
2698                         break;
2699         }
2700         return err;
2701 }
2702
2703 /**
2704  * tipc_accept - wait for connection request
2705  * @sock: listening socket
2706  * @new_sock: new socket that is to be connected
2707  * @flags: file-related flags associated with socket
2708  *
2709  * Returns 0 on success, errno otherwise
2710  */
2711 static int tipc_accept(struct socket *sock, struct socket *new_sock, int flags,
2712                        bool kern)
2713 {
2714         struct sock *new_sk, *sk = sock->sk;
2715         struct tipc_sock *new_tsock;
2716         struct msghdr m = {NULL,};
2717         struct tipc_msg *msg;
2718         struct sk_buff *buf;
2719         long timeo;
2720         int res;
2721
2722         lock_sock(sk);
2723
2724         if (sk->sk_state != TIPC_LISTEN) {
2725                 res = -EINVAL;
2726                 goto exit;
2727         }
2728         timeo = sock_rcvtimeo(sk, flags & O_NONBLOCK);
2729         res = tipc_wait_for_accept(sock, timeo);
2730         if (res)
2731                 goto exit;
2732
2733         buf = skb_peek(&sk->sk_receive_queue);
2734
2735         res = tipc_sk_create(sock_net(sock->sk), new_sock, 0, kern);
2736         if (res)
2737                 goto exit;
2738         security_sk_clone(sock->sk, new_sock->sk);
2739
2740         new_sk = new_sock->sk;
2741         new_tsock = tipc_sk(new_sk);
2742         msg = buf_msg(buf);
2743
2744         /* we lock on new_sk; but lockdep sees the lock on sk */
2745         lock_sock_nested(new_sk, SINGLE_DEPTH_NESTING);
2746
2747         /*
2748          * Reject any stray messages received by new socket
2749          * before the socket lock was taken (very, very unlikely)
2750          */
2751         tsk_rej_rx_queue(new_sk, TIPC_ERR_NO_PORT);
2752
2753         /* Connect new socket to it's peer */
2754         tipc_sk_finish_conn(new_tsock, msg_origport(msg), msg_orignode(msg));
2755
2756         tsk_set_importance(new_sk, msg_importance(msg));
2757         if (msg_named(msg)) {
2758                 new_tsock->conn_type = msg_nametype(msg);
2759                 new_tsock->conn_instance = msg_nameinst(msg);
2760         }
2761
2762         /*
2763          * Respond to 'SYN-' by discarding it & returning 'ACK'.
2764          * Respond to 'SYN+' by queuing it on new socket & returning 'ACK'.
2765          */
2766         if (!msg_data_sz(msg)) {
2767                 tsk_advance_rx_queue(sk);
2768         } else {
2769                 __skb_dequeue(&sk->sk_receive_queue);
2770                 __skb_queue_head(&new_sk->sk_receive_queue, buf);
2771                 skb_set_owner_r(buf, new_sk);
2772         }
2773         __tipc_sendstream(new_sock, &m, 0);
2774         release_sock(new_sk);
2775 exit:
2776         release_sock(sk);
2777         return res;
2778 }
2779
2780 /**
2781  * tipc_shutdown - shutdown socket connection
2782  * @sock: socket structure
2783  * @how: direction to close (must be SHUT_RDWR)
2784  *
2785  * Terminates connection (if necessary), then purges socket's receive queue.
2786  *
2787  * Returns 0 on success, errno otherwise
2788  */
2789 static int tipc_shutdown(struct socket *sock, int how)
2790 {
2791         struct sock *sk = sock->sk;
2792         int res;
2793
2794         if (how != SHUT_RDWR)
2795                 return -EINVAL;
2796
2797         lock_sock(sk);
2798
2799         trace_tipc_sk_shutdown(sk, NULL, TIPC_DUMP_ALL, " ");
2800         __tipc_shutdown(sock, TIPC_CONN_SHUTDOWN);
2801         sk->sk_shutdown = SHUTDOWN_MASK;
2802
2803         if (sk->sk_state == TIPC_DISCONNECTING) {
2804                 /* Discard any unreceived messages */
2805                 __skb_queue_purge(&sk->sk_receive_queue);
2806
2807                 res = 0;
2808         } else {
2809                 res = -ENOTCONN;
2810         }
2811         /* Wake up anyone sleeping in poll. */
2812         sk->sk_state_change(sk);
2813
2814         release_sock(sk);
2815         return res;
2816 }
2817
2818 static void tipc_sk_check_probing_state(struct sock *sk,
2819                                         struct sk_buff_head *list)
2820 {
2821         struct tipc_sock *tsk = tipc_sk(sk);
2822         u32 pnode = tsk_peer_node(tsk);
2823         u32 pport = tsk_peer_port(tsk);
2824         u32 self = tsk_own_node(tsk);
2825         u32 oport = tsk->portid;
2826         struct sk_buff *skb;
2827
2828         if (tsk->probe_unacked) {
2829                 tipc_set_sk_state(sk, TIPC_DISCONNECTING);
2830                 sk->sk_err = ECONNABORTED;
2831                 tipc_node_remove_conn(sock_net(sk), pnode, pport);
2832                 sk->sk_state_change(sk);
2833                 return;
2834         }
2835         /* Prepare new probe */
2836         skb = tipc_msg_create(CONN_MANAGER, CONN_PROBE, INT_H_SIZE, 0,
2837                               pnode, self, pport, oport, TIPC_OK);
2838         if (skb)
2839                 __skb_queue_tail(list, skb);
2840         tsk->probe_unacked = true;
2841         sk_reset_timer(sk, &sk->sk_timer, jiffies + CONN_PROBING_INTV);
2842 }
2843
2844 static void tipc_sk_retry_connect(struct sock *sk, struct sk_buff_head *list)
2845 {
2846         struct tipc_sock *tsk = tipc_sk(sk);
2847
2848         /* Try again later if dest link is congested */
2849         if (tsk->cong_link_cnt) {
2850                 sk_reset_timer(sk, &sk->sk_timer,
2851                                jiffies + msecs_to_jiffies(100));
2852                 return;
2853         }
2854         /* Prepare SYN for retransmit */
2855         tipc_msg_skb_clone(&sk->sk_write_queue, list);
2856 }
2857
2858 static void tipc_sk_timeout(struct timer_list *t)
2859 {
2860         struct sock *sk = from_timer(sk, t, sk_timer);
2861         struct tipc_sock *tsk = tipc_sk(sk);
2862         u32 pnode = tsk_peer_node(tsk);
2863         struct sk_buff_head list;
2864         int rc = 0;
2865
2866         __skb_queue_head_init(&list);
2867         bh_lock_sock(sk);
2868
2869         /* Try again later if socket is busy */
2870         if (sock_owned_by_user(sk)) {
2871                 sk_reset_timer(sk, &sk->sk_timer, jiffies + HZ / 20);
2872                 bh_unlock_sock(sk);
2873                 sock_put(sk);
2874                 return;
2875         }
2876
2877         if (sk->sk_state == TIPC_ESTABLISHED)
2878                 tipc_sk_check_probing_state(sk, &list);
2879         else if (sk->sk_state == TIPC_CONNECTING)
2880                 tipc_sk_retry_connect(sk, &list);
2881
2882         bh_unlock_sock(sk);
2883
2884         if (!skb_queue_empty(&list))
2885                 rc = tipc_node_xmit(sock_net(sk), &list, pnode, tsk->portid);
2886
2887         /* SYN messages may cause link congestion */
2888         if (rc == -ELINKCONG) {
2889                 tipc_dest_push(&tsk->cong_links, pnode, 0);
2890                 tsk->cong_link_cnt = 1;
2891         }
2892         sock_put(sk);
2893 }
2894
2895 static int tipc_sk_publish(struct tipc_sock *tsk, uint scope,
2896                            struct tipc_name_seq const *seq)
2897 {
2898         struct sock *sk = &tsk->sk;
2899         struct net *net = sock_net(sk);
2900         struct publication *publ;
2901         u32 key;
2902
2903         if (scope != TIPC_NODE_SCOPE)
2904                 scope = TIPC_CLUSTER_SCOPE;
2905
2906         if (tipc_sk_connected(sk))
2907                 return -EINVAL;
2908         key = tsk->portid + tsk->pub_count + 1;
2909         if (key == tsk->portid)
2910                 return -EADDRINUSE;
2911
2912         publ = tipc_nametbl_publish(net, seq->type, seq->lower, seq->upper,
2913                                     scope, tsk->portid, key);
2914         if (unlikely(!publ))
2915                 return -EINVAL;
2916
2917         list_add(&publ->binding_sock, &tsk->publications);
2918         tsk->pub_count++;
2919         tsk->published = 1;
2920         return 0;
2921 }
2922
2923 static int tipc_sk_withdraw(struct tipc_sock *tsk, uint scope,
2924                             struct tipc_name_seq const *seq)
2925 {
2926         struct net *net = sock_net(&tsk->sk);
2927         struct publication *publ;
2928         struct publication *safe;
2929         int rc = -EINVAL;
2930
2931         if (scope != TIPC_NODE_SCOPE)
2932                 scope = TIPC_CLUSTER_SCOPE;
2933
2934         list_for_each_entry_safe(publ, safe, &tsk->publications, binding_sock) {
2935                 if (seq) {
2936                         if (publ->scope != scope)
2937                                 continue;
2938                         if (publ->type != seq->type)
2939                                 continue;
2940                         if (publ->lower != seq->lower)
2941                                 continue;
2942                         if (publ->upper != seq->upper)
2943                                 break;
2944                         tipc_nametbl_withdraw(net, publ->type, publ->lower,
2945                                               publ->upper, publ->key);
2946                         rc = 0;
2947                         break;
2948                 }
2949                 tipc_nametbl_withdraw(net, publ->type, publ->lower,
2950                                       publ->upper, publ->key);
2951                 rc = 0;
2952         }
2953         if (list_empty(&tsk->publications))
2954                 tsk->published = 0;
2955         return rc;
2956 }
2957
2958 /* tipc_sk_reinit: set non-zero address in all existing sockets
2959  *                 when we go from standalone to network mode.
2960  */
2961 void tipc_sk_reinit(struct net *net)
2962 {
2963         struct tipc_net *tn = net_generic(net, tipc_net_id);
2964         struct rhashtable_iter iter;
2965         struct tipc_sock *tsk;
2966         struct tipc_msg *msg;
2967
2968         rhashtable_walk_enter(&tn->sk_rht, &iter);
2969
2970         do {
2971                 rhashtable_walk_start(&iter);
2972
2973                 while ((tsk = rhashtable_walk_next(&iter)) && !IS_ERR(tsk)) {
2974                         sock_hold(&tsk->sk);
2975                         rhashtable_walk_stop(&iter);
2976                         lock_sock(&tsk->sk);
2977                         msg = &tsk->phdr;
2978                         msg_set_prevnode(msg, tipc_own_addr(net));
2979                         msg_set_orignode(msg, tipc_own_addr(net));
2980                         release_sock(&tsk->sk);
2981                         rhashtable_walk_start(&iter);
2982                         sock_put(&tsk->sk);
2983                 }
2984
2985                 rhashtable_walk_stop(&iter);
2986         } while (tsk == ERR_PTR(-EAGAIN));
2987
2988         rhashtable_walk_exit(&iter);
2989 }
2990
2991 static struct tipc_sock *tipc_sk_lookup(struct net *net, u32 portid)
2992 {
2993         struct tipc_net *tn = net_generic(net, tipc_net_id);
2994         struct tipc_sock *tsk;
2995
2996         rcu_read_lock();
2997         tsk = rhashtable_lookup(&tn->sk_rht, &portid, tsk_rht_params);
2998         if (tsk)
2999                 sock_hold(&tsk->sk);
3000         rcu_read_unlock();
3001
3002         return tsk;
3003 }
3004
3005 static int tipc_sk_insert(struct tipc_sock *tsk)
3006 {
3007         struct sock *sk = &tsk->sk;
3008         struct net *net = sock_net(sk);
3009         struct tipc_net *tn = net_generic(net, tipc_net_id);
3010         u32 remaining = (TIPC_MAX_PORT - TIPC_MIN_PORT) + 1;
3011         u32 portid = prandom_u32() % remaining + TIPC_MIN_PORT;
3012
3013         while (remaining--) {
3014                 portid++;
3015                 if ((portid < TIPC_MIN_PORT) || (portid > TIPC_MAX_PORT))
3016                         portid = TIPC_MIN_PORT;
3017                 tsk->portid = portid;
3018                 sock_hold(&tsk->sk);
3019                 if (!rhashtable_lookup_insert_fast(&tn->sk_rht, &tsk->node,
3020                                                    tsk_rht_params))
3021                         return 0;
3022                 sock_put(&tsk->sk);
3023         }
3024
3025         return -1;
3026 }
3027
3028 static void tipc_sk_remove(struct tipc_sock *tsk)
3029 {
3030         struct sock *sk = &tsk->sk;
3031         struct tipc_net *tn = net_generic(sock_net(sk), tipc_net_id);
3032
3033         if (!rhashtable_remove_fast(&tn->sk_rht, &tsk->node, tsk_rht_params)) {
3034                 WARN_ON(refcount_read(&sk->sk_refcnt) == 1);
3035                 __sock_put(sk);
3036         }
3037 }
3038
3039 static const struct rhashtable_params tsk_rht_params = {
3040         .nelem_hint = 192,
3041         .head_offset = offsetof(struct tipc_sock, node),
3042         .key_offset = offsetof(struct tipc_sock, portid),
3043         .key_len = sizeof(u32), /* portid */
3044         .max_size = 1048576,
3045         .min_size = 256,
3046         .automatic_shrinking = true,
3047 };
3048
3049 int tipc_sk_rht_init(struct net *net)
3050 {
3051         struct tipc_net *tn = net_generic(net, tipc_net_id);
3052
3053         return rhashtable_init(&tn->sk_rht, &tsk_rht_params);
3054 }
3055
3056 void tipc_sk_rht_destroy(struct net *net)
3057 {
3058         struct tipc_net *tn = net_generic(net, tipc_net_id);
3059
3060         /* Wait for socket readers to complete */
3061         synchronize_net();
3062
3063         rhashtable_destroy(&tn->sk_rht);
3064 }
3065
3066 static int tipc_sk_join(struct tipc_sock *tsk, struct tipc_group_req *mreq)
3067 {
3068         struct net *net = sock_net(&tsk->sk);
3069         struct tipc_group *grp = tsk->group;
3070         struct tipc_msg *hdr = &tsk->phdr;
3071         struct tipc_name_seq seq;
3072         int rc;
3073
3074         if (mreq->type < TIPC_RESERVED_TYPES)
3075                 return -EACCES;
3076         if (mreq->scope > TIPC_NODE_SCOPE)
3077                 return -EINVAL;
3078         if (grp)
3079                 return -EACCES;
3080         grp = tipc_group_create(net, tsk->portid, mreq, &tsk->group_is_open);
3081         if (!grp)
3082                 return -ENOMEM;
3083         tsk->group = grp;
3084         msg_set_lookup_scope(hdr, mreq->scope);
3085         msg_set_nametype(hdr, mreq->type);
3086         msg_set_dest_droppable(hdr, true);
3087         seq.type = mreq->type;
3088         seq.lower = mreq->instance;
3089         seq.upper = seq.lower;
3090         tipc_nametbl_build_group(net, grp, mreq->type, mreq->scope);
3091         rc = tipc_sk_publish(tsk, mreq->scope, &seq);
3092         if (rc) {
3093                 tipc_group_delete(net, grp);
3094                 tsk->group = NULL;
3095                 return rc;
3096         }
3097         /* Eliminate any risk that a broadcast overtakes sent JOINs */
3098         tsk->mc_method.rcast = true;
3099         tsk->mc_method.mandatory = true;
3100         tipc_group_join(net, grp, &tsk->sk.sk_rcvbuf);
3101         return rc;
3102 }
3103
3104 static int tipc_sk_leave(struct tipc_sock *tsk)
3105 {
3106         struct net *net = sock_net(&tsk->sk);
3107         struct tipc_group *grp = tsk->group;
3108         struct tipc_name_seq seq;
3109         int scope;
3110
3111         if (!grp)
3112                 return -EINVAL;
3113         tipc_group_self(grp, &seq, &scope);
3114         tipc_group_delete(net, grp);
3115         tsk->group = NULL;
3116         tipc_sk_withdraw(tsk, scope, &seq);
3117         return 0;
3118 }
3119
3120 /**
3121  * tipc_setsockopt - set socket option
3122  * @sock: socket structure
3123  * @lvl: option level
3124  * @opt: option identifier
3125  * @ov: pointer to new option value
3126  * @ol: length of option value
3127  *
3128  * For stream sockets only, accepts and ignores all IPPROTO_TCP options
3129  * (to ease compatibility).
3130  *
3131  * Returns 0 on success, errno otherwise
3132  */
3133 static int tipc_setsockopt(struct socket *sock, int lvl, int opt,
3134                            sockptr_t ov, unsigned int ol)
3135 {
3136         struct sock *sk = sock->sk;
3137         struct tipc_sock *tsk = tipc_sk(sk);
3138         struct tipc_group_req mreq;
3139         u32 value = 0;
3140         int res = 0;
3141
3142         if ((lvl == IPPROTO_TCP) && (sock->type == SOCK_STREAM))
3143                 return 0;
3144         if (lvl != SOL_TIPC)
3145                 return -ENOPROTOOPT;
3146
3147         switch (opt) {
3148         case TIPC_IMPORTANCE:
3149         case TIPC_SRC_DROPPABLE:
3150         case TIPC_DEST_DROPPABLE:
3151         case TIPC_CONN_TIMEOUT:
3152         case TIPC_NODELAY:
3153                 if (ol < sizeof(value))
3154                         return -EINVAL;
3155                 if (copy_from_sockptr(&value, ov, sizeof(u32)))
3156                         return -EFAULT;
3157                 break;
3158         case TIPC_GROUP_JOIN:
3159                 if (ol < sizeof(mreq))
3160                         return -EINVAL;
3161                 if (copy_from_sockptr(&mreq, ov, sizeof(mreq)))
3162                         return -EFAULT;
3163                 break;
3164         default:
3165                 if (!sockptr_is_null(ov) || ol)
3166                         return -EINVAL;
3167         }
3168
3169         lock_sock(sk);
3170
3171         switch (opt) {
3172         case TIPC_IMPORTANCE:
3173                 res = tsk_set_importance(sk, value);
3174                 break;
3175         case TIPC_SRC_DROPPABLE:
3176                 if (sock->type != SOCK_STREAM)
3177                         tsk_set_unreliable(tsk, value);
3178                 else
3179                         res = -ENOPROTOOPT;
3180                 break;
3181         case TIPC_DEST_DROPPABLE:
3182                 tsk_set_unreturnable(tsk, value);
3183                 break;
3184         case TIPC_CONN_TIMEOUT:
3185                 tipc_sk(sk)->conn_timeout = value;
3186                 break;
3187         case TIPC_MCAST_BROADCAST:
3188                 tsk->mc_method.rcast = false;
3189                 tsk->mc_method.mandatory = true;
3190                 break;
3191         case TIPC_MCAST_REPLICAST:
3192                 tsk->mc_method.rcast = true;
3193                 tsk->mc_method.mandatory = true;
3194                 break;
3195         case TIPC_GROUP_JOIN:
3196                 res = tipc_sk_join(tsk, &mreq);
3197                 break;
3198         case TIPC_GROUP_LEAVE:
3199                 res = tipc_sk_leave(tsk);
3200                 break;
3201         case TIPC_NODELAY:
3202                 tsk->nodelay = !!value;
3203                 tsk_set_nagle(tsk);
3204                 break;
3205         default:
3206                 res = -EINVAL;
3207         }
3208
3209         release_sock(sk);
3210
3211         return res;
3212 }
3213
3214 /**
3215  * tipc_getsockopt - get socket option
3216  * @sock: socket structure
3217  * @lvl: option level
3218  * @opt: option identifier
3219  * @ov: receptacle for option value
3220  * @ol: receptacle for length of option value
3221  *
3222  * For stream sockets only, returns 0 length result for all IPPROTO_TCP options
3223  * (to ease compatibility).
3224  *
3225  * Returns 0 on success, errno otherwise
3226  */
3227 static int tipc_getsockopt(struct socket *sock, int lvl, int opt,
3228                            char __user *ov, int __user *ol)
3229 {
3230         struct sock *sk = sock->sk;
3231         struct tipc_sock *tsk = tipc_sk(sk);
3232         struct tipc_name_seq seq;
3233         int len, scope;
3234         u32 value;
3235         int res;
3236
3237         if ((lvl == IPPROTO_TCP) && (sock->type == SOCK_STREAM))
3238                 return put_user(0, ol);
3239         if (lvl != SOL_TIPC)
3240                 return -ENOPROTOOPT;
3241         res = get_user(len, ol);
3242         if (res)
3243                 return res;
3244
3245         lock_sock(sk);
3246
3247         switch (opt) {
3248         case TIPC_IMPORTANCE:
3249                 value = tsk_importance(tsk);
3250                 break;
3251         case TIPC_SRC_DROPPABLE:
3252                 value = tsk_unreliable(tsk);
3253                 break;
3254         case TIPC_DEST_DROPPABLE:
3255                 value = tsk_unreturnable(tsk);
3256                 break;
3257         case TIPC_CONN_TIMEOUT:
3258                 value = tsk->conn_timeout;
3259                 /* no need to set "res", since already 0 at this point */
3260                 break;
3261         case TIPC_NODE_RECVQ_DEPTH:
3262                 value = 0; /* was tipc_queue_size, now obsolete */
3263                 break;
3264         case TIPC_SOCK_RECVQ_DEPTH:
3265                 value = skb_queue_len(&sk->sk_receive_queue);
3266                 break;
3267         case TIPC_SOCK_RECVQ_USED:
3268                 value = sk_rmem_alloc_get(sk);
3269                 break;
3270         case TIPC_GROUP_JOIN:
3271                 seq.type = 0;
3272                 if (tsk->group)
3273                         tipc_group_self(tsk->group, &seq, &scope);
3274                 value = seq.type;
3275                 break;
3276         default:
3277                 res = -EINVAL;
3278         }
3279
3280         release_sock(sk);
3281
3282         if (res)
3283                 return res;     /* "get" failed */
3284
3285         if (len < sizeof(value))
3286                 return -EINVAL;
3287
3288         if (copy_to_user(ov, &value, sizeof(value)))
3289                 return -EFAULT;
3290
3291         return put_user(sizeof(value), ol);
3292 }
3293
3294 static int tipc_ioctl(struct socket *sock, unsigned int cmd, unsigned long arg)
3295 {
3296         struct net *net = sock_net(sock->sk);
3297         struct tipc_sioc_nodeid_req nr = {0};
3298         struct tipc_sioc_ln_req lnr;
3299         void __user *argp = (void __user *)arg;
3300
3301         switch (cmd) {
3302         case SIOCGETLINKNAME:
3303                 if (copy_from_user(&lnr, argp, sizeof(lnr)))
3304                         return -EFAULT;
3305                 if (!tipc_node_get_linkname(net,
3306                                             lnr.bearer_id & 0xffff, lnr.peer,
3307                                             lnr.linkname, TIPC_MAX_LINK_NAME)) {
3308                         if (copy_to_user(argp, &lnr, sizeof(lnr)))
3309                                 return -EFAULT;
3310                         return 0;
3311                 }
3312                 return -EADDRNOTAVAIL;
3313         case SIOCGETNODEID:
3314                 if (copy_from_user(&nr, argp, sizeof(nr)))
3315                         return -EFAULT;
3316                 if (!tipc_node_get_id(net, nr.peer, nr.node_id))
3317                         return -EADDRNOTAVAIL;
3318                 if (copy_to_user(argp, &nr, sizeof(nr)))
3319                         return -EFAULT;
3320                 return 0;
3321         default:
3322                 return -ENOIOCTLCMD;
3323         }
3324 }
3325
3326 static int tipc_socketpair(struct socket *sock1, struct socket *sock2)
3327 {
3328         struct tipc_sock *tsk2 = tipc_sk(sock2->sk);
3329         struct tipc_sock *tsk1 = tipc_sk(sock1->sk);
3330         u32 onode = tipc_own_addr(sock_net(sock1->sk));
3331
3332         tsk1->peer.family = AF_TIPC;
3333         tsk1->peer.addrtype = TIPC_ADDR_ID;
3334         tsk1->peer.scope = TIPC_NODE_SCOPE;
3335         tsk1->peer.addr.id.ref = tsk2->portid;
3336         tsk1->peer.addr.id.node = onode;
3337         tsk2->peer.family = AF_TIPC;
3338         tsk2->peer.addrtype = TIPC_ADDR_ID;
3339         tsk2->peer.scope = TIPC_NODE_SCOPE;
3340         tsk2->peer.addr.id.ref = tsk1->portid;
3341         tsk2->peer.addr.id.node = onode;
3342
3343         tipc_sk_finish_conn(tsk1, tsk2->portid, onode);
3344         tipc_sk_finish_conn(tsk2, tsk1->portid, onode);
3345         return 0;
3346 }
3347
3348 /* Protocol switches for the various types of TIPC sockets */
3349
3350 static const struct proto_ops msg_ops = {
3351         .owner          = THIS_MODULE,
3352         .family         = AF_TIPC,
3353         .release        = tipc_release,
3354         .bind           = tipc_bind,
3355         .connect        = tipc_connect,
3356         .socketpair     = tipc_socketpair,
3357         .accept         = sock_no_accept,
3358         .getname        = tipc_getname,
3359         .poll           = tipc_poll,
3360         .ioctl          = tipc_ioctl,
3361         .listen         = sock_no_listen,
3362         .shutdown       = tipc_shutdown,
3363         .setsockopt     = tipc_setsockopt,
3364         .getsockopt     = tipc_getsockopt,
3365         .sendmsg        = tipc_sendmsg,
3366         .recvmsg        = tipc_recvmsg,
3367         .mmap           = sock_no_mmap,
3368         .sendpage       = sock_no_sendpage
3369 };
3370
3371 static const struct proto_ops packet_ops = {
3372         .owner          = THIS_MODULE,
3373         .family         = AF_TIPC,
3374         .release        = tipc_release,
3375         .bind           = tipc_bind,
3376         .connect        = tipc_connect,
3377         .socketpair     = tipc_socketpair,
3378         .accept         = tipc_accept,
3379         .getname        = tipc_getname,
3380         .poll           = tipc_poll,
3381         .ioctl          = tipc_ioctl,
3382         .listen         = tipc_listen,
3383         .shutdown       = tipc_shutdown,
3384         .setsockopt     = tipc_setsockopt,
3385         .getsockopt     = tipc_getsockopt,
3386         .sendmsg        = tipc_send_packet,
3387         .recvmsg        = tipc_recvmsg,
3388         .mmap           = sock_no_mmap,
3389         .sendpage       = sock_no_sendpage
3390 };
3391
3392 static const struct proto_ops stream_ops = {
3393         .owner          = THIS_MODULE,
3394         .family         = AF_TIPC,
3395         .release        = tipc_release,
3396         .bind           = tipc_bind,
3397         .connect        = tipc_connect,
3398         .socketpair     = tipc_socketpair,
3399         .accept         = tipc_accept,
3400         .getname        = tipc_getname,
3401         .poll           = tipc_poll,
3402         .ioctl          = tipc_ioctl,
3403         .listen         = tipc_listen,
3404         .shutdown       = tipc_shutdown,
3405         .setsockopt     = tipc_setsockopt,
3406         .getsockopt     = tipc_getsockopt,
3407         .sendmsg        = tipc_sendstream,
3408         .recvmsg        = tipc_recvstream,
3409         .mmap           = sock_no_mmap,
3410         .sendpage       = sock_no_sendpage
3411 };
3412
3413 static const struct net_proto_family tipc_family_ops = {
3414         .owner          = THIS_MODULE,
3415         .family         = AF_TIPC,
3416         .create         = tipc_sk_create
3417 };
3418
3419 static struct proto tipc_proto = {
3420         .name           = "TIPC",
3421         .owner          = THIS_MODULE,
3422         .obj_size       = sizeof(struct tipc_sock),
3423         .sysctl_rmem    = sysctl_tipc_rmem
3424 };
3425
3426 /**
3427  * tipc_socket_init - initialize TIPC socket interface
3428  *
3429  * Returns 0 on success, errno otherwise
3430  */
3431 int tipc_socket_init(void)
3432 {
3433         int res;
3434
3435         res = proto_register(&tipc_proto, 1);
3436         if (res) {
3437                 pr_err("Failed to register TIPC protocol type\n");
3438                 goto out;
3439         }
3440
3441         res = sock_register(&tipc_family_ops);
3442         if (res) {
3443                 pr_err("Failed to register TIPC socket type\n");
3444                 proto_unregister(&tipc_proto);
3445                 goto out;
3446         }
3447  out:
3448         return res;
3449 }
3450
3451 /**
3452  * tipc_socket_stop - stop TIPC socket interface
3453  */
3454 void tipc_socket_stop(void)
3455 {
3456         sock_unregister(tipc_family_ops.family);
3457         proto_unregister(&tipc_proto);
3458 }
3459
3460 /* Caller should hold socket lock for the passed tipc socket. */
3461 static int __tipc_nl_add_sk_con(struct sk_buff *skb, struct tipc_sock *tsk)
3462 {
3463         u32 peer_node;
3464         u32 peer_port;
3465         struct nlattr *nest;
3466
3467         peer_node = tsk_peer_node(tsk);
3468         peer_port = tsk_peer_port(tsk);
3469
3470         nest = nla_nest_start_noflag(skb, TIPC_NLA_SOCK_CON);
3471         if (!nest)
3472                 return -EMSGSIZE;
3473
3474         if (nla_put_u32(skb, TIPC_NLA_CON_NODE, peer_node))
3475                 goto msg_full;
3476         if (nla_put_u32(skb, TIPC_NLA_CON_SOCK, peer_port))
3477                 goto msg_full;
3478
3479         if (tsk->conn_type != 0) {
3480                 if (nla_put_flag(skb, TIPC_NLA_CON_FLAG))
3481                         goto msg_full;
3482                 if (nla_put_u32(skb, TIPC_NLA_CON_TYPE, tsk->conn_type))
3483                         goto msg_full;
3484                 if (nla_put_u32(skb, TIPC_NLA_CON_INST, tsk->conn_instance))
3485                         goto msg_full;
3486         }
3487         nla_nest_end(skb, nest);
3488
3489         return 0;
3490
3491 msg_full:
3492         nla_nest_cancel(skb, nest);
3493
3494         return -EMSGSIZE;
3495 }
3496
3497 static int __tipc_nl_add_sk_info(struct sk_buff *skb, struct tipc_sock
3498                           *tsk)
3499 {
3500         struct net *net = sock_net(skb->sk);
3501         struct sock *sk = &tsk->sk;
3502
3503         if (nla_put_u32(skb, TIPC_NLA_SOCK_REF, tsk->portid) ||
3504             nla_put_u32(skb, TIPC_NLA_SOCK_ADDR, tipc_own_addr(net)))
3505                 return -EMSGSIZE;
3506
3507         if (tipc_sk_connected(sk)) {
3508                 if (__tipc_nl_add_sk_con(skb, tsk))
3509                         return -EMSGSIZE;
3510         } else if (!list_empty(&tsk->publications)) {
3511                 if (nla_put_flag(skb, TIPC_NLA_SOCK_HAS_PUBL))
3512                         return -EMSGSIZE;
3513         }
3514         return 0;
3515 }
3516
3517 /* Caller should hold socket lock for the passed tipc socket. */
3518 static int __tipc_nl_add_sk(struct sk_buff *skb, struct netlink_callback *cb,
3519                             struct tipc_sock *tsk)
3520 {
3521         struct nlattr *attrs;
3522         void *hdr;
3523
3524         hdr = genlmsg_put(skb, NETLINK_CB(cb->skb).portid, cb->nlh->nlmsg_seq,
3525                           &tipc_genl_family, NLM_F_MULTI, TIPC_NL_SOCK_GET);
3526         if (!hdr)
3527                 goto msg_cancel;
3528
3529         attrs = nla_nest_start_noflag(skb, TIPC_NLA_SOCK);
3530         if (!attrs)
3531                 goto genlmsg_cancel;
3532
3533         if (__tipc_nl_add_sk_info(skb, tsk))
3534                 goto attr_msg_cancel;
3535
3536         nla_nest_end(skb, attrs);
3537         genlmsg_end(skb, hdr);
3538
3539         return 0;
3540
3541 attr_msg_cancel:
3542         nla_nest_cancel(skb, attrs);
3543 genlmsg_cancel:
3544         genlmsg_cancel(skb, hdr);
3545 msg_cancel:
3546         return -EMSGSIZE;
3547 }
3548
3549 int tipc_nl_sk_walk(struct sk_buff *skb, struct netlink_callback *cb,
3550                     int (*skb_handler)(struct sk_buff *skb,
3551                                        struct netlink_callback *cb,
3552                                        struct tipc_sock *tsk))
3553 {
3554         struct rhashtable_iter *iter = (void *)cb->args[4];
3555         struct tipc_sock *tsk;
3556         int err;
3557
3558         rhashtable_walk_start(iter);
3559         while ((tsk = rhashtable_walk_next(iter)) != NULL) {
3560                 if (IS_ERR(tsk)) {
3561                         err = PTR_ERR(tsk);
3562                         if (err == -EAGAIN) {
3563                                 err = 0;
3564                                 continue;
3565                         }
3566                         break;
3567                 }
3568
3569                 sock_hold(&tsk->sk);
3570                 rhashtable_walk_stop(iter);
3571                 lock_sock(&tsk->sk);
3572                 err = skb_handler(skb, cb, tsk);
3573                 if (err) {
3574                         release_sock(&tsk->sk);
3575                         sock_put(&tsk->sk);
3576                         goto out;
3577                 }
3578                 release_sock(&tsk->sk);
3579                 rhashtable_walk_start(iter);
3580                 sock_put(&tsk->sk);
3581         }
3582         rhashtable_walk_stop(iter);
3583 out:
3584         return skb->len;
3585 }
3586 EXPORT_SYMBOL(tipc_nl_sk_walk);
3587
3588 int tipc_dump_start(struct netlink_callback *cb)
3589 {
3590         return __tipc_dump_start(cb, sock_net(cb->skb->sk));
3591 }
3592 EXPORT_SYMBOL(tipc_dump_start);
3593
3594 int __tipc_dump_start(struct netlink_callback *cb, struct net *net)
3595 {
3596         /* tipc_nl_name_table_dump() uses cb->args[0...3]. */
3597         struct rhashtable_iter *iter = (void *)cb->args[4];
3598         struct tipc_net *tn = tipc_net(net);
3599
3600         if (!iter) {
3601                 iter = kmalloc(sizeof(*iter), GFP_KERNEL);
3602                 if (!iter)
3603                         return -ENOMEM;
3604
3605                 cb->args[4] = (long)iter;
3606         }
3607
3608         rhashtable_walk_enter(&tn->sk_rht, iter);
3609         return 0;
3610 }
3611
3612 int tipc_dump_done(struct netlink_callback *cb)
3613 {
3614         struct rhashtable_iter *hti = (void *)cb->args[4];
3615
3616         rhashtable_walk_exit(hti);
3617         kfree(hti);
3618         return 0;
3619 }
3620 EXPORT_SYMBOL(tipc_dump_done);
3621
3622 int tipc_sk_fill_sock_diag(struct sk_buff *skb, struct netlink_callback *cb,
3623                            struct tipc_sock *tsk, u32 sk_filter_state,
3624                            u64 (*tipc_diag_gen_cookie)(struct sock *sk))
3625 {
3626         struct sock *sk = &tsk->sk;
3627         struct nlattr *attrs;
3628         struct nlattr *stat;
3629
3630         /*filter response w.r.t sk_state*/
3631         if (!(sk_filter_state & (1 << sk->sk_state)))
3632                 return 0;
3633
3634         attrs = nla_nest_start_noflag(skb, TIPC_NLA_SOCK);
3635         if (!attrs)
3636                 goto msg_cancel;
3637
3638         if (__tipc_nl_add_sk_info(skb, tsk))
3639                 goto attr_msg_cancel;
3640
3641         if (nla_put_u32(skb, TIPC_NLA_SOCK_TYPE, (u32)sk->sk_type) ||
3642             nla_put_u32(skb, TIPC_NLA_SOCK_TIPC_STATE, (u32)sk->sk_state) ||
3643             nla_put_u32(skb, TIPC_NLA_SOCK_INO, sock_i_ino(sk)) ||
3644             nla_put_u32(skb, TIPC_NLA_SOCK_UID,
3645                         from_kuid_munged(sk_user_ns(NETLINK_CB(cb->skb).sk),
3646                                          sock_i_uid(sk))) ||
3647             nla_put_u64_64bit(skb, TIPC_NLA_SOCK_COOKIE,
3648                               tipc_diag_gen_cookie(sk),
3649                               TIPC_NLA_SOCK_PAD))
3650                 goto attr_msg_cancel;
3651
3652         stat = nla_nest_start_noflag(skb, TIPC_NLA_SOCK_STAT);
3653         if (!stat)
3654                 goto attr_msg_cancel;
3655
3656         if (nla_put_u32(skb, TIPC_NLA_SOCK_STAT_RCVQ,
3657                         skb_queue_len(&sk->sk_receive_queue)) ||
3658             nla_put_u32(skb, TIPC_NLA_SOCK_STAT_SENDQ,
3659                         skb_queue_len(&sk->sk_write_queue)) ||
3660             nla_put_u32(skb, TIPC_NLA_SOCK_STAT_DROP,
3661                         atomic_read(&sk->sk_drops)))
3662                 goto stat_msg_cancel;
3663
3664         if (tsk->cong_link_cnt &&
3665             nla_put_flag(skb, TIPC_NLA_SOCK_STAT_LINK_CONG))
3666                 goto stat_msg_cancel;
3667
3668         if (tsk_conn_cong(tsk) &&
3669             nla_put_flag(skb, TIPC_NLA_SOCK_STAT_CONN_CONG))
3670                 goto stat_msg_cancel;
3671
3672         nla_nest_end(skb, stat);
3673
3674         if (tsk->group)
3675                 if (tipc_group_fill_sock_diag(tsk->group, skb))
3676                         goto stat_msg_cancel;
3677
3678         nla_nest_end(skb, attrs);
3679
3680         return 0;
3681
3682 stat_msg_cancel:
3683         nla_nest_cancel(skb, stat);
3684 attr_msg_cancel:
3685         nla_nest_cancel(skb, attrs);
3686 msg_cancel:
3687         return -EMSGSIZE;
3688 }
3689 EXPORT_SYMBOL(tipc_sk_fill_sock_diag);
3690
3691 int tipc_nl_sk_dump(struct sk_buff *skb, struct netlink_callback *cb)
3692 {
3693         return tipc_nl_sk_walk(skb, cb, __tipc_nl_add_sk);
3694 }
3695
3696 /* Caller should hold socket lock for the passed tipc socket. */
3697 static int __tipc_nl_add_sk_publ(struct sk_buff *skb,
3698                                  struct netlink_callback *cb,
3699                                  struct publication *publ)
3700 {
3701         void *hdr;
3702         struct nlattr *attrs;
3703
3704         hdr = genlmsg_put(skb, NETLINK_CB(cb->skb).portid, cb->nlh->nlmsg_seq,
3705                           &tipc_genl_family, NLM_F_MULTI, TIPC_NL_PUBL_GET);
3706         if (!hdr)
3707                 goto msg_cancel;
3708
3709         attrs = nla_nest_start_noflag(skb, TIPC_NLA_PUBL);
3710         if (!attrs)
3711                 goto genlmsg_cancel;
3712
3713         if (nla_put_u32(skb, TIPC_NLA_PUBL_KEY, publ->key))
3714                 goto attr_msg_cancel;
3715         if (nla_put_u32(skb, TIPC_NLA_PUBL_TYPE, publ->type))
3716                 goto attr_msg_cancel;
3717         if (nla_put_u32(skb, TIPC_NLA_PUBL_LOWER, publ->lower))
3718                 goto attr_msg_cancel;
3719         if (nla_put_u32(skb, TIPC_NLA_PUBL_UPPER, publ->upper))
3720                 goto attr_msg_cancel;
3721
3722         nla_nest_end(skb, attrs);
3723         genlmsg_end(skb, hdr);
3724
3725         return 0;
3726
3727 attr_msg_cancel:
3728         nla_nest_cancel(skb, attrs);
3729 genlmsg_cancel:
3730         genlmsg_cancel(skb, hdr);
3731 msg_cancel:
3732         return -EMSGSIZE;
3733 }
3734
3735 /* Caller should hold socket lock for the passed tipc socket. */
3736 static int __tipc_nl_list_sk_publ(struct sk_buff *skb,
3737                                   struct netlink_callback *cb,
3738                                   struct tipc_sock *tsk, u32 *last_publ)
3739 {
3740         int err;
3741         struct publication *p;
3742
3743         if (*last_publ) {
3744                 list_for_each_entry(p, &tsk->publications, binding_sock) {
3745                         if (p->key == *last_publ)
3746                                 break;
3747                 }
3748                 if (list_entry_is_head(p, &tsk->publications, binding_sock)) {
3749                         /* We never set seq or call nl_dump_check_consistent()
3750                          * this means that setting prev_seq here will cause the
3751                          * consistence check to fail in the netlink callback
3752                          * handler. Resulting in the last NLMSG_DONE message
3753                          * having the NLM_F_DUMP_INTR flag set.
3754                          */
3755                         cb->prev_seq = 1;
3756                         *last_publ = 0;
3757                         return -EPIPE;
3758                 }
3759         } else {
3760                 p = list_first_entry(&tsk->publications, struct publication,
3761                                      binding_sock);
3762         }
3763
3764         list_for_each_entry_from(p, &tsk->publications, binding_sock) {
3765                 err = __tipc_nl_add_sk_publ(skb, cb, p);
3766                 if (err) {
3767                         *last_publ = p->key;
3768                         return err;
3769                 }
3770         }
3771         *last_publ = 0;
3772
3773         return 0;
3774 }
3775
3776 int tipc_nl_publ_dump(struct sk_buff *skb, struct netlink_callback *cb)
3777 {
3778         int err;
3779         u32 tsk_portid = cb->args[0];
3780         u32 last_publ = cb->args[1];
3781         u32 done = cb->args[2];
3782         struct net *net = sock_net(skb->sk);
3783         struct tipc_sock *tsk;
3784
3785         if (!tsk_portid) {
3786                 struct nlattr **attrs = genl_dumpit_info(cb)->attrs;
3787                 struct nlattr *sock[TIPC_NLA_SOCK_MAX + 1];
3788
3789                 if (!attrs[TIPC_NLA_SOCK])
3790                         return -EINVAL;
3791
3792                 err = nla_parse_nested_deprecated(sock, TIPC_NLA_SOCK_MAX,
3793                                                   attrs[TIPC_NLA_SOCK],
3794                                                   tipc_nl_sock_policy, NULL);
3795                 if (err)
3796                         return err;
3797
3798                 if (!sock[TIPC_NLA_SOCK_REF])
3799                         return -EINVAL;
3800
3801                 tsk_portid = nla_get_u32(sock[TIPC_NLA_SOCK_REF]);
3802         }
3803
3804         if (done)
3805                 return 0;
3806
3807         tsk = tipc_sk_lookup(net, tsk_portid);
3808         if (!tsk)
3809                 return -EINVAL;
3810
3811         lock_sock(&tsk->sk);
3812         err = __tipc_nl_list_sk_publ(skb, cb, tsk, &last_publ);
3813         if (!err)
3814                 done = 1;
3815         release_sock(&tsk->sk);
3816         sock_put(&tsk->sk);
3817
3818         cb->args[0] = tsk_portid;
3819         cb->args[1] = last_publ;
3820         cb->args[2] = done;
3821
3822         return skb->len;
3823 }
3824
3825 /**
3826  * tipc_sk_filtering - check if a socket should be traced
3827  * @sk: the socket to be examined
3828  * @sysctl_tipc_sk_filter[]: the socket tuple for filtering,
3829  *  (portid, sock type, name type, name lower, name upper)
3830  *
3831  * Returns true if the socket meets the socket tuple data
3832  * (value 0 = 'any') or when there is no tuple set (all = 0),
3833  * otherwise false
3834  */
3835 bool tipc_sk_filtering(struct sock *sk)
3836 {
3837         struct tipc_sock *tsk;
3838         struct publication *p;
3839         u32 _port, _sktype, _type, _lower, _upper;
3840         u32 type = 0, lower = 0, upper = 0;
3841
3842         if (!sk)
3843                 return true;
3844
3845         tsk = tipc_sk(sk);
3846
3847         _port = sysctl_tipc_sk_filter[0];
3848         _sktype = sysctl_tipc_sk_filter[1];
3849         _type = sysctl_tipc_sk_filter[2];
3850         _lower = sysctl_tipc_sk_filter[3];
3851         _upper = sysctl_tipc_sk_filter[4];
3852
3853         if (!_port && !_sktype && !_type && !_lower && !_upper)
3854                 return true;
3855
3856         if (_port)
3857                 return (_port == tsk->portid);
3858
3859         if (_sktype && _sktype != sk->sk_type)
3860                 return false;
3861
3862         if (tsk->published) {
3863                 p = list_first_entry_or_null(&tsk->publications,
3864                                              struct publication, binding_sock);
3865                 if (p) {
3866                         type = p->type;
3867                         lower = p->lower;
3868                         upper = p->upper;
3869                 }
3870         }
3871
3872         if (!tipc_sk_type_connectionless(sk)) {
3873                 type = tsk->conn_type;
3874                 lower = tsk->conn_instance;
3875                 upper = tsk->conn_instance;
3876         }
3877
3878         if ((_type && _type != type) || (_lower && _lower != lower) ||
3879             (_upper && _upper != upper))
3880                 return false;
3881
3882         return true;
3883 }
3884
3885 u32 tipc_sock_get_portid(struct sock *sk)
3886 {
3887         return (sk) ? (tipc_sk(sk))->portid : 0;
3888 }
3889
3890 /**
3891  * tipc_sk_overlimit1 - check if socket rx queue is about to be overloaded,
3892  *                      both the rcv and backlog queues are considered
3893  * @sk: tipc sk to be checked
3894  * @skb: tipc msg to be checked
3895  *
3896  * Returns true if the socket rx queue allocation is > 90%, otherwise false
3897  */
3898
3899 bool tipc_sk_overlimit1(struct sock *sk, struct sk_buff *skb)
3900 {
3901         atomic_t *dcnt = &tipc_sk(sk)->dupl_rcvcnt;
3902         unsigned int lim = rcvbuf_limit(sk, skb) + atomic_read(dcnt);
3903         unsigned int qsize = sk->sk_backlog.len + sk_rmem_alloc_get(sk);
3904
3905         return (qsize > lim * 90 / 100);
3906 }
3907
3908 /**
3909  * tipc_sk_overlimit2 - check if socket rx queue is about to be overloaded,
3910  *                      only the rcv queue is considered
3911  * @sk: tipc sk to be checked
3912  * @skb: tipc msg to be checked
3913  *
3914  * Returns true if the socket rx queue allocation is > 90%, otherwise false
3915  */
3916
3917 bool tipc_sk_overlimit2(struct sock *sk, struct sk_buff *skb)
3918 {
3919         unsigned int lim = rcvbuf_limit(sk, skb);
3920         unsigned int qsize = sk_rmem_alloc_get(sk);
3921
3922         return (qsize > lim * 90 / 100);
3923 }
3924
3925 /**
3926  * tipc_sk_dump - dump TIPC socket
3927  * @sk: tipc sk to be dumped
3928  * @dqueues: bitmask to decide if any socket queue to be dumped?
3929  *           - TIPC_DUMP_NONE: don't dump socket queues
3930  *           - TIPC_DUMP_SK_SNDQ: dump socket send queue
3931  *           - TIPC_DUMP_SK_RCVQ: dump socket rcv queue
3932  *           - TIPC_DUMP_SK_BKLGQ: dump socket backlog queue
3933  *           - TIPC_DUMP_ALL: dump all the socket queues above
3934  * @buf: returned buffer of dump data in format
3935  */
3936 int tipc_sk_dump(struct sock *sk, u16 dqueues, char *buf)
3937 {
3938         int i = 0;
3939         size_t sz = (dqueues) ? SK_LMAX : SK_LMIN;
3940         struct tipc_sock *tsk;
3941         struct publication *p;
3942         bool tsk_connected;
3943
3944         if (!sk) {
3945                 i += scnprintf(buf, sz, "sk data: (null)\n");
3946                 return i;
3947         }
3948
3949         tsk = tipc_sk(sk);
3950         tsk_connected = !tipc_sk_type_connectionless(sk);
3951
3952         i += scnprintf(buf, sz, "sk data: %u", sk->sk_type);
3953         i += scnprintf(buf + i, sz - i, " %d", sk->sk_state);
3954         i += scnprintf(buf + i, sz - i, " %x", tsk_own_node(tsk));
3955         i += scnprintf(buf + i, sz - i, " %u", tsk->portid);
3956         i += scnprintf(buf + i, sz - i, " | %u", tsk_connected);
3957         if (tsk_connected) {
3958                 i += scnprintf(buf + i, sz - i, " %x", tsk_peer_node(tsk));
3959                 i += scnprintf(buf + i, sz - i, " %u", tsk_peer_port(tsk));
3960                 i += scnprintf(buf + i, sz - i, " %u", tsk->conn_type);
3961                 i += scnprintf(buf + i, sz - i, " %u", tsk->conn_instance);
3962         }
3963         i += scnprintf(buf + i, sz - i, " | %u", tsk->published);
3964         if (tsk->published) {
3965                 p = list_first_entry_or_null(&tsk->publications,
3966                                              struct publication, binding_sock);
3967                 i += scnprintf(buf + i, sz - i, " %u", (p) ? p->type : 0);
3968                 i += scnprintf(buf + i, sz - i, " %u", (p) ? p->lower : 0);
3969                 i += scnprintf(buf + i, sz - i, " %u", (p) ? p->upper : 0);
3970         }
3971         i += scnprintf(buf + i, sz - i, " | %u", tsk->snd_win);
3972         i += scnprintf(buf + i, sz - i, " %u", tsk->rcv_win);
3973         i += scnprintf(buf + i, sz - i, " %u", tsk->max_pkt);
3974         i += scnprintf(buf + i, sz - i, " %x", tsk->peer_caps);
3975         i += scnprintf(buf + i, sz - i, " %u", tsk->cong_link_cnt);
3976         i += scnprintf(buf + i, sz - i, " %u", tsk->snt_unacked);
3977         i += scnprintf(buf + i, sz - i, " %u", tsk->rcv_unacked);
3978         i += scnprintf(buf + i, sz - i, " %u", atomic_read(&tsk->dupl_rcvcnt));
3979         i += scnprintf(buf + i, sz - i, " %u", sk->sk_shutdown);
3980         i += scnprintf(buf + i, sz - i, " | %d", sk_wmem_alloc_get(sk));
3981         i += scnprintf(buf + i, sz - i, " %d", sk->sk_sndbuf);
3982         i += scnprintf(buf + i, sz - i, " | %d", sk_rmem_alloc_get(sk));
3983         i += scnprintf(buf + i, sz - i, " %d", sk->sk_rcvbuf);
3984         i += scnprintf(buf + i, sz - i, " | %d\n", READ_ONCE(sk->sk_backlog.len));
3985
3986         if (dqueues & TIPC_DUMP_SK_SNDQ) {
3987                 i += scnprintf(buf + i, sz - i, "sk_write_queue: ");
3988                 i += tipc_list_dump(&sk->sk_write_queue, false, buf + i);
3989         }
3990
3991         if (dqueues & TIPC_DUMP_SK_RCVQ) {
3992                 i += scnprintf(buf + i, sz - i, "sk_receive_queue: ");
3993                 i += tipc_list_dump(&sk->sk_receive_queue, false, buf + i);
3994         }
3995
3996         if (dqueues & TIPC_DUMP_SK_BKLGQ) {
3997                 i += scnprintf(buf + i, sz - i, "sk_backlog:\n  head ");
3998                 i += tipc_skb_dump(sk->sk_backlog.head, false, buf + i);
3999                 if (sk->sk_backlog.tail != sk->sk_backlog.head) {
4000                         i += scnprintf(buf + i, sz - i, "  tail ");
4001                         i += tipc_skb_dump(sk->sk_backlog.tail, false,
4002                                            buf + i);
4003                 }
4004         }
4005
4006         return i;
4007 }