xref: /openbmc/linux/net/tipc/socket.c (revision a16be368)
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_FWD_MSG		1
56 #define TIPC_MAX_PORT		0xffffffff
57 #define TIPC_MIN_PORT		1
58 #define TIPC_ACK_RATE		4       /* ACK at 1/4 of of rcv window size */
59 
60 enum {
61 	TIPC_LISTEN = TCP_LISTEN,
62 	TIPC_ESTABLISHED = TCP_ESTABLISHED,
63 	TIPC_OPEN = TCP_CLOSE,
64 	TIPC_DISCONNECTING = TCP_CLOSE_WAIT,
65 	TIPC_CONNECTING = TCP_SYN_SENT,
66 };
67 
68 struct sockaddr_pair {
69 	struct sockaddr_tipc sock;
70 	struct sockaddr_tipc member;
71 };
72 
73 /**
74  * struct tipc_sock - TIPC socket structure
75  * @sk: socket - interacts with 'port' and with user via the socket API
76  * @conn_type: TIPC type used when connection was established
77  * @conn_instance: TIPC instance used when connection was established
78  * @published: non-zero if port has one or more associated names
79  * @max_pkt: maximum packet size "hint" used when building messages sent by port
80  * @maxnagle: maximum size of msg which can be subject to nagle
81  * @portid: unique port identity in TIPC socket hash table
82  * @phdr: preformatted message header used when sending messages
83  * #cong_links: list of congested links
84  * @publications: list of publications for port
85  * @blocking_link: address of the congested link we are currently sleeping on
86  * @pub_count: total # of publications port has made during its lifetime
87  * @conn_timeout: the time we can wait for an unresponded setup request
88  * @dupl_rcvcnt: number of bytes counted twice, in both backlog and rcv queue
89  * @cong_link_cnt: number of congested links
90  * @snt_unacked: # messages sent by socket, and not yet acked by peer
91  * @rcv_unacked: # messages read by user, but not yet acked back to peer
92  * @peer: 'connected' peer for dgram/rdm
93  * @node: hash table node
94  * @mc_method: cookie for use between socket and broadcast layer
95  * @rcu: rcu struct for tipc_sock
96  */
97 struct tipc_sock {
98 	struct sock sk;
99 	u32 conn_type;
100 	u32 conn_instance;
101 	int published;
102 	u32 max_pkt;
103 	u32 maxnagle;
104 	u32 portid;
105 	struct tipc_msg phdr;
106 	struct list_head cong_links;
107 	struct list_head publications;
108 	u32 pub_count;
109 	atomic_t dupl_rcvcnt;
110 	u16 conn_timeout;
111 	bool probe_unacked;
112 	u16 cong_link_cnt;
113 	u16 snt_unacked;
114 	u16 snd_win;
115 	u16 peer_caps;
116 	u16 rcv_unacked;
117 	u16 rcv_win;
118 	struct sockaddr_tipc peer;
119 	struct rhash_head node;
120 	struct tipc_mc_method mc_method;
121 	struct rcu_head rcu;
122 	struct tipc_group *group;
123 	u32 oneway;
124 	u32 nagle_start;
125 	u16 snd_backlog;
126 	u16 msg_acc;
127 	u16 pkt_cnt;
128 	bool expect_ack;
129 	bool nodelay;
130 	bool group_is_open;
131 };
132 
133 static int tipc_sk_backlog_rcv(struct sock *sk, struct sk_buff *skb);
134 static void tipc_data_ready(struct sock *sk);
135 static void tipc_write_space(struct sock *sk);
136 static void tipc_sock_destruct(struct sock *sk);
137 static int tipc_release(struct socket *sock);
138 static int tipc_accept(struct socket *sock, struct socket *new_sock, int flags,
139 		       bool kern);
140 static void tipc_sk_timeout(struct timer_list *t);
141 static int tipc_sk_publish(struct tipc_sock *tsk, uint scope,
142 			   struct tipc_name_seq const *seq);
143 static int tipc_sk_withdraw(struct tipc_sock *tsk, uint scope,
144 			    struct tipc_name_seq const *seq);
145 static int tipc_sk_leave(struct tipc_sock *tsk);
146 static struct tipc_sock *tipc_sk_lookup(struct net *net, u32 portid);
147 static int tipc_sk_insert(struct tipc_sock *tsk);
148 static void tipc_sk_remove(struct tipc_sock *tsk);
149 static int __tipc_sendstream(struct socket *sock, struct msghdr *m, size_t dsz);
150 static int __tipc_sendmsg(struct socket *sock, struct msghdr *m, size_t dsz);
151 static void tipc_sk_push_backlog(struct tipc_sock *tsk, bool nagle_ack);
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 		pr_warn("Socket create failed; port number exhausted\n");
493 		return -EINVAL;
494 	}
495 
496 	/* Ensure tsk is visible before we read own_addr. */
497 	smp_mb();
498 
499 	tipc_msg_init(tipc_own_addr(net), msg, TIPC_LOW_IMPORTANCE,
500 		      TIPC_NAMED_MSG, NAMED_H_SIZE, 0);
501 
502 	msg_set_origport(msg, tsk->portid);
503 	timer_setup(&sk->sk_timer, tipc_sk_timeout, 0);
504 	sk->sk_shutdown = 0;
505 	sk->sk_backlog_rcv = tipc_sk_backlog_rcv;
506 	sk->sk_rcvbuf = sysctl_tipc_rmem[1];
507 	sk->sk_data_ready = tipc_data_ready;
508 	sk->sk_write_space = tipc_write_space;
509 	sk->sk_destruct = tipc_sock_destruct;
510 	tsk->conn_timeout = CONN_TIMEOUT_DEFAULT;
511 	tsk->group_is_open = true;
512 	atomic_set(&tsk->dupl_rcvcnt, 0);
513 
514 	/* Start out with safe limits until we receive an advertised window */
515 	tsk->snd_win = tsk_adv_blocks(RCVBUF_MIN);
516 	tsk->rcv_win = tsk->snd_win;
517 
518 	if (tipc_sk_type_connectionless(sk)) {
519 		tsk_set_unreturnable(tsk, true);
520 		if (sock->type == SOCK_DGRAM)
521 			tsk_set_unreliable(tsk, true);
522 	}
523 	__skb_queue_head_init(&tsk->mc_method.deferredq);
524 	trace_tipc_sk_create(sk, NULL, TIPC_DUMP_NONE, " ");
525 	return 0;
526 }
527 
528 static void tipc_sk_callback(struct rcu_head *head)
529 {
530 	struct tipc_sock *tsk = container_of(head, struct tipc_sock, rcu);
531 
532 	sock_put(&tsk->sk);
533 }
534 
535 /* Caller should hold socket lock for the socket. */
536 static void __tipc_shutdown(struct socket *sock, int error)
537 {
538 	struct sock *sk = sock->sk;
539 	struct tipc_sock *tsk = tipc_sk(sk);
540 	struct net *net = sock_net(sk);
541 	long timeout = msecs_to_jiffies(CONN_TIMEOUT_DEFAULT);
542 	u32 dnode = tsk_peer_node(tsk);
543 	struct sk_buff *skb;
544 
545 	/* Avoid that hi-prio shutdown msgs bypass msgs in link wakeup queue */
546 	tipc_wait_for_cond(sock, &timeout, (!tsk->cong_link_cnt &&
547 					    !tsk_conn_cong(tsk)));
548 
549 	/* Push out delayed messages if in Nagle mode */
550 	tipc_sk_push_backlog(tsk, false);
551 	/* Remove pending SYN */
552 	__skb_queue_purge(&sk->sk_write_queue);
553 
554 	/* Remove partially received buffer if any */
555 	skb = skb_peek(&sk->sk_receive_queue);
556 	if (skb && TIPC_SKB_CB(skb)->bytes_read) {
557 		__skb_unlink(skb, &sk->sk_receive_queue);
558 		kfree_skb(skb);
559 	}
560 
561 	/* Reject all unreceived messages if connectionless */
562 	if (tipc_sk_type_connectionless(sk)) {
563 		tsk_rej_rx_queue(sk, error);
564 		return;
565 	}
566 
567 	switch (sk->sk_state) {
568 	case TIPC_CONNECTING:
569 	case TIPC_ESTABLISHED:
570 		tipc_set_sk_state(sk, TIPC_DISCONNECTING);
571 		tipc_node_remove_conn(net, dnode, tsk->portid);
572 		/* Send a FIN+/- to its peer */
573 		skb = __skb_dequeue(&sk->sk_receive_queue);
574 		if (skb) {
575 			__skb_queue_purge(&sk->sk_receive_queue);
576 			tipc_sk_respond(sk, skb, error);
577 			break;
578 		}
579 		skb = tipc_msg_create(TIPC_CRITICAL_IMPORTANCE,
580 				      TIPC_CONN_MSG, SHORT_H_SIZE, 0, dnode,
581 				      tsk_own_node(tsk), tsk_peer_port(tsk),
582 				      tsk->portid, error);
583 		if (skb)
584 			tipc_node_xmit_skb(net, skb, dnode, tsk->portid);
585 		break;
586 	case TIPC_LISTEN:
587 		/* Reject all SYN messages */
588 		tsk_rej_rx_queue(sk, error);
589 		break;
590 	default:
591 		__skb_queue_purge(&sk->sk_receive_queue);
592 		break;
593 	}
594 }
595 
596 /**
597  * tipc_release - destroy a TIPC socket
598  * @sock: socket to destroy
599  *
600  * This routine cleans up any messages that are still queued on the socket.
601  * For DGRAM and RDM socket types, all queued messages are rejected.
602  * For SEQPACKET and STREAM socket types, the first message is rejected
603  * and any others are discarded.  (If the first message on a STREAM socket
604  * is partially-read, it is discarded and the next one is rejected instead.)
605  *
606  * NOTE: Rejected messages are not necessarily returned to the sender!  They
607  * are returned or discarded according to the "destination droppable" setting
608  * specified for the message by the sender.
609  *
610  * Returns 0 on success, errno otherwise
611  */
612 static int tipc_release(struct socket *sock)
613 {
614 	struct sock *sk = sock->sk;
615 	struct tipc_sock *tsk;
616 
617 	/*
618 	 * Exit if socket isn't fully initialized (occurs when a failed accept()
619 	 * releases a pre-allocated child socket that was never used)
620 	 */
621 	if (sk == NULL)
622 		return 0;
623 
624 	tsk = tipc_sk(sk);
625 	lock_sock(sk);
626 
627 	trace_tipc_sk_release(sk, NULL, TIPC_DUMP_ALL, " ");
628 	__tipc_shutdown(sock, TIPC_ERR_NO_PORT);
629 	sk->sk_shutdown = SHUTDOWN_MASK;
630 	tipc_sk_leave(tsk);
631 	tipc_sk_withdraw(tsk, 0, NULL);
632 	__skb_queue_purge(&tsk->mc_method.deferredq);
633 	sk_stop_timer(sk, &sk->sk_timer);
634 	tipc_sk_remove(tsk);
635 
636 	sock_orphan(sk);
637 	/* Reject any messages that accumulated in backlog queue */
638 	release_sock(sk);
639 	tipc_dest_list_purge(&tsk->cong_links);
640 	tsk->cong_link_cnt = 0;
641 	call_rcu(&tsk->rcu, tipc_sk_callback);
642 	sock->sk = NULL;
643 
644 	return 0;
645 }
646 
647 /**
648  * tipc_bind - associate or disassocate TIPC name(s) with a socket
649  * @sock: socket structure
650  * @uaddr: socket address describing name(s) and desired operation
651  * @uaddr_len: size of socket address data structure
652  *
653  * Name and name sequence binding is indicated using a positive scope value;
654  * a negative scope value unbinds the specified name.  Specifying no name
655  * (i.e. a socket address length of 0) unbinds all names from the socket.
656  *
657  * Returns 0 on success, errno otherwise
658  *
659  * NOTE: This routine doesn't need to take the socket lock since it doesn't
660  *       access any non-constant socket information.
661  */
662 static int tipc_bind(struct socket *sock, struct sockaddr *uaddr,
663 		     int uaddr_len)
664 {
665 	struct sock *sk = sock->sk;
666 	struct sockaddr_tipc *addr = (struct sockaddr_tipc *)uaddr;
667 	struct tipc_sock *tsk = tipc_sk(sk);
668 	int res = -EINVAL;
669 
670 	lock_sock(sk);
671 	if (unlikely(!uaddr_len)) {
672 		res = tipc_sk_withdraw(tsk, 0, NULL);
673 		goto exit;
674 	}
675 	if (tsk->group) {
676 		res = -EACCES;
677 		goto exit;
678 	}
679 	if (uaddr_len < sizeof(struct sockaddr_tipc)) {
680 		res = -EINVAL;
681 		goto exit;
682 	}
683 	if (addr->family != AF_TIPC) {
684 		res = -EAFNOSUPPORT;
685 		goto exit;
686 	}
687 
688 	if (addr->addrtype == TIPC_ADDR_NAME)
689 		addr->addr.nameseq.upper = addr->addr.nameseq.lower;
690 	else if (addr->addrtype != TIPC_ADDR_NAMESEQ) {
691 		res = -EAFNOSUPPORT;
692 		goto exit;
693 	}
694 
695 	if ((addr->addr.nameseq.type < TIPC_RESERVED_TYPES) &&
696 	    (addr->addr.nameseq.type != TIPC_TOP_SRV) &&
697 	    (addr->addr.nameseq.type != TIPC_CFG_SRV)) {
698 		res = -EACCES;
699 		goto exit;
700 	}
701 
702 	res = (addr->scope >= 0) ?
703 		tipc_sk_publish(tsk, addr->scope, &addr->addr.nameseq) :
704 		tipc_sk_withdraw(tsk, -addr->scope, &addr->addr.nameseq);
705 exit:
706 	release_sock(sk);
707 	return res;
708 }
709 
710 /**
711  * tipc_getname - get port ID of socket or peer socket
712  * @sock: socket structure
713  * @uaddr: area for returned socket address
714  * @uaddr_len: area for returned length of 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 		/* fall through */
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  * @sk: 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 			kfree_skb(__skb_dequeue(arrvq));
1250 		}
1251 		spin_unlock_bh(&inputq->lock);
1252 		__skb_queue_purge(&tmpq);
1253 		kfree_skb(skb);
1254 	}
1255 	tipc_sk_rcv(net, inputq);
1256 }
1257 
1258 /* tipc_sk_push_backlog(): send accumulated buffers in socket write queue
1259  *                         when socket is in Nagle mode
1260  */
1261 static void tipc_sk_push_backlog(struct tipc_sock *tsk, bool nagle_ack)
1262 {
1263 	struct sk_buff_head *txq = &tsk->sk.sk_write_queue;
1264 	struct sk_buff *skb = skb_peek_tail(txq);
1265 	struct net *net = sock_net(&tsk->sk);
1266 	u32 dnode = tsk_peer_node(tsk);
1267 	int rc;
1268 
1269 	if (nagle_ack) {
1270 		tsk->pkt_cnt += skb_queue_len(txq);
1271 		if (!tsk->pkt_cnt || tsk->msg_acc / tsk->pkt_cnt < 2) {
1272 			tsk->oneway = 0;
1273 			if (tsk->nagle_start < NAGLE_START_MAX)
1274 				tsk->nagle_start *= 2;
1275 			tsk->expect_ack = false;
1276 			pr_debug("tsk %10u: bad nagle %u -> %u, next start %u!\n",
1277 				 tsk->portid, tsk->msg_acc, tsk->pkt_cnt,
1278 				 tsk->nagle_start);
1279 		} else {
1280 			tsk->nagle_start = NAGLE_START_INIT;
1281 			if (skb) {
1282 				msg_set_ack_required(buf_msg(skb));
1283 				tsk->expect_ack = true;
1284 			} else {
1285 				tsk->expect_ack = false;
1286 			}
1287 		}
1288 		tsk->msg_acc = 0;
1289 		tsk->pkt_cnt = 0;
1290 	}
1291 
1292 	if (!skb || tsk->cong_link_cnt)
1293 		return;
1294 
1295 	/* Do not send SYN again after congestion */
1296 	if (msg_is_syn(buf_msg(skb)))
1297 		return;
1298 
1299 	if (tsk->msg_acc)
1300 		tsk->pkt_cnt += skb_queue_len(txq);
1301 	tsk->snt_unacked += tsk->snd_backlog;
1302 	tsk->snd_backlog = 0;
1303 	rc = tipc_node_xmit(net, txq, dnode, tsk->portid);
1304 	if (rc == -ELINKCONG)
1305 		tsk->cong_link_cnt = 1;
1306 }
1307 
1308 /**
1309  * tipc_sk_conn_proto_rcv - receive a connection mng protocol message
1310  * @tsk: receiving socket
1311  * @skb: pointer to message buffer.
1312  */
1313 static void tipc_sk_conn_proto_rcv(struct tipc_sock *tsk, struct sk_buff *skb,
1314 				   struct sk_buff_head *inputq,
1315 				   struct sk_buff_head *xmitq)
1316 {
1317 	struct tipc_msg *hdr = buf_msg(skb);
1318 	u32 onode = tsk_own_node(tsk);
1319 	struct sock *sk = &tsk->sk;
1320 	int mtyp = msg_type(hdr);
1321 	bool was_cong;
1322 
1323 	/* Ignore if connection cannot be validated: */
1324 	if (!tsk_peer_msg(tsk, hdr)) {
1325 		trace_tipc_sk_drop_msg(sk, skb, TIPC_DUMP_NONE, "@proto_rcv!");
1326 		goto exit;
1327 	}
1328 
1329 	if (unlikely(msg_errcode(hdr))) {
1330 		tipc_set_sk_state(sk, TIPC_DISCONNECTING);
1331 		tipc_node_remove_conn(sock_net(sk), tsk_peer_node(tsk),
1332 				      tsk_peer_port(tsk));
1333 		sk->sk_state_change(sk);
1334 
1335 		/* State change is ignored if socket already awake,
1336 		 * - convert msg to abort msg and add to inqueue
1337 		 */
1338 		msg_set_user(hdr, TIPC_CRITICAL_IMPORTANCE);
1339 		msg_set_type(hdr, TIPC_CONN_MSG);
1340 		msg_set_size(hdr, BASIC_H_SIZE);
1341 		msg_set_hdr_sz(hdr, BASIC_H_SIZE);
1342 		__skb_queue_tail(inputq, skb);
1343 		return;
1344 	}
1345 
1346 	tsk->probe_unacked = false;
1347 
1348 	if (mtyp == CONN_PROBE) {
1349 		msg_set_type(hdr, CONN_PROBE_REPLY);
1350 		if (tipc_msg_reverse(onode, &skb, TIPC_OK))
1351 			__skb_queue_tail(xmitq, skb);
1352 		return;
1353 	} else if (mtyp == CONN_ACK) {
1354 		was_cong = tsk_conn_cong(tsk);
1355 		tipc_sk_push_backlog(tsk, msg_nagle_ack(hdr));
1356 		tsk->snt_unacked -= msg_conn_ack(hdr);
1357 		if (tsk->peer_caps & TIPC_BLOCK_FLOWCTL)
1358 			tsk->snd_win = msg_adv_win(hdr);
1359 		if (was_cong && !tsk_conn_cong(tsk))
1360 			sk->sk_write_space(sk);
1361 	} else if (mtyp != CONN_PROBE_REPLY) {
1362 		pr_warn("Received unknown CONN_PROTO msg\n");
1363 	}
1364 exit:
1365 	kfree_skb(skb);
1366 }
1367 
1368 /**
1369  * tipc_sendmsg - send message in connectionless manner
1370  * @sock: socket structure
1371  * @m: message to send
1372  * @dsz: amount of user data to be sent
1373  *
1374  * Message must have an destination specified explicitly.
1375  * Used for SOCK_RDM and SOCK_DGRAM messages,
1376  * and for 'SYN' messages on SOCK_SEQPACKET and SOCK_STREAM connections.
1377  * (Note: 'SYN+' is prohibited on SOCK_STREAM.)
1378  *
1379  * Returns the number of bytes sent on success, or errno otherwise
1380  */
1381 static int tipc_sendmsg(struct socket *sock,
1382 			struct msghdr *m, size_t dsz)
1383 {
1384 	struct sock *sk = sock->sk;
1385 	int ret;
1386 
1387 	lock_sock(sk);
1388 	ret = __tipc_sendmsg(sock, m, dsz);
1389 	release_sock(sk);
1390 
1391 	return ret;
1392 }
1393 
1394 static int __tipc_sendmsg(struct socket *sock, struct msghdr *m, size_t dlen)
1395 {
1396 	struct sock *sk = sock->sk;
1397 	struct net *net = sock_net(sk);
1398 	struct tipc_sock *tsk = tipc_sk(sk);
1399 	DECLARE_SOCKADDR(struct sockaddr_tipc *, dest, m->msg_name);
1400 	long timeout = sock_sndtimeo(sk, m->msg_flags & MSG_DONTWAIT);
1401 	struct list_head *clinks = &tsk->cong_links;
1402 	bool syn = !tipc_sk_type_connectionless(sk);
1403 	struct tipc_group *grp = tsk->group;
1404 	struct tipc_msg *hdr = &tsk->phdr;
1405 	struct tipc_name_seq *seq;
1406 	struct sk_buff_head pkts;
1407 	u32 dport = 0, dnode = 0;
1408 	u32 type = 0, inst = 0;
1409 	int mtu, rc;
1410 
1411 	if (unlikely(dlen > TIPC_MAX_USER_MSG_SIZE))
1412 		return -EMSGSIZE;
1413 
1414 	if (likely(dest)) {
1415 		if (unlikely(m->msg_namelen < sizeof(*dest)))
1416 			return -EINVAL;
1417 		if (unlikely(dest->family != AF_TIPC))
1418 			return -EINVAL;
1419 	}
1420 
1421 	if (grp) {
1422 		if (!dest)
1423 			return tipc_send_group_bcast(sock, m, dlen, timeout);
1424 		if (dest->addrtype == TIPC_ADDR_NAME)
1425 			return tipc_send_group_anycast(sock, m, dlen, timeout);
1426 		if (dest->addrtype == TIPC_ADDR_ID)
1427 			return tipc_send_group_unicast(sock, m, dlen, timeout);
1428 		if (dest->addrtype == TIPC_ADDR_MCAST)
1429 			return tipc_send_group_mcast(sock, m, dlen, timeout);
1430 		return -EINVAL;
1431 	}
1432 
1433 	if (unlikely(!dest)) {
1434 		dest = &tsk->peer;
1435 		if (!syn && dest->family != AF_TIPC)
1436 			return -EDESTADDRREQ;
1437 	}
1438 
1439 	if (unlikely(syn)) {
1440 		if (sk->sk_state == TIPC_LISTEN)
1441 			return -EPIPE;
1442 		if (sk->sk_state != TIPC_OPEN)
1443 			return -EISCONN;
1444 		if (tsk->published)
1445 			return -EOPNOTSUPP;
1446 		if (dest->addrtype == TIPC_ADDR_NAME) {
1447 			tsk->conn_type = dest->addr.name.name.type;
1448 			tsk->conn_instance = dest->addr.name.name.instance;
1449 		}
1450 		msg_set_syn(hdr, 1);
1451 	}
1452 
1453 	seq = &dest->addr.nameseq;
1454 	if (dest->addrtype == TIPC_ADDR_MCAST)
1455 		return tipc_sendmcast(sock, seq, m, dlen, timeout);
1456 
1457 	if (dest->addrtype == TIPC_ADDR_NAME) {
1458 		type = dest->addr.name.name.type;
1459 		inst = dest->addr.name.name.instance;
1460 		dnode = dest->addr.name.domain;
1461 		dport = tipc_nametbl_translate(net, type, inst, &dnode);
1462 		if (unlikely(!dport && !dnode))
1463 			return -EHOSTUNREACH;
1464 	} else if (dest->addrtype == TIPC_ADDR_ID) {
1465 		dnode = dest->addr.id.node;
1466 	} else {
1467 		return -EINVAL;
1468 	}
1469 
1470 	/* Block or return if destination link is congested */
1471 	rc = tipc_wait_for_cond(sock, &timeout,
1472 				!tipc_dest_find(clinks, dnode, 0));
1473 	if (unlikely(rc))
1474 		return rc;
1475 
1476 	if (dest->addrtype == TIPC_ADDR_NAME) {
1477 		msg_set_type(hdr, TIPC_NAMED_MSG);
1478 		msg_set_hdr_sz(hdr, NAMED_H_SIZE);
1479 		msg_set_nametype(hdr, type);
1480 		msg_set_nameinst(hdr, inst);
1481 		msg_set_lookup_scope(hdr, tipc_node2scope(dnode));
1482 		msg_set_destnode(hdr, dnode);
1483 		msg_set_destport(hdr, dport);
1484 	} else { /* TIPC_ADDR_ID */
1485 		msg_set_type(hdr, TIPC_DIRECT_MSG);
1486 		msg_set_lookup_scope(hdr, 0);
1487 		msg_set_destnode(hdr, dnode);
1488 		msg_set_destport(hdr, dest->addr.id.ref);
1489 		msg_set_hdr_sz(hdr, BASIC_H_SIZE);
1490 	}
1491 
1492 	__skb_queue_head_init(&pkts);
1493 	mtu = tipc_node_get_mtu(net, dnode, tsk->portid, true);
1494 	rc = tipc_msg_build(hdr, m, 0, dlen, mtu, &pkts);
1495 	if (unlikely(rc != dlen))
1496 		return rc;
1497 	if (unlikely(syn && !tipc_msg_skb_clone(&pkts, &sk->sk_write_queue))) {
1498 		__skb_queue_purge(&pkts);
1499 		return -ENOMEM;
1500 	}
1501 
1502 	trace_tipc_sk_sendmsg(sk, skb_peek(&pkts), TIPC_DUMP_SK_SNDQ, " ");
1503 	rc = tipc_node_xmit(net, &pkts, dnode, tsk->portid);
1504 	if (unlikely(rc == -ELINKCONG)) {
1505 		tipc_dest_push(clinks, dnode, 0);
1506 		tsk->cong_link_cnt++;
1507 		rc = 0;
1508 	}
1509 
1510 	if (unlikely(syn && !rc))
1511 		tipc_set_sk_state(sk, TIPC_CONNECTING);
1512 
1513 	return rc ? rc : dlen;
1514 }
1515 
1516 /**
1517  * tipc_sendstream - send stream-oriented data
1518  * @sock: socket structure
1519  * @m: data to send
1520  * @dsz: total length of data to be transmitted
1521  *
1522  * Used for SOCK_STREAM data.
1523  *
1524  * Returns the number of bytes sent on success (or partial success),
1525  * or errno if no data sent
1526  */
1527 static int tipc_sendstream(struct socket *sock, struct msghdr *m, size_t dsz)
1528 {
1529 	struct sock *sk = sock->sk;
1530 	int ret;
1531 
1532 	lock_sock(sk);
1533 	ret = __tipc_sendstream(sock, m, dsz);
1534 	release_sock(sk);
1535 
1536 	return ret;
1537 }
1538 
1539 static int __tipc_sendstream(struct socket *sock, struct msghdr *m, size_t dlen)
1540 {
1541 	struct sock *sk = sock->sk;
1542 	DECLARE_SOCKADDR(struct sockaddr_tipc *, dest, m->msg_name);
1543 	long timeout = sock_sndtimeo(sk, m->msg_flags & MSG_DONTWAIT);
1544 	struct sk_buff_head *txq = &sk->sk_write_queue;
1545 	struct tipc_sock *tsk = tipc_sk(sk);
1546 	struct tipc_msg *hdr = &tsk->phdr;
1547 	struct net *net = sock_net(sk);
1548 	struct sk_buff *skb;
1549 	u32 dnode = tsk_peer_node(tsk);
1550 	int maxnagle = tsk->maxnagle;
1551 	int maxpkt = tsk->max_pkt;
1552 	int send, sent = 0;
1553 	int blocks, rc = 0;
1554 
1555 	if (unlikely(dlen > INT_MAX))
1556 		return -EMSGSIZE;
1557 
1558 	/* Handle implicit connection setup */
1559 	if (unlikely(dest)) {
1560 		rc = __tipc_sendmsg(sock, m, dlen);
1561 		if (dlen && dlen == rc) {
1562 			tsk->peer_caps = tipc_node_get_capabilities(net, dnode);
1563 			tsk->snt_unacked = tsk_inc(tsk, dlen + msg_hdr_sz(hdr));
1564 		}
1565 		return rc;
1566 	}
1567 
1568 	do {
1569 		rc = tipc_wait_for_cond(sock, &timeout,
1570 					(!tsk->cong_link_cnt &&
1571 					 !tsk_conn_cong(tsk) &&
1572 					 tipc_sk_connected(sk)));
1573 		if (unlikely(rc))
1574 			break;
1575 		send = min_t(size_t, dlen - sent, TIPC_MAX_USER_MSG_SIZE);
1576 		blocks = tsk->snd_backlog;
1577 		if (tsk->oneway++ >= tsk->nagle_start && send <= maxnagle) {
1578 			rc = tipc_msg_append(hdr, m, send, maxnagle, txq);
1579 			if (unlikely(rc < 0))
1580 				break;
1581 			blocks += rc;
1582 			tsk->msg_acc++;
1583 			if (blocks <= 64 && tsk->expect_ack) {
1584 				tsk->snd_backlog = blocks;
1585 				sent += send;
1586 				break;
1587 			} else if (blocks > 64) {
1588 				tsk->pkt_cnt += skb_queue_len(txq);
1589 			} else {
1590 				skb = skb_peek_tail(txq);
1591 				if (skb) {
1592 					msg_set_ack_required(buf_msg(skb));
1593 					tsk->expect_ack = true;
1594 				} else {
1595 					tsk->expect_ack = false;
1596 				}
1597 				tsk->msg_acc = 0;
1598 				tsk->pkt_cnt = 0;
1599 			}
1600 		} else {
1601 			rc = tipc_msg_build(hdr, m, sent, send, maxpkt, txq);
1602 			if (unlikely(rc != send))
1603 				break;
1604 			blocks += tsk_inc(tsk, send + MIN_H_SIZE);
1605 		}
1606 		trace_tipc_sk_sendstream(sk, skb_peek(txq),
1607 					 TIPC_DUMP_SK_SNDQ, " ");
1608 		rc = tipc_node_xmit(net, txq, dnode, tsk->portid);
1609 		if (unlikely(rc == -ELINKCONG)) {
1610 			tsk->cong_link_cnt = 1;
1611 			rc = 0;
1612 		}
1613 		if (likely(!rc)) {
1614 			tsk->snt_unacked += blocks;
1615 			tsk->snd_backlog = 0;
1616 			sent += send;
1617 		}
1618 	} while (sent < dlen && !rc);
1619 
1620 	return sent ? sent : rc;
1621 }
1622 
1623 /**
1624  * tipc_send_packet - send a connection-oriented message
1625  * @sock: socket structure
1626  * @m: message to send
1627  * @dsz: length of data to be transmitted
1628  *
1629  * Used for SOCK_SEQPACKET messages.
1630  *
1631  * Returns the number of bytes sent on success, or errno otherwise
1632  */
1633 static int tipc_send_packet(struct socket *sock, struct msghdr *m, size_t dsz)
1634 {
1635 	if (dsz > TIPC_MAX_USER_MSG_SIZE)
1636 		return -EMSGSIZE;
1637 
1638 	return tipc_sendstream(sock, m, dsz);
1639 }
1640 
1641 /* tipc_sk_finish_conn - complete the setup of a connection
1642  */
1643 static void tipc_sk_finish_conn(struct tipc_sock *tsk, u32 peer_port,
1644 				u32 peer_node)
1645 {
1646 	struct sock *sk = &tsk->sk;
1647 	struct net *net = sock_net(sk);
1648 	struct tipc_msg *msg = &tsk->phdr;
1649 
1650 	msg_set_syn(msg, 0);
1651 	msg_set_destnode(msg, peer_node);
1652 	msg_set_destport(msg, peer_port);
1653 	msg_set_type(msg, TIPC_CONN_MSG);
1654 	msg_set_lookup_scope(msg, 0);
1655 	msg_set_hdr_sz(msg, SHORT_H_SIZE);
1656 
1657 	sk_reset_timer(sk, &sk->sk_timer, jiffies + CONN_PROBING_INTV);
1658 	tipc_set_sk_state(sk, TIPC_ESTABLISHED);
1659 	tipc_node_add_conn(net, peer_node, tsk->portid, peer_port);
1660 	tsk->max_pkt = tipc_node_get_mtu(net, peer_node, tsk->portid, true);
1661 	tsk->peer_caps = tipc_node_get_capabilities(net, peer_node);
1662 	tsk_set_nagle(tsk);
1663 	__skb_queue_purge(&sk->sk_write_queue);
1664 	if (tsk->peer_caps & TIPC_BLOCK_FLOWCTL)
1665 		return;
1666 
1667 	/* Fall back to message based flow control */
1668 	tsk->rcv_win = FLOWCTL_MSG_WIN;
1669 	tsk->snd_win = FLOWCTL_MSG_WIN;
1670 }
1671 
1672 /**
1673  * tipc_sk_set_orig_addr - capture sender's address for received message
1674  * @m: descriptor for message info
1675  * @hdr: received message header
1676  *
1677  * Note: Address is not captured if not requested by receiver.
1678  */
1679 static void tipc_sk_set_orig_addr(struct msghdr *m, struct sk_buff *skb)
1680 {
1681 	DECLARE_SOCKADDR(struct sockaddr_pair *, srcaddr, m->msg_name);
1682 	struct tipc_msg *hdr = buf_msg(skb);
1683 
1684 	if (!srcaddr)
1685 		return;
1686 
1687 	srcaddr->sock.family = AF_TIPC;
1688 	srcaddr->sock.addrtype = TIPC_ADDR_ID;
1689 	srcaddr->sock.scope = 0;
1690 	srcaddr->sock.addr.id.ref = msg_origport(hdr);
1691 	srcaddr->sock.addr.id.node = msg_orignode(hdr);
1692 	srcaddr->sock.addr.name.domain = 0;
1693 	m->msg_namelen = sizeof(struct sockaddr_tipc);
1694 
1695 	if (!msg_in_group(hdr))
1696 		return;
1697 
1698 	/* Group message users may also want to know sending member's id */
1699 	srcaddr->member.family = AF_TIPC;
1700 	srcaddr->member.addrtype = TIPC_ADDR_NAME;
1701 	srcaddr->member.scope = 0;
1702 	srcaddr->member.addr.name.name.type = msg_nametype(hdr);
1703 	srcaddr->member.addr.name.name.instance = TIPC_SKB_CB(skb)->orig_member;
1704 	srcaddr->member.addr.name.domain = 0;
1705 	m->msg_namelen = sizeof(*srcaddr);
1706 }
1707 
1708 /**
1709  * tipc_sk_anc_data_recv - optionally capture ancillary data for received message
1710  * @m: descriptor for message info
1711  * @skb: received message buffer
1712  * @tsk: TIPC port associated with message
1713  *
1714  * Note: Ancillary data is not captured if not requested by receiver.
1715  *
1716  * Returns 0 if successful, otherwise errno
1717  */
1718 static int tipc_sk_anc_data_recv(struct msghdr *m, struct sk_buff *skb,
1719 				 struct tipc_sock *tsk)
1720 {
1721 	struct tipc_msg *msg;
1722 	u32 anc_data[3];
1723 	u32 err;
1724 	u32 dest_type;
1725 	int has_name;
1726 	int res;
1727 
1728 	if (likely(m->msg_controllen == 0))
1729 		return 0;
1730 	msg = buf_msg(skb);
1731 
1732 	/* Optionally capture errored message object(s) */
1733 	err = msg ? msg_errcode(msg) : 0;
1734 	if (unlikely(err)) {
1735 		anc_data[0] = err;
1736 		anc_data[1] = msg_data_sz(msg);
1737 		res = put_cmsg(m, SOL_TIPC, TIPC_ERRINFO, 8, anc_data);
1738 		if (res)
1739 			return res;
1740 		if (anc_data[1]) {
1741 			if (skb_linearize(skb))
1742 				return -ENOMEM;
1743 			msg = buf_msg(skb);
1744 			res = put_cmsg(m, SOL_TIPC, TIPC_RETDATA, anc_data[1],
1745 				       msg_data(msg));
1746 			if (res)
1747 				return res;
1748 		}
1749 	}
1750 
1751 	/* Optionally capture message destination object */
1752 	dest_type = msg ? msg_type(msg) : TIPC_DIRECT_MSG;
1753 	switch (dest_type) {
1754 	case TIPC_NAMED_MSG:
1755 		has_name = 1;
1756 		anc_data[0] = msg_nametype(msg);
1757 		anc_data[1] = msg_namelower(msg);
1758 		anc_data[2] = msg_namelower(msg);
1759 		break;
1760 	case TIPC_MCAST_MSG:
1761 		has_name = 1;
1762 		anc_data[0] = msg_nametype(msg);
1763 		anc_data[1] = msg_namelower(msg);
1764 		anc_data[2] = msg_nameupper(msg);
1765 		break;
1766 	case TIPC_CONN_MSG:
1767 		has_name = (tsk->conn_type != 0);
1768 		anc_data[0] = tsk->conn_type;
1769 		anc_data[1] = tsk->conn_instance;
1770 		anc_data[2] = tsk->conn_instance;
1771 		break;
1772 	default:
1773 		has_name = 0;
1774 	}
1775 	if (has_name) {
1776 		res = put_cmsg(m, SOL_TIPC, TIPC_DESTNAME, 12, anc_data);
1777 		if (res)
1778 			return res;
1779 	}
1780 
1781 	return 0;
1782 }
1783 
1784 static struct sk_buff *tipc_sk_build_ack(struct tipc_sock *tsk)
1785 {
1786 	struct sock *sk = &tsk->sk;
1787 	struct sk_buff *skb = NULL;
1788 	struct tipc_msg *msg;
1789 	u32 peer_port = tsk_peer_port(tsk);
1790 	u32 dnode = tsk_peer_node(tsk);
1791 
1792 	if (!tipc_sk_connected(sk))
1793 		return NULL;
1794 	skb = tipc_msg_create(CONN_MANAGER, CONN_ACK, INT_H_SIZE, 0,
1795 			      dnode, tsk_own_node(tsk), peer_port,
1796 			      tsk->portid, TIPC_OK);
1797 	if (!skb)
1798 		return NULL;
1799 	msg = buf_msg(skb);
1800 	msg_set_conn_ack(msg, tsk->rcv_unacked);
1801 	tsk->rcv_unacked = 0;
1802 
1803 	/* Adjust to and advertize the correct window limit */
1804 	if (tsk->peer_caps & TIPC_BLOCK_FLOWCTL) {
1805 		tsk->rcv_win = tsk_adv_blocks(tsk->sk.sk_rcvbuf);
1806 		msg_set_adv_win(msg, tsk->rcv_win);
1807 	}
1808 	return skb;
1809 }
1810 
1811 static void tipc_sk_send_ack(struct tipc_sock *tsk)
1812 {
1813 	struct sk_buff *skb;
1814 
1815 	skb = tipc_sk_build_ack(tsk);
1816 	if (!skb)
1817 		return;
1818 
1819 	tipc_node_xmit_skb(sock_net(&tsk->sk), skb, tsk_peer_node(tsk),
1820 			   msg_link_selector(buf_msg(skb)));
1821 }
1822 
1823 static int tipc_wait_for_rcvmsg(struct socket *sock, long *timeop)
1824 {
1825 	struct sock *sk = sock->sk;
1826 	DEFINE_WAIT_FUNC(wait, woken_wake_function);
1827 	long timeo = *timeop;
1828 	int err = sock_error(sk);
1829 
1830 	if (err)
1831 		return err;
1832 
1833 	for (;;) {
1834 		if (timeo && skb_queue_empty(&sk->sk_receive_queue)) {
1835 			if (sk->sk_shutdown & RCV_SHUTDOWN) {
1836 				err = -ENOTCONN;
1837 				break;
1838 			}
1839 			add_wait_queue(sk_sleep(sk), &wait);
1840 			release_sock(sk);
1841 			timeo = wait_woken(&wait, TASK_INTERRUPTIBLE, timeo);
1842 			sched_annotate_sleep();
1843 			lock_sock(sk);
1844 			remove_wait_queue(sk_sleep(sk), &wait);
1845 		}
1846 		err = 0;
1847 		if (!skb_queue_empty(&sk->sk_receive_queue))
1848 			break;
1849 		err = -EAGAIN;
1850 		if (!timeo)
1851 			break;
1852 		err = sock_intr_errno(timeo);
1853 		if (signal_pending(current))
1854 			break;
1855 
1856 		err = sock_error(sk);
1857 		if (err)
1858 			break;
1859 	}
1860 	*timeop = timeo;
1861 	return err;
1862 }
1863 
1864 /**
1865  * tipc_recvmsg - receive packet-oriented message
1866  * @m: descriptor for message info
1867  * @buflen: length of user buffer area
1868  * @flags: receive flags
1869  *
1870  * Used for SOCK_DGRAM, SOCK_RDM, and SOCK_SEQPACKET messages.
1871  * If the complete message doesn't fit in user area, truncate it.
1872  *
1873  * Returns size of returned message data, errno otherwise
1874  */
1875 static int tipc_recvmsg(struct socket *sock, struct msghdr *m,
1876 			size_t buflen,	int flags)
1877 {
1878 	struct sock *sk = sock->sk;
1879 	bool connected = !tipc_sk_type_connectionless(sk);
1880 	struct tipc_sock *tsk = tipc_sk(sk);
1881 	int rc, err, hlen, dlen, copy;
1882 	struct sk_buff_head xmitq;
1883 	struct tipc_msg *hdr;
1884 	struct sk_buff *skb;
1885 	bool grp_evt;
1886 	long timeout;
1887 
1888 	/* Catch invalid receive requests */
1889 	if (unlikely(!buflen))
1890 		return -EINVAL;
1891 
1892 	lock_sock(sk);
1893 	if (unlikely(connected && sk->sk_state == TIPC_OPEN)) {
1894 		rc = -ENOTCONN;
1895 		goto exit;
1896 	}
1897 	timeout = sock_rcvtimeo(sk, flags & MSG_DONTWAIT);
1898 
1899 	/* Step rcv queue to first msg with data or error; wait if necessary */
1900 	do {
1901 		rc = tipc_wait_for_rcvmsg(sock, &timeout);
1902 		if (unlikely(rc))
1903 			goto exit;
1904 		skb = skb_peek(&sk->sk_receive_queue);
1905 		hdr = buf_msg(skb);
1906 		dlen = msg_data_sz(hdr);
1907 		hlen = msg_hdr_sz(hdr);
1908 		err = msg_errcode(hdr);
1909 		grp_evt = msg_is_grp_evt(hdr);
1910 		if (likely(dlen || err))
1911 			break;
1912 		tsk_advance_rx_queue(sk);
1913 	} while (1);
1914 
1915 	/* Collect msg meta data, including error code and rejected data */
1916 	tipc_sk_set_orig_addr(m, skb);
1917 	rc = tipc_sk_anc_data_recv(m, skb, tsk);
1918 	if (unlikely(rc))
1919 		goto exit;
1920 	hdr = buf_msg(skb);
1921 
1922 	/* Capture data if non-error msg, otherwise just set return value */
1923 	if (likely(!err)) {
1924 		copy = min_t(int, dlen, buflen);
1925 		if (unlikely(copy != dlen))
1926 			m->msg_flags |= MSG_TRUNC;
1927 		rc = skb_copy_datagram_msg(skb, hlen, m, copy);
1928 	} else {
1929 		copy = 0;
1930 		rc = 0;
1931 		if (err != TIPC_CONN_SHUTDOWN && connected && !m->msg_control)
1932 			rc = -ECONNRESET;
1933 	}
1934 	if (unlikely(rc))
1935 		goto exit;
1936 
1937 	/* Mark message as group event if applicable */
1938 	if (unlikely(grp_evt)) {
1939 		if (msg_grp_evt(hdr) == TIPC_WITHDRAWN)
1940 			m->msg_flags |= MSG_EOR;
1941 		m->msg_flags |= MSG_OOB;
1942 		copy = 0;
1943 	}
1944 
1945 	/* Caption of data or error code/rejected data was successful */
1946 	if (unlikely(flags & MSG_PEEK))
1947 		goto exit;
1948 
1949 	/* Send group flow control advertisement when applicable */
1950 	if (tsk->group && msg_in_group(hdr) && !grp_evt) {
1951 		__skb_queue_head_init(&xmitq);
1952 		tipc_group_update_rcv_win(tsk->group, tsk_blocks(hlen + dlen),
1953 					  msg_orignode(hdr), msg_origport(hdr),
1954 					  &xmitq);
1955 		tipc_node_distr_xmit(sock_net(sk), &xmitq);
1956 	}
1957 
1958 	tsk_advance_rx_queue(sk);
1959 
1960 	if (likely(!connected))
1961 		goto exit;
1962 
1963 	/* Send connection flow control advertisement when applicable */
1964 	tsk->rcv_unacked += tsk_inc(tsk, hlen + dlen);
1965 	if (tsk->rcv_unacked >= tsk->rcv_win / TIPC_ACK_RATE)
1966 		tipc_sk_send_ack(tsk);
1967 exit:
1968 	release_sock(sk);
1969 	return rc ? rc : copy;
1970 }
1971 
1972 /**
1973  * tipc_recvstream - receive stream-oriented data
1974  * @m: descriptor for message info
1975  * @buflen: total size of user buffer area
1976  * @flags: receive flags
1977  *
1978  * Used for SOCK_STREAM messages only.  If not enough data is available
1979  * will optionally wait for more; never truncates data.
1980  *
1981  * Returns size of returned message data, errno otherwise
1982  */
1983 static int tipc_recvstream(struct socket *sock, struct msghdr *m,
1984 			   size_t buflen, int flags)
1985 {
1986 	struct sock *sk = sock->sk;
1987 	struct tipc_sock *tsk = tipc_sk(sk);
1988 	struct sk_buff *skb;
1989 	struct tipc_msg *hdr;
1990 	struct tipc_skb_cb *skb_cb;
1991 	bool peek = flags & MSG_PEEK;
1992 	int offset, required, copy, copied = 0;
1993 	int hlen, dlen, err, rc;
1994 	long timeout;
1995 
1996 	/* Catch invalid receive attempts */
1997 	if (unlikely(!buflen))
1998 		return -EINVAL;
1999 
2000 	lock_sock(sk);
2001 
2002 	if (unlikely(sk->sk_state == TIPC_OPEN)) {
2003 		rc = -ENOTCONN;
2004 		goto exit;
2005 	}
2006 	required = sock_rcvlowat(sk, flags & MSG_WAITALL, buflen);
2007 	timeout = sock_rcvtimeo(sk, flags & MSG_DONTWAIT);
2008 
2009 	do {
2010 		/* Look at first msg in receive queue; wait if necessary */
2011 		rc = tipc_wait_for_rcvmsg(sock, &timeout);
2012 		if (unlikely(rc))
2013 			break;
2014 		skb = skb_peek(&sk->sk_receive_queue);
2015 		skb_cb = TIPC_SKB_CB(skb);
2016 		hdr = buf_msg(skb);
2017 		dlen = msg_data_sz(hdr);
2018 		hlen = msg_hdr_sz(hdr);
2019 		err = msg_errcode(hdr);
2020 
2021 		/* Discard any empty non-errored (SYN-) message */
2022 		if (unlikely(!dlen && !err)) {
2023 			tsk_advance_rx_queue(sk);
2024 			continue;
2025 		}
2026 
2027 		/* Collect msg meta data, incl. error code and rejected data */
2028 		if (!copied) {
2029 			tipc_sk_set_orig_addr(m, skb);
2030 			rc = tipc_sk_anc_data_recv(m, skb, tsk);
2031 			if (rc)
2032 				break;
2033 			hdr = buf_msg(skb);
2034 		}
2035 
2036 		/* Copy data if msg ok, otherwise return error/partial data */
2037 		if (likely(!err)) {
2038 			offset = skb_cb->bytes_read;
2039 			copy = min_t(int, dlen - offset, buflen - copied);
2040 			rc = skb_copy_datagram_msg(skb, hlen + offset, m, copy);
2041 			if (unlikely(rc))
2042 				break;
2043 			copied += copy;
2044 			offset += copy;
2045 			if (unlikely(offset < dlen)) {
2046 				if (!peek)
2047 					skb_cb->bytes_read = offset;
2048 				break;
2049 			}
2050 		} else {
2051 			rc = 0;
2052 			if ((err != TIPC_CONN_SHUTDOWN) && !m->msg_control)
2053 				rc = -ECONNRESET;
2054 			if (copied || rc)
2055 				break;
2056 		}
2057 
2058 		if (unlikely(peek))
2059 			break;
2060 
2061 		tsk_advance_rx_queue(sk);
2062 
2063 		/* Send connection flow control advertisement when applicable */
2064 		tsk->rcv_unacked += tsk_inc(tsk, hlen + dlen);
2065 		if (tsk->rcv_unacked >= tsk->rcv_win / TIPC_ACK_RATE)
2066 			tipc_sk_send_ack(tsk);
2067 
2068 		/* Exit if all requested data or FIN/error received */
2069 		if (copied == buflen || err)
2070 			break;
2071 
2072 	} while (!skb_queue_empty(&sk->sk_receive_queue) || copied < required);
2073 exit:
2074 	release_sock(sk);
2075 	return copied ? copied : rc;
2076 }
2077 
2078 /**
2079  * tipc_write_space - wake up thread if port congestion is released
2080  * @sk: socket
2081  */
2082 static void tipc_write_space(struct sock *sk)
2083 {
2084 	struct socket_wq *wq;
2085 
2086 	rcu_read_lock();
2087 	wq = rcu_dereference(sk->sk_wq);
2088 	if (skwq_has_sleeper(wq))
2089 		wake_up_interruptible_sync_poll(&wq->wait, EPOLLOUT |
2090 						EPOLLWRNORM | EPOLLWRBAND);
2091 	rcu_read_unlock();
2092 }
2093 
2094 /**
2095  * tipc_data_ready - wake up threads to indicate messages have been received
2096  * @sk: socket
2097  * @len: the length of messages
2098  */
2099 static void tipc_data_ready(struct sock *sk)
2100 {
2101 	struct socket_wq *wq;
2102 
2103 	rcu_read_lock();
2104 	wq = rcu_dereference(sk->sk_wq);
2105 	if (skwq_has_sleeper(wq))
2106 		wake_up_interruptible_sync_poll(&wq->wait, EPOLLIN |
2107 						EPOLLRDNORM | EPOLLRDBAND);
2108 	rcu_read_unlock();
2109 }
2110 
2111 static void tipc_sock_destruct(struct sock *sk)
2112 {
2113 	__skb_queue_purge(&sk->sk_receive_queue);
2114 }
2115 
2116 static void tipc_sk_proto_rcv(struct sock *sk,
2117 			      struct sk_buff_head *inputq,
2118 			      struct sk_buff_head *xmitq)
2119 {
2120 	struct sk_buff *skb = __skb_dequeue(inputq);
2121 	struct tipc_sock *tsk = tipc_sk(sk);
2122 	struct tipc_msg *hdr = buf_msg(skb);
2123 	struct tipc_group *grp = tsk->group;
2124 	bool wakeup = false;
2125 
2126 	switch (msg_user(hdr)) {
2127 	case CONN_MANAGER:
2128 		tipc_sk_conn_proto_rcv(tsk, skb, inputq, xmitq);
2129 		return;
2130 	case SOCK_WAKEUP:
2131 		tipc_dest_del(&tsk->cong_links, msg_orignode(hdr), 0);
2132 		/* coupled with smp_rmb() in tipc_wait_for_cond() */
2133 		smp_wmb();
2134 		tsk->cong_link_cnt--;
2135 		wakeup = true;
2136 		tipc_sk_push_backlog(tsk, false);
2137 		break;
2138 	case GROUP_PROTOCOL:
2139 		tipc_group_proto_rcv(grp, &wakeup, hdr, inputq, xmitq);
2140 		break;
2141 	case TOP_SRV:
2142 		tipc_group_member_evt(tsk->group, &wakeup, &sk->sk_rcvbuf,
2143 				      hdr, inputq, xmitq);
2144 		break;
2145 	default:
2146 		break;
2147 	}
2148 
2149 	if (wakeup)
2150 		sk->sk_write_space(sk);
2151 
2152 	kfree_skb(skb);
2153 }
2154 
2155 /**
2156  * tipc_sk_filter_connect - check incoming message for a connection-based socket
2157  * @tsk: TIPC socket
2158  * @skb: pointer to message buffer.
2159  * @xmitq: for Nagle ACK if any
2160  * Returns true if message should be added to receive queue, false otherwise
2161  */
2162 static bool tipc_sk_filter_connect(struct tipc_sock *tsk, struct sk_buff *skb,
2163 				   struct sk_buff_head *xmitq)
2164 {
2165 	struct sock *sk = &tsk->sk;
2166 	struct net *net = sock_net(sk);
2167 	struct tipc_msg *hdr = buf_msg(skb);
2168 	bool con_msg = msg_connected(hdr);
2169 	u32 pport = tsk_peer_port(tsk);
2170 	u32 pnode = tsk_peer_node(tsk);
2171 	u32 oport = msg_origport(hdr);
2172 	u32 onode = msg_orignode(hdr);
2173 	int err = msg_errcode(hdr);
2174 	unsigned long delay;
2175 
2176 	if (unlikely(msg_mcast(hdr)))
2177 		return false;
2178 	tsk->oneway = 0;
2179 
2180 	switch (sk->sk_state) {
2181 	case TIPC_CONNECTING:
2182 		/* Setup ACK */
2183 		if (likely(con_msg)) {
2184 			if (err)
2185 				break;
2186 			tipc_sk_finish_conn(tsk, oport, onode);
2187 			msg_set_importance(&tsk->phdr, msg_importance(hdr));
2188 			/* ACK+ message with data is added to receive queue */
2189 			if (msg_data_sz(hdr))
2190 				return true;
2191 			/* Empty ACK-, - wake up sleeping connect() and drop */
2192 			sk->sk_state_change(sk);
2193 			msg_set_dest_droppable(hdr, 1);
2194 			return false;
2195 		}
2196 		/* Ignore connectionless message if not from listening socket */
2197 		if (oport != pport || onode != pnode)
2198 			return false;
2199 
2200 		/* Rejected SYN */
2201 		if (err != TIPC_ERR_OVERLOAD)
2202 			break;
2203 
2204 		/* Prepare for new setup attempt if we have a SYN clone */
2205 		if (skb_queue_empty(&sk->sk_write_queue))
2206 			break;
2207 		get_random_bytes(&delay, 2);
2208 		delay %= (tsk->conn_timeout / 4);
2209 		delay = msecs_to_jiffies(delay + 100);
2210 		sk_reset_timer(sk, &sk->sk_timer, jiffies + delay);
2211 		return false;
2212 	case TIPC_OPEN:
2213 	case TIPC_DISCONNECTING:
2214 		return false;
2215 	case TIPC_LISTEN:
2216 		/* Accept only SYN message */
2217 		if (!msg_is_syn(hdr) &&
2218 		    tipc_node_get_capabilities(net, onode) & TIPC_SYN_BIT)
2219 			return false;
2220 		if (!con_msg && !err)
2221 			return true;
2222 		return false;
2223 	case TIPC_ESTABLISHED:
2224 		if (!skb_queue_empty(&sk->sk_write_queue))
2225 			tipc_sk_push_backlog(tsk, false);
2226 		/* Accept only connection-based messages sent by peer */
2227 		if (likely(con_msg && !err && pport == oport &&
2228 			   pnode == onode)) {
2229 			if (msg_ack_required(hdr)) {
2230 				struct sk_buff *skb;
2231 
2232 				skb = tipc_sk_build_ack(tsk);
2233 				if (skb) {
2234 					msg_set_nagle_ack(buf_msg(skb));
2235 					__skb_queue_tail(xmitq, skb);
2236 				}
2237 			}
2238 			return true;
2239 		}
2240 		if (!tsk_peer_msg(tsk, hdr))
2241 			return false;
2242 		if (!err)
2243 			return true;
2244 		tipc_set_sk_state(sk, TIPC_DISCONNECTING);
2245 		tipc_node_remove_conn(net, pnode, tsk->portid);
2246 		sk->sk_state_change(sk);
2247 		return true;
2248 	default:
2249 		pr_err("Unknown sk_state %u\n", sk->sk_state);
2250 	}
2251 	/* Abort connection setup attempt */
2252 	tipc_set_sk_state(sk, TIPC_DISCONNECTING);
2253 	sk->sk_err = ECONNREFUSED;
2254 	sk->sk_state_change(sk);
2255 	return true;
2256 }
2257 
2258 /**
2259  * rcvbuf_limit - get proper overload limit of socket receive queue
2260  * @sk: socket
2261  * @skb: message
2262  *
2263  * For connection oriented messages, irrespective of importance,
2264  * default queue limit is 2 MB.
2265  *
2266  * For connectionless messages, queue limits are based on message
2267  * importance as follows:
2268  *
2269  * TIPC_LOW_IMPORTANCE       (2 MB)
2270  * TIPC_MEDIUM_IMPORTANCE    (4 MB)
2271  * TIPC_HIGH_IMPORTANCE      (8 MB)
2272  * TIPC_CRITICAL_IMPORTANCE  (16 MB)
2273  *
2274  * Returns overload limit according to corresponding message importance
2275  */
2276 static unsigned int rcvbuf_limit(struct sock *sk, struct sk_buff *skb)
2277 {
2278 	struct tipc_sock *tsk = tipc_sk(sk);
2279 	struct tipc_msg *hdr = buf_msg(skb);
2280 
2281 	if (unlikely(msg_in_group(hdr)))
2282 		return READ_ONCE(sk->sk_rcvbuf);
2283 
2284 	if (unlikely(!msg_connected(hdr)))
2285 		return READ_ONCE(sk->sk_rcvbuf) << msg_importance(hdr);
2286 
2287 	if (likely(tsk->peer_caps & TIPC_BLOCK_FLOWCTL))
2288 		return READ_ONCE(sk->sk_rcvbuf);
2289 
2290 	return FLOWCTL_MSG_LIM;
2291 }
2292 
2293 /**
2294  * tipc_sk_filter_rcv - validate incoming message
2295  * @sk: socket
2296  * @skb: pointer to message.
2297  *
2298  * Enqueues message on receive queue if acceptable; optionally handles
2299  * disconnect indication for a connected socket.
2300  *
2301  * Called with socket lock already taken
2302  *
2303  */
2304 static void tipc_sk_filter_rcv(struct sock *sk, struct sk_buff *skb,
2305 			       struct sk_buff_head *xmitq)
2306 {
2307 	bool sk_conn = !tipc_sk_type_connectionless(sk);
2308 	struct tipc_sock *tsk = tipc_sk(sk);
2309 	struct tipc_group *grp = tsk->group;
2310 	struct tipc_msg *hdr = buf_msg(skb);
2311 	struct net *net = sock_net(sk);
2312 	struct sk_buff_head inputq;
2313 	int mtyp = msg_type(hdr);
2314 	int limit, err = TIPC_OK;
2315 
2316 	trace_tipc_sk_filter_rcv(sk, skb, TIPC_DUMP_ALL, " ");
2317 	TIPC_SKB_CB(skb)->bytes_read = 0;
2318 	__skb_queue_head_init(&inputq);
2319 	__skb_queue_tail(&inputq, skb);
2320 
2321 	if (unlikely(!msg_isdata(hdr)))
2322 		tipc_sk_proto_rcv(sk, &inputq, xmitq);
2323 
2324 	if (unlikely(grp))
2325 		tipc_group_filter_msg(grp, &inputq, xmitq);
2326 
2327 	if (unlikely(!grp) && mtyp == TIPC_MCAST_MSG)
2328 		tipc_mcast_filter_msg(net, &tsk->mc_method.deferredq, &inputq);
2329 
2330 	/* Validate and add to receive buffer if there is space */
2331 	while ((skb = __skb_dequeue(&inputq))) {
2332 		hdr = buf_msg(skb);
2333 		limit = rcvbuf_limit(sk, skb);
2334 		if ((sk_conn && !tipc_sk_filter_connect(tsk, skb, xmitq)) ||
2335 		    (!sk_conn && msg_connected(hdr)) ||
2336 		    (!grp && msg_in_group(hdr)))
2337 			err = TIPC_ERR_NO_PORT;
2338 		else if (sk_rmem_alloc_get(sk) + skb->truesize >= limit) {
2339 			trace_tipc_sk_dump(sk, skb, TIPC_DUMP_ALL,
2340 					   "err_overload2!");
2341 			atomic_inc(&sk->sk_drops);
2342 			err = TIPC_ERR_OVERLOAD;
2343 		}
2344 
2345 		if (unlikely(err)) {
2346 			if (tipc_msg_reverse(tipc_own_addr(net), &skb, err)) {
2347 				trace_tipc_sk_rej_msg(sk, skb, TIPC_DUMP_NONE,
2348 						      "@filter_rcv!");
2349 				__skb_queue_tail(xmitq, skb);
2350 			}
2351 			err = TIPC_OK;
2352 			continue;
2353 		}
2354 		__skb_queue_tail(&sk->sk_receive_queue, skb);
2355 		skb_set_owner_r(skb, sk);
2356 		trace_tipc_sk_overlimit2(sk, skb, TIPC_DUMP_ALL,
2357 					 "rcvq >90% allocated!");
2358 		sk->sk_data_ready(sk);
2359 	}
2360 }
2361 
2362 /**
2363  * tipc_sk_backlog_rcv - handle incoming message from backlog queue
2364  * @sk: socket
2365  * @skb: message
2366  *
2367  * Caller must hold socket lock
2368  */
2369 static int tipc_sk_backlog_rcv(struct sock *sk, struct sk_buff *skb)
2370 {
2371 	unsigned int before = sk_rmem_alloc_get(sk);
2372 	struct sk_buff_head xmitq;
2373 	unsigned int added;
2374 
2375 	__skb_queue_head_init(&xmitq);
2376 
2377 	tipc_sk_filter_rcv(sk, skb, &xmitq);
2378 	added = sk_rmem_alloc_get(sk) - before;
2379 	atomic_add(added, &tipc_sk(sk)->dupl_rcvcnt);
2380 
2381 	/* Send pending response/rejected messages, if any */
2382 	tipc_node_distr_xmit(sock_net(sk), &xmitq);
2383 	return 0;
2384 }
2385 
2386 /**
2387  * tipc_sk_enqueue - extract all buffers with destination 'dport' from
2388  *                   inputq and try adding them to socket or backlog queue
2389  * @inputq: list of incoming buffers with potentially different destinations
2390  * @sk: socket where the buffers should be enqueued
2391  * @dport: port number for the socket
2392  *
2393  * Caller must hold socket lock
2394  */
2395 static void tipc_sk_enqueue(struct sk_buff_head *inputq, struct sock *sk,
2396 			    u32 dport, struct sk_buff_head *xmitq)
2397 {
2398 	unsigned long time_limit = jiffies + 2;
2399 	struct sk_buff *skb;
2400 	unsigned int lim;
2401 	atomic_t *dcnt;
2402 	u32 onode;
2403 
2404 	while (skb_queue_len(inputq)) {
2405 		if (unlikely(time_after_eq(jiffies, time_limit)))
2406 			return;
2407 
2408 		skb = tipc_skb_dequeue(inputq, dport);
2409 		if (unlikely(!skb))
2410 			return;
2411 
2412 		/* Add message directly to receive queue if possible */
2413 		if (!sock_owned_by_user(sk)) {
2414 			tipc_sk_filter_rcv(sk, skb, xmitq);
2415 			continue;
2416 		}
2417 
2418 		/* Try backlog, compensating for double-counted bytes */
2419 		dcnt = &tipc_sk(sk)->dupl_rcvcnt;
2420 		if (!sk->sk_backlog.len)
2421 			atomic_set(dcnt, 0);
2422 		lim = rcvbuf_limit(sk, skb) + atomic_read(dcnt);
2423 		if (likely(!sk_add_backlog(sk, skb, lim))) {
2424 			trace_tipc_sk_overlimit1(sk, skb, TIPC_DUMP_ALL,
2425 						 "bklg & rcvq >90% allocated!");
2426 			continue;
2427 		}
2428 
2429 		trace_tipc_sk_dump(sk, skb, TIPC_DUMP_ALL, "err_overload!");
2430 		/* Overload => reject message back to sender */
2431 		onode = tipc_own_addr(sock_net(sk));
2432 		atomic_inc(&sk->sk_drops);
2433 		if (tipc_msg_reverse(onode, &skb, TIPC_ERR_OVERLOAD)) {
2434 			trace_tipc_sk_rej_msg(sk, skb, TIPC_DUMP_ALL,
2435 					      "@sk_enqueue!");
2436 			__skb_queue_tail(xmitq, skb);
2437 		}
2438 		break;
2439 	}
2440 }
2441 
2442 /**
2443  * tipc_sk_rcv - handle a chain of incoming buffers
2444  * @inputq: buffer list containing the buffers
2445  * Consumes all buffers in list until inputq is empty
2446  * Note: may be called in multiple threads referring to the same queue
2447  */
2448 void tipc_sk_rcv(struct net *net, struct sk_buff_head *inputq)
2449 {
2450 	struct sk_buff_head xmitq;
2451 	u32 dnode, dport = 0;
2452 	int err;
2453 	struct tipc_sock *tsk;
2454 	struct sock *sk;
2455 	struct sk_buff *skb;
2456 
2457 	__skb_queue_head_init(&xmitq);
2458 	while (skb_queue_len(inputq)) {
2459 		dport = tipc_skb_peek_port(inputq, dport);
2460 		tsk = tipc_sk_lookup(net, dport);
2461 
2462 		if (likely(tsk)) {
2463 			sk = &tsk->sk;
2464 			if (likely(spin_trylock_bh(&sk->sk_lock.slock))) {
2465 				tipc_sk_enqueue(inputq, sk, dport, &xmitq);
2466 				spin_unlock_bh(&sk->sk_lock.slock);
2467 			}
2468 			/* Send pending response/rejected messages, if any */
2469 			tipc_node_distr_xmit(sock_net(sk), &xmitq);
2470 			sock_put(sk);
2471 			continue;
2472 		}
2473 		/* No destination socket => dequeue skb if still there */
2474 		skb = tipc_skb_dequeue(inputq, dport);
2475 		if (!skb)
2476 			return;
2477 
2478 		/* Try secondary lookup if unresolved named message */
2479 		err = TIPC_ERR_NO_PORT;
2480 		if (tipc_msg_lookup_dest(net, skb, &err))
2481 			goto xmit;
2482 
2483 		/* Prepare for message rejection */
2484 		if (!tipc_msg_reverse(tipc_own_addr(net), &skb, err))
2485 			continue;
2486 
2487 		trace_tipc_sk_rej_msg(NULL, skb, TIPC_DUMP_NONE, "@sk_rcv!");
2488 xmit:
2489 		dnode = msg_destnode(buf_msg(skb));
2490 		tipc_node_xmit_skb(net, skb, dnode, dport);
2491 	}
2492 }
2493 
2494 static int tipc_wait_for_connect(struct socket *sock, long *timeo_p)
2495 {
2496 	DEFINE_WAIT_FUNC(wait, woken_wake_function);
2497 	struct sock *sk = sock->sk;
2498 	int done;
2499 
2500 	do {
2501 		int err = sock_error(sk);
2502 		if (err)
2503 			return err;
2504 		if (!*timeo_p)
2505 			return -ETIMEDOUT;
2506 		if (signal_pending(current))
2507 			return sock_intr_errno(*timeo_p);
2508 		if (sk->sk_state == TIPC_DISCONNECTING)
2509 			break;
2510 
2511 		add_wait_queue(sk_sleep(sk), &wait);
2512 		done = sk_wait_event(sk, timeo_p, tipc_sk_connected(sk),
2513 				     &wait);
2514 		remove_wait_queue(sk_sleep(sk), &wait);
2515 	} while (!done);
2516 	return 0;
2517 }
2518 
2519 static bool tipc_sockaddr_is_sane(struct sockaddr_tipc *addr)
2520 {
2521 	if (addr->family != AF_TIPC)
2522 		return false;
2523 	if (addr->addrtype == TIPC_SERVICE_RANGE)
2524 		return (addr->addr.nameseq.lower <= addr->addr.nameseq.upper);
2525 	return (addr->addrtype == TIPC_SERVICE_ADDR ||
2526 		addr->addrtype == TIPC_SOCKET_ADDR);
2527 }
2528 
2529 /**
2530  * tipc_connect - establish a connection to another TIPC port
2531  * @sock: socket structure
2532  * @dest: socket address for destination port
2533  * @destlen: size of socket address data structure
2534  * @flags: file-related flags associated with socket
2535  *
2536  * Returns 0 on success, errno otherwise
2537  */
2538 static int tipc_connect(struct socket *sock, struct sockaddr *dest,
2539 			int destlen, int flags)
2540 {
2541 	struct sock *sk = sock->sk;
2542 	struct tipc_sock *tsk = tipc_sk(sk);
2543 	struct sockaddr_tipc *dst = (struct sockaddr_tipc *)dest;
2544 	struct msghdr m = {NULL,};
2545 	long timeout = (flags & O_NONBLOCK) ? 0 : tsk->conn_timeout;
2546 	int previous;
2547 	int res = 0;
2548 
2549 	if (destlen != sizeof(struct sockaddr_tipc))
2550 		return -EINVAL;
2551 
2552 	lock_sock(sk);
2553 
2554 	if (tsk->group) {
2555 		res = -EINVAL;
2556 		goto exit;
2557 	}
2558 
2559 	if (dst->family == AF_UNSPEC) {
2560 		memset(&tsk->peer, 0, sizeof(struct sockaddr_tipc));
2561 		if (!tipc_sk_type_connectionless(sk))
2562 			res = -EINVAL;
2563 		goto exit;
2564 	}
2565 	if (!tipc_sockaddr_is_sane(dst)) {
2566 		res = -EINVAL;
2567 		goto exit;
2568 	}
2569 	/* DGRAM/RDM connect(), just save the destaddr */
2570 	if (tipc_sk_type_connectionless(sk)) {
2571 		memcpy(&tsk->peer, dest, destlen);
2572 		goto exit;
2573 	} else if (dst->addrtype == TIPC_SERVICE_RANGE) {
2574 		res = -EINVAL;
2575 		goto exit;
2576 	}
2577 
2578 	previous = sk->sk_state;
2579 
2580 	switch (sk->sk_state) {
2581 	case TIPC_OPEN:
2582 		/* Send a 'SYN-' to destination */
2583 		m.msg_name = dest;
2584 		m.msg_namelen = destlen;
2585 
2586 		/* If connect is in non-blocking case, set MSG_DONTWAIT to
2587 		 * indicate send_msg() is never blocked.
2588 		 */
2589 		if (!timeout)
2590 			m.msg_flags = MSG_DONTWAIT;
2591 
2592 		res = __tipc_sendmsg(sock, &m, 0);
2593 		if ((res < 0) && (res != -EWOULDBLOCK))
2594 			goto exit;
2595 
2596 		/* Just entered TIPC_CONNECTING state; the only
2597 		 * difference is that return value in non-blocking
2598 		 * case is EINPROGRESS, rather than EALREADY.
2599 		 */
2600 		res = -EINPROGRESS;
2601 		/* fall through */
2602 	case TIPC_CONNECTING:
2603 		if (!timeout) {
2604 			if (previous == TIPC_CONNECTING)
2605 				res = -EALREADY;
2606 			goto exit;
2607 		}
2608 		timeout = msecs_to_jiffies(timeout);
2609 		/* Wait until an 'ACK' or 'RST' arrives, or a timeout occurs */
2610 		res = tipc_wait_for_connect(sock, &timeout);
2611 		break;
2612 	case TIPC_ESTABLISHED:
2613 		res = -EISCONN;
2614 		break;
2615 	default:
2616 		res = -EINVAL;
2617 	}
2618 
2619 exit:
2620 	release_sock(sk);
2621 	return res;
2622 }
2623 
2624 /**
2625  * tipc_listen - allow socket to listen for incoming connections
2626  * @sock: socket structure
2627  * @len: (unused)
2628  *
2629  * Returns 0 on success, errno otherwise
2630  */
2631 static int tipc_listen(struct socket *sock, int len)
2632 {
2633 	struct sock *sk = sock->sk;
2634 	int res;
2635 
2636 	lock_sock(sk);
2637 	res = tipc_set_sk_state(sk, TIPC_LISTEN);
2638 	release_sock(sk);
2639 
2640 	return res;
2641 }
2642 
2643 static int tipc_wait_for_accept(struct socket *sock, long timeo)
2644 {
2645 	struct sock *sk = sock->sk;
2646 	DEFINE_WAIT(wait);
2647 	int err;
2648 
2649 	/* True wake-one mechanism for incoming connections: only
2650 	 * one process gets woken up, not the 'whole herd'.
2651 	 * Since we do not 'race & poll' for established sockets
2652 	 * anymore, the common case will execute the loop only once.
2653 	*/
2654 	for (;;) {
2655 		prepare_to_wait_exclusive(sk_sleep(sk), &wait,
2656 					  TASK_INTERRUPTIBLE);
2657 		if (timeo && skb_queue_empty(&sk->sk_receive_queue)) {
2658 			release_sock(sk);
2659 			timeo = schedule_timeout(timeo);
2660 			lock_sock(sk);
2661 		}
2662 		err = 0;
2663 		if (!skb_queue_empty(&sk->sk_receive_queue))
2664 			break;
2665 		err = -EAGAIN;
2666 		if (!timeo)
2667 			break;
2668 		err = sock_intr_errno(timeo);
2669 		if (signal_pending(current))
2670 			break;
2671 	}
2672 	finish_wait(sk_sleep(sk), &wait);
2673 	return err;
2674 }
2675 
2676 /**
2677  * tipc_accept - wait for connection request
2678  * @sock: listening socket
2679  * @newsock: new socket that is to be connected
2680  * @flags: file-related flags associated with socket
2681  *
2682  * Returns 0 on success, errno otherwise
2683  */
2684 static int tipc_accept(struct socket *sock, struct socket *new_sock, int flags,
2685 		       bool kern)
2686 {
2687 	struct sock *new_sk, *sk = sock->sk;
2688 	struct sk_buff *buf;
2689 	struct tipc_sock *new_tsock;
2690 	struct tipc_msg *msg;
2691 	long timeo;
2692 	int res;
2693 
2694 	lock_sock(sk);
2695 
2696 	if (sk->sk_state != TIPC_LISTEN) {
2697 		res = -EINVAL;
2698 		goto exit;
2699 	}
2700 	timeo = sock_rcvtimeo(sk, flags & O_NONBLOCK);
2701 	res = tipc_wait_for_accept(sock, timeo);
2702 	if (res)
2703 		goto exit;
2704 
2705 	buf = skb_peek(&sk->sk_receive_queue);
2706 
2707 	res = tipc_sk_create(sock_net(sock->sk), new_sock, 0, kern);
2708 	if (res)
2709 		goto exit;
2710 	security_sk_clone(sock->sk, new_sock->sk);
2711 
2712 	new_sk = new_sock->sk;
2713 	new_tsock = tipc_sk(new_sk);
2714 	msg = buf_msg(buf);
2715 
2716 	/* we lock on new_sk; but lockdep sees the lock on sk */
2717 	lock_sock_nested(new_sk, SINGLE_DEPTH_NESTING);
2718 
2719 	/*
2720 	 * Reject any stray messages received by new socket
2721 	 * before the socket lock was taken (very, very unlikely)
2722 	 */
2723 	tsk_rej_rx_queue(new_sk, TIPC_ERR_NO_PORT);
2724 
2725 	/* Connect new socket to it's peer */
2726 	tipc_sk_finish_conn(new_tsock, msg_origport(msg), msg_orignode(msg));
2727 
2728 	tsk_set_importance(new_sk, msg_importance(msg));
2729 	if (msg_named(msg)) {
2730 		new_tsock->conn_type = msg_nametype(msg);
2731 		new_tsock->conn_instance = msg_nameinst(msg);
2732 	}
2733 
2734 	/*
2735 	 * Respond to 'SYN-' by discarding it & returning 'ACK'-.
2736 	 * Respond to 'SYN+' by queuing it on new socket.
2737 	 */
2738 	if (!msg_data_sz(msg)) {
2739 		struct msghdr m = {NULL,};
2740 
2741 		tsk_advance_rx_queue(sk);
2742 		__tipc_sendstream(new_sock, &m, 0);
2743 	} else {
2744 		__skb_dequeue(&sk->sk_receive_queue);
2745 		__skb_queue_head(&new_sk->sk_receive_queue, buf);
2746 		skb_set_owner_r(buf, new_sk);
2747 	}
2748 	release_sock(new_sk);
2749 exit:
2750 	release_sock(sk);
2751 	return res;
2752 }
2753 
2754 /**
2755  * tipc_shutdown - shutdown socket connection
2756  * @sock: socket structure
2757  * @how: direction to close (must be SHUT_RDWR)
2758  *
2759  * Terminates connection (if necessary), then purges socket's receive queue.
2760  *
2761  * Returns 0 on success, errno otherwise
2762  */
2763 static int tipc_shutdown(struct socket *sock, int how)
2764 {
2765 	struct sock *sk = sock->sk;
2766 	int res;
2767 
2768 	if (how != SHUT_RDWR)
2769 		return -EINVAL;
2770 
2771 	lock_sock(sk);
2772 
2773 	trace_tipc_sk_shutdown(sk, NULL, TIPC_DUMP_ALL, " ");
2774 	__tipc_shutdown(sock, TIPC_CONN_SHUTDOWN);
2775 	sk->sk_shutdown = SEND_SHUTDOWN;
2776 
2777 	if (sk->sk_state == TIPC_DISCONNECTING) {
2778 		/* Discard any unreceived messages */
2779 		__skb_queue_purge(&sk->sk_receive_queue);
2780 
2781 		/* Wake up anyone sleeping in poll */
2782 		sk->sk_state_change(sk);
2783 		res = 0;
2784 	} else {
2785 		res = -ENOTCONN;
2786 	}
2787 
2788 	release_sock(sk);
2789 	return res;
2790 }
2791 
2792 static void tipc_sk_check_probing_state(struct sock *sk,
2793 					struct sk_buff_head *list)
2794 {
2795 	struct tipc_sock *tsk = tipc_sk(sk);
2796 	u32 pnode = tsk_peer_node(tsk);
2797 	u32 pport = tsk_peer_port(tsk);
2798 	u32 self = tsk_own_node(tsk);
2799 	u32 oport = tsk->portid;
2800 	struct sk_buff *skb;
2801 
2802 	if (tsk->probe_unacked) {
2803 		tipc_set_sk_state(sk, TIPC_DISCONNECTING);
2804 		sk->sk_err = ECONNABORTED;
2805 		tipc_node_remove_conn(sock_net(sk), pnode, pport);
2806 		sk->sk_state_change(sk);
2807 		return;
2808 	}
2809 	/* Prepare new probe */
2810 	skb = tipc_msg_create(CONN_MANAGER, CONN_PROBE, INT_H_SIZE, 0,
2811 			      pnode, self, pport, oport, TIPC_OK);
2812 	if (skb)
2813 		__skb_queue_tail(list, skb);
2814 	tsk->probe_unacked = true;
2815 	sk_reset_timer(sk, &sk->sk_timer, jiffies + CONN_PROBING_INTV);
2816 }
2817 
2818 static void tipc_sk_retry_connect(struct sock *sk, struct sk_buff_head *list)
2819 {
2820 	struct tipc_sock *tsk = tipc_sk(sk);
2821 
2822 	/* Try again later if dest link is congested */
2823 	if (tsk->cong_link_cnt) {
2824 		sk_reset_timer(sk, &sk->sk_timer, msecs_to_jiffies(100));
2825 		return;
2826 	}
2827 	/* Prepare SYN for retransmit */
2828 	tipc_msg_skb_clone(&sk->sk_write_queue, list);
2829 }
2830 
2831 static void tipc_sk_timeout(struct timer_list *t)
2832 {
2833 	struct sock *sk = from_timer(sk, t, sk_timer);
2834 	struct tipc_sock *tsk = tipc_sk(sk);
2835 	u32 pnode = tsk_peer_node(tsk);
2836 	struct sk_buff_head list;
2837 	int rc = 0;
2838 
2839 	__skb_queue_head_init(&list);
2840 	bh_lock_sock(sk);
2841 
2842 	/* Try again later if socket is busy */
2843 	if (sock_owned_by_user(sk)) {
2844 		sk_reset_timer(sk, &sk->sk_timer, jiffies + HZ / 20);
2845 		bh_unlock_sock(sk);
2846 		sock_put(sk);
2847 		return;
2848 	}
2849 
2850 	if (sk->sk_state == TIPC_ESTABLISHED)
2851 		tipc_sk_check_probing_state(sk, &list);
2852 	else if (sk->sk_state == TIPC_CONNECTING)
2853 		tipc_sk_retry_connect(sk, &list);
2854 
2855 	bh_unlock_sock(sk);
2856 
2857 	if (!skb_queue_empty(&list))
2858 		rc = tipc_node_xmit(sock_net(sk), &list, pnode, tsk->portid);
2859 
2860 	/* SYN messages may cause link congestion */
2861 	if (rc == -ELINKCONG) {
2862 		tipc_dest_push(&tsk->cong_links, pnode, 0);
2863 		tsk->cong_link_cnt = 1;
2864 	}
2865 	sock_put(sk);
2866 }
2867 
2868 static int tipc_sk_publish(struct tipc_sock *tsk, uint scope,
2869 			   struct tipc_name_seq const *seq)
2870 {
2871 	struct sock *sk = &tsk->sk;
2872 	struct net *net = sock_net(sk);
2873 	struct publication *publ;
2874 	u32 key;
2875 
2876 	if (scope != TIPC_NODE_SCOPE)
2877 		scope = TIPC_CLUSTER_SCOPE;
2878 
2879 	if (tipc_sk_connected(sk))
2880 		return -EINVAL;
2881 	key = tsk->portid + tsk->pub_count + 1;
2882 	if (key == tsk->portid)
2883 		return -EADDRINUSE;
2884 
2885 	publ = tipc_nametbl_publish(net, seq->type, seq->lower, seq->upper,
2886 				    scope, tsk->portid, key);
2887 	if (unlikely(!publ))
2888 		return -EINVAL;
2889 
2890 	list_add(&publ->binding_sock, &tsk->publications);
2891 	tsk->pub_count++;
2892 	tsk->published = 1;
2893 	return 0;
2894 }
2895 
2896 static int tipc_sk_withdraw(struct tipc_sock *tsk, uint scope,
2897 			    struct tipc_name_seq const *seq)
2898 {
2899 	struct net *net = sock_net(&tsk->sk);
2900 	struct publication *publ;
2901 	struct publication *safe;
2902 	int rc = -EINVAL;
2903 
2904 	if (scope != TIPC_NODE_SCOPE)
2905 		scope = TIPC_CLUSTER_SCOPE;
2906 
2907 	list_for_each_entry_safe(publ, safe, &tsk->publications, binding_sock) {
2908 		if (seq) {
2909 			if (publ->scope != scope)
2910 				continue;
2911 			if (publ->type != seq->type)
2912 				continue;
2913 			if (publ->lower != seq->lower)
2914 				continue;
2915 			if (publ->upper != seq->upper)
2916 				break;
2917 			tipc_nametbl_withdraw(net, publ->type, publ->lower,
2918 					      publ->upper, publ->key);
2919 			rc = 0;
2920 			break;
2921 		}
2922 		tipc_nametbl_withdraw(net, publ->type, publ->lower,
2923 				      publ->upper, publ->key);
2924 		rc = 0;
2925 	}
2926 	if (list_empty(&tsk->publications))
2927 		tsk->published = 0;
2928 	return rc;
2929 }
2930 
2931 /* tipc_sk_reinit: set non-zero address in all existing sockets
2932  *                 when we go from standalone to network mode.
2933  */
2934 void tipc_sk_reinit(struct net *net)
2935 {
2936 	struct tipc_net *tn = net_generic(net, tipc_net_id);
2937 	struct rhashtable_iter iter;
2938 	struct tipc_sock *tsk;
2939 	struct tipc_msg *msg;
2940 
2941 	rhashtable_walk_enter(&tn->sk_rht, &iter);
2942 
2943 	do {
2944 		rhashtable_walk_start(&iter);
2945 
2946 		while ((tsk = rhashtable_walk_next(&iter)) && !IS_ERR(tsk)) {
2947 			sock_hold(&tsk->sk);
2948 			rhashtable_walk_stop(&iter);
2949 			lock_sock(&tsk->sk);
2950 			msg = &tsk->phdr;
2951 			msg_set_prevnode(msg, tipc_own_addr(net));
2952 			msg_set_orignode(msg, tipc_own_addr(net));
2953 			release_sock(&tsk->sk);
2954 			rhashtable_walk_start(&iter);
2955 			sock_put(&tsk->sk);
2956 		}
2957 
2958 		rhashtable_walk_stop(&iter);
2959 	} while (tsk == ERR_PTR(-EAGAIN));
2960 
2961 	rhashtable_walk_exit(&iter);
2962 }
2963 
2964 static struct tipc_sock *tipc_sk_lookup(struct net *net, u32 portid)
2965 {
2966 	struct tipc_net *tn = net_generic(net, tipc_net_id);
2967 	struct tipc_sock *tsk;
2968 
2969 	rcu_read_lock();
2970 	tsk = rhashtable_lookup(&tn->sk_rht, &portid, tsk_rht_params);
2971 	if (tsk)
2972 		sock_hold(&tsk->sk);
2973 	rcu_read_unlock();
2974 
2975 	return tsk;
2976 }
2977 
2978 static int tipc_sk_insert(struct tipc_sock *tsk)
2979 {
2980 	struct sock *sk = &tsk->sk;
2981 	struct net *net = sock_net(sk);
2982 	struct tipc_net *tn = net_generic(net, tipc_net_id);
2983 	u32 remaining = (TIPC_MAX_PORT - TIPC_MIN_PORT) + 1;
2984 	u32 portid = prandom_u32() % remaining + TIPC_MIN_PORT;
2985 
2986 	while (remaining--) {
2987 		portid++;
2988 		if ((portid < TIPC_MIN_PORT) || (portid > TIPC_MAX_PORT))
2989 			portid = TIPC_MIN_PORT;
2990 		tsk->portid = portid;
2991 		sock_hold(&tsk->sk);
2992 		if (!rhashtable_lookup_insert_fast(&tn->sk_rht, &tsk->node,
2993 						   tsk_rht_params))
2994 			return 0;
2995 		sock_put(&tsk->sk);
2996 	}
2997 
2998 	return -1;
2999 }
3000 
3001 static void tipc_sk_remove(struct tipc_sock *tsk)
3002 {
3003 	struct sock *sk = &tsk->sk;
3004 	struct tipc_net *tn = net_generic(sock_net(sk), tipc_net_id);
3005 
3006 	if (!rhashtable_remove_fast(&tn->sk_rht, &tsk->node, tsk_rht_params)) {
3007 		WARN_ON(refcount_read(&sk->sk_refcnt) == 1);
3008 		__sock_put(sk);
3009 	}
3010 }
3011 
3012 static const struct rhashtable_params tsk_rht_params = {
3013 	.nelem_hint = 192,
3014 	.head_offset = offsetof(struct tipc_sock, node),
3015 	.key_offset = offsetof(struct tipc_sock, portid),
3016 	.key_len = sizeof(u32), /* portid */
3017 	.max_size = 1048576,
3018 	.min_size = 256,
3019 	.automatic_shrinking = true,
3020 };
3021 
3022 int tipc_sk_rht_init(struct net *net)
3023 {
3024 	struct tipc_net *tn = net_generic(net, tipc_net_id);
3025 
3026 	return rhashtable_init(&tn->sk_rht, &tsk_rht_params);
3027 }
3028 
3029 void tipc_sk_rht_destroy(struct net *net)
3030 {
3031 	struct tipc_net *tn = net_generic(net, tipc_net_id);
3032 
3033 	/* Wait for socket readers to complete */
3034 	synchronize_net();
3035 
3036 	rhashtable_destroy(&tn->sk_rht);
3037 }
3038 
3039 static int tipc_sk_join(struct tipc_sock *tsk, struct tipc_group_req *mreq)
3040 {
3041 	struct net *net = sock_net(&tsk->sk);
3042 	struct tipc_group *grp = tsk->group;
3043 	struct tipc_msg *hdr = &tsk->phdr;
3044 	struct tipc_name_seq seq;
3045 	int rc;
3046 
3047 	if (mreq->type < TIPC_RESERVED_TYPES)
3048 		return -EACCES;
3049 	if (mreq->scope > TIPC_NODE_SCOPE)
3050 		return -EINVAL;
3051 	if (grp)
3052 		return -EACCES;
3053 	grp = tipc_group_create(net, tsk->portid, mreq, &tsk->group_is_open);
3054 	if (!grp)
3055 		return -ENOMEM;
3056 	tsk->group = grp;
3057 	msg_set_lookup_scope(hdr, mreq->scope);
3058 	msg_set_nametype(hdr, mreq->type);
3059 	msg_set_dest_droppable(hdr, true);
3060 	seq.type = mreq->type;
3061 	seq.lower = mreq->instance;
3062 	seq.upper = seq.lower;
3063 	tipc_nametbl_build_group(net, grp, mreq->type, mreq->scope);
3064 	rc = tipc_sk_publish(tsk, mreq->scope, &seq);
3065 	if (rc) {
3066 		tipc_group_delete(net, grp);
3067 		tsk->group = NULL;
3068 		return rc;
3069 	}
3070 	/* Eliminate any risk that a broadcast overtakes sent JOINs */
3071 	tsk->mc_method.rcast = true;
3072 	tsk->mc_method.mandatory = true;
3073 	tipc_group_join(net, grp, &tsk->sk.sk_rcvbuf);
3074 	return rc;
3075 }
3076 
3077 static int tipc_sk_leave(struct tipc_sock *tsk)
3078 {
3079 	struct net *net = sock_net(&tsk->sk);
3080 	struct tipc_group *grp = tsk->group;
3081 	struct tipc_name_seq seq;
3082 	int scope;
3083 
3084 	if (!grp)
3085 		return -EINVAL;
3086 	tipc_group_self(grp, &seq, &scope);
3087 	tipc_group_delete(net, grp);
3088 	tsk->group = NULL;
3089 	tipc_sk_withdraw(tsk, scope, &seq);
3090 	return 0;
3091 }
3092 
3093 /**
3094  * tipc_setsockopt - set socket option
3095  * @sock: socket structure
3096  * @lvl: option level
3097  * @opt: option identifier
3098  * @ov: pointer to new option value
3099  * @ol: length of option value
3100  *
3101  * For stream sockets only, accepts and ignores all IPPROTO_TCP options
3102  * (to ease compatibility).
3103  *
3104  * Returns 0 on success, errno otherwise
3105  */
3106 static int tipc_setsockopt(struct socket *sock, int lvl, int opt,
3107 			   char __user *ov, unsigned int ol)
3108 {
3109 	struct sock *sk = sock->sk;
3110 	struct tipc_sock *tsk = tipc_sk(sk);
3111 	struct tipc_group_req mreq;
3112 	u32 value = 0;
3113 	int res = 0;
3114 
3115 	if ((lvl == IPPROTO_TCP) && (sock->type == SOCK_STREAM))
3116 		return 0;
3117 	if (lvl != SOL_TIPC)
3118 		return -ENOPROTOOPT;
3119 
3120 	switch (opt) {
3121 	case TIPC_IMPORTANCE:
3122 	case TIPC_SRC_DROPPABLE:
3123 	case TIPC_DEST_DROPPABLE:
3124 	case TIPC_CONN_TIMEOUT:
3125 	case TIPC_NODELAY:
3126 		if (ol < sizeof(value))
3127 			return -EINVAL;
3128 		if (get_user(value, (u32 __user *)ov))
3129 			return -EFAULT;
3130 		break;
3131 	case TIPC_GROUP_JOIN:
3132 		if (ol < sizeof(mreq))
3133 			return -EINVAL;
3134 		if (copy_from_user(&mreq, ov, sizeof(mreq)))
3135 			return -EFAULT;
3136 		break;
3137 	default:
3138 		if (ov || ol)
3139 			return -EINVAL;
3140 	}
3141 
3142 	lock_sock(sk);
3143 
3144 	switch (opt) {
3145 	case TIPC_IMPORTANCE:
3146 		res = tsk_set_importance(sk, value);
3147 		break;
3148 	case TIPC_SRC_DROPPABLE:
3149 		if (sock->type != SOCK_STREAM)
3150 			tsk_set_unreliable(tsk, value);
3151 		else
3152 			res = -ENOPROTOOPT;
3153 		break;
3154 	case TIPC_DEST_DROPPABLE:
3155 		tsk_set_unreturnable(tsk, value);
3156 		break;
3157 	case TIPC_CONN_TIMEOUT:
3158 		tipc_sk(sk)->conn_timeout = value;
3159 		break;
3160 	case TIPC_MCAST_BROADCAST:
3161 		tsk->mc_method.rcast = false;
3162 		tsk->mc_method.mandatory = true;
3163 		break;
3164 	case TIPC_MCAST_REPLICAST:
3165 		tsk->mc_method.rcast = true;
3166 		tsk->mc_method.mandatory = true;
3167 		break;
3168 	case TIPC_GROUP_JOIN:
3169 		res = tipc_sk_join(tsk, &mreq);
3170 		break;
3171 	case TIPC_GROUP_LEAVE:
3172 		res = tipc_sk_leave(tsk);
3173 		break;
3174 	case TIPC_NODELAY:
3175 		tsk->nodelay = !!value;
3176 		tsk_set_nagle(tsk);
3177 		break;
3178 	default:
3179 		res = -EINVAL;
3180 	}
3181 
3182 	release_sock(sk);
3183 
3184 	return res;
3185 }
3186 
3187 /**
3188  * tipc_getsockopt - get socket option
3189  * @sock: socket structure
3190  * @lvl: option level
3191  * @opt: option identifier
3192  * @ov: receptacle for option value
3193  * @ol: receptacle for length of option value
3194  *
3195  * For stream sockets only, returns 0 length result for all IPPROTO_TCP options
3196  * (to ease compatibility).
3197  *
3198  * Returns 0 on success, errno otherwise
3199  */
3200 static int tipc_getsockopt(struct socket *sock, int lvl, int opt,
3201 			   char __user *ov, int __user *ol)
3202 {
3203 	struct sock *sk = sock->sk;
3204 	struct tipc_sock *tsk = tipc_sk(sk);
3205 	struct tipc_name_seq seq;
3206 	int len, scope;
3207 	u32 value;
3208 	int res;
3209 
3210 	if ((lvl == IPPROTO_TCP) && (sock->type == SOCK_STREAM))
3211 		return put_user(0, ol);
3212 	if (lvl != SOL_TIPC)
3213 		return -ENOPROTOOPT;
3214 	res = get_user(len, ol);
3215 	if (res)
3216 		return res;
3217 
3218 	lock_sock(sk);
3219 
3220 	switch (opt) {
3221 	case TIPC_IMPORTANCE:
3222 		value = tsk_importance(tsk);
3223 		break;
3224 	case TIPC_SRC_DROPPABLE:
3225 		value = tsk_unreliable(tsk);
3226 		break;
3227 	case TIPC_DEST_DROPPABLE:
3228 		value = tsk_unreturnable(tsk);
3229 		break;
3230 	case TIPC_CONN_TIMEOUT:
3231 		value = tsk->conn_timeout;
3232 		/* no need to set "res", since already 0 at this point */
3233 		break;
3234 	case TIPC_NODE_RECVQ_DEPTH:
3235 		value = 0; /* was tipc_queue_size, now obsolete */
3236 		break;
3237 	case TIPC_SOCK_RECVQ_DEPTH:
3238 		value = skb_queue_len(&sk->sk_receive_queue);
3239 		break;
3240 	case TIPC_SOCK_RECVQ_USED:
3241 		value = sk_rmem_alloc_get(sk);
3242 		break;
3243 	case TIPC_GROUP_JOIN:
3244 		seq.type = 0;
3245 		if (tsk->group)
3246 			tipc_group_self(tsk->group, &seq, &scope);
3247 		value = seq.type;
3248 		break;
3249 	default:
3250 		res = -EINVAL;
3251 	}
3252 
3253 	release_sock(sk);
3254 
3255 	if (res)
3256 		return res;	/* "get" failed */
3257 
3258 	if (len < sizeof(value))
3259 		return -EINVAL;
3260 
3261 	if (copy_to_user(ov, &value, sizeof(value)))
3262 		return -EFAULT;
3263 
3264 	return put_user(sizeof(value), ol);
3265 }
3266 
3267 static int tipc_ioctl(struct socket *sock, unsigned int cmd, unsigned long arg)
3268 {
3269 	struct net *net = sock_net(sock->sk);
3270 	struct tipc_sioc_nodeid_req nr = {0};
3271 	struct tipc_sioc_ln_req lnr;
3272 	void __user *argp = (void __user *)arg;
3273 
3274 	switch (cmd) {
3275 	case SIOCGETLINKNAME:
3276 		if (copy_from_user(&lnr, argp, sizeof(lnr)))
3277 			return -EFAULT;
3278 		if (!tipc_node_get_linkname(net,
3279 					    lnr.bearer_id & 0xffff, lnr.peer,
3280 					    lnr.linkname, TIPC_MAX_LINK_NAME)) {
3281 			if (copy_to_user(argp, &lnr, sizeof(lnr)))
3282 				return -EFAULT;
3283 			return 0;
3284 		}
3285 		return -EADDRNOTAVAIL;
3286 	case SIOCGETNODEID:
3287 		if (copy_from_user(&nr, argp, sizeof(nr)))
3288 			return -EFAULT;
3289 		if (!tipc_node_get_id(net, nr.peer, nr.node_id))
3290 			return -EADDRNOTAVAIL;
3291 		if (copy_to_user(argp, &nr, sizeof(nr)))
3292 			return -EFAULT;
3293 		return 0;
3294 	default:
3295 		return -ENOIOCTLCMD;
3296 	}
3297 }
3298 
3299 static int tipc_socketpair(struct socket *sock1, struct socket *sock2)
3300 {
3301 	struct tipc_sock *tsk2 = tipc_sk(sock2->sk);
3302 	struct tipc_sock *tsk1 = tipc_sk(sock1->sk);
3303 	u32 onode = tipc_own_addr(sock_net(sock1->sk));
3304 
3305 	tsk1->peer.family = AF_TIPC;
3306 	tsk1->peer.addrtype = TIPC_ADDR_ID;
3307 	tsk1->peer.scope = TIPC_NODE_SCOPE;
3308 	tsk1->peer.addr.id.ref = tsk2->portid;
3309 	tsk1->peer.addr.id.node = onode;
3310 	tsk2->peer.family = AF_TIPC;
3311 	tsk2->peer.addrtype = TIPC_ADDR_ID;
3312 	tsk2->peer.scope = TIPC_NODE_SCOPE;
3313 	tsk2->peer.addr.id.ref = tsk1->portid;
3314 	tsk2->peer.addr.id.node = onode;
3315 
3316 	tipc_sk_finish_conn(tsk1, tsk2->portid, onode);
3317 	tipc_sk_finish_conn(tsk2, tsk1->portid, onode);
3318 	return 0;
3319 }
3320 
3321 /* Protocol switches for the various types of TIPC sockets */
3322 
3323 static const struct proto_ops msg_ops = {
3324 	.owner		= THIS_MODULE,
3325 	.family		= AF_TIPC,
3326 	.release	= tipc_release,
3327 	.bind		= tipc_bind,
3328 	.connect	= tipc_connect,
3329 	.socketpair	= tipc_socketpair,
3330 	.accept		= sock_no_accept,
3331 	.getname	= tipc_getname,
3332 	.poll		= tipc_poll,
3333 	.ioctl		= tipc_ioctl,
3334 	.listen		= sock_no_listen,
3335 	.shutdown	= tipc_shutdown,
3336 	.setsockopt	= tipc_setsockopt,
3337 	.getsockopt	= tipc_getsockopt,
3338 	.sendmsg	= tipc_sendmsg,
3339 	.recvmsg	= tipc_recvmsg,
3340 	.mmap		= sock_no_mmap,
3341 	.sendpage	= sock_no_sendpage
3342 };
3343 
3344 static const struct proto_ops packet_ops = {
3345 	.owner		= THIS_MODULE,
3346 	.family		= AF_TIPC,
3347 	.release	= tipc_release,
3348 	.bind		= tipc_bind,
3349 	.connect	= tipc_connect,
3350 	.socketpair	= tipc_socketpair,
3351 	.accept		= tipc_accept,
3352 	.getname	= tipc_getname,
3353 	.poll		= tipc_poll,
3354 	.ioctl		= tipc_ioctl,
3355 	.listen		= tipc_listen,
3356 	.shutdown	= tipc_shutdown,
3357 	.setsockopt	= tipc_setsockopt,
3358 	.getsockopt	= tipc_getsockopt,
3359 	.sendmsg	= tipc_send_packet,
3360 	.recvmsg	= tipc_recvmsg,
3361 	.mmap		= sock_no_mmap,
3362 	.sendpage	= sock_no_sendpage
3363 };
3364 
3365 static const struct proto_ops stream_ops = {
3366 	.owner		= THIS_MODULE,
3367 	.family		= AF_TIPC,
3368 	.release	= tipc_release,
3369 	.bind		= tipc_bind,
3370 	.connect	= tipc_connect,
3371 	.socketpair	= tipc_socketpair,
3372 	.accept		= tipc_accept,
3373 	.getname	= tipc_getname,
3374 	.poll		= tipc_poll,
3375 	.ioctl		= tipc_ioctl,
3376 	.listen		= tipc_listen,
3377 	.shutdown	= tipc_shutdown,
3378 	.setsockopt	= tipc_setsockopt,
3379 	.getsockopt	= tipc_getsockopt,
3380 	.sendmsg	= tipc_sendstream,
3381 	.recvmsg	= tipc_recvstream,
3382 	.mmap		= sock_no_mmap,
3383 	.sendpage	= sock_no_sendpage
3384 };
3385 
3386 static const struct net_proto_family tipc_family_ops = {
3387 	.owner		= THIS_MODULE,
3388 	.family		= AF_TIPC,
3389 	.create		= tipc_sk_create
3390 };
3391 
3392 static struct proto tipc_proto = {
3393 	.name		= "TIPC",
3394 	.owner		= THIS_MODULE,
3395 	.obj_size	= sizeof(struct tipc_sock),
3396 	.sysctl_rmem	= sysctl_tipc_rmem
3397 };
3398 
3399 /**
3400  * tipc_socket_init - initialize TIPC socket interface
3401  *
3402  * Returns 0 on success, errno otherwise
3403  */
3404 int tipc_socket_init(void)
3405 {
3406 	int res;
3407 
3408 	res = proto_register(&tipc_proto, 1);
3409 	if (res) {
3410 		pr_err("Failed to register TIPC protocol type\n");
3411 		goto out;
3412 	}
3413 
3414 	res = sock_register(&tipc_family_ops);
3415 	if (res) {
3416 		pr_err("Failed to register TIPC socket type\n");
3417 		proto_unregister(&tipc_proto);
3418 		goto out;
3419 	}
3420  out:
3421 	return res;
3422 }
3423 
3424 /**
3425  * tipc_socket_stop - stop TIPC socket interface
3426  */
3427 void tipc_socket_stop(void)
3428 {
3429 	sock_unregister(tipc_family_ops.family);
3430 	proto_unregister(&tipc_proto);
3431 }
3432 
3433 /* Caller should hold socket lock for the passed tipc socket. */
3434 static int __tipc_nl_add_sk_con(struct sk_buff *skb, struct tipc_sock *tsk)
3435 {
3436 	u32 peer_node;
3437 	u32 peer_port;
3438 	struct nlattr *nest;
3439 
3440 	peer_node = tsk_peer_node(tsk);
3441 	peer_port = tsk_peer_port(tsk);
3442 
3443 	nest = nla_nest_start_noflag(skb, TIPC_NLA_SOCK_CON);
3444 	if (!nest)
3445 		return -EMSGSIZE;
3446 
3447 	if (nla_put_u32(skb, TIPC_NLA_CON_NODE, peer_node))
3448 		goto msg_full;
3449 	if (nla_put_u32(skb, TIPC_NLA_CON_SOCK, peer_port))
3450 		goto msg_full;
3451 
3452 	if (tsk->conn_type != 0) {
3453 		if (nla_put_flag(skb, TIPC_NLA_CON_FLAG))
3454 			goto msg_full;
3455 		if (nla_put_u32(skb, TIPC_NLA_CON_TYPE, tsk->conn_type))
3456 			goto msg_full;
3457 		if (nla_put_u32(skb, TIPC_NLA_CON_INST, tsk->conn_instance))
3458 			goto msg_full;
3459 	}
3460 	nla_nest_end(skb, nest);
3461 
3462 	return 0;
3463 
3464 msg_full:
3465 	nla_nest_cancel(skb, nest);
3466 
3467 	return -EMSGSIZE;
3468 }
3469 
3470 static int __tipc_nl_add_sk_info(struct sk_buff *skb, struct tipc_sock
3471 			  *tsk)
3472 {
3473 	struct net *net = sock_net(skb->sk);
3474 	struct sock *sk = &tsk->sk;
3475 
3476 	if (nla_put_u32(skb, TIPC_NLA_SOCK_REF, tsk->portid) ||
3477 	    nla_put_u32(skb, TIPC_NLA_SOCK_ADDR, tipc_own_addr(net)))
3478 		return -EMSGSIZE;
3479 
3480 	if (tipc_sk_connected(sk)) {
3481 		if (__tipc_nl_add_sk_con(skb, tsk))
3482 			return -EMSGSIZE;
3483 	} else if (!list_empty(&tsk->publications)) {
3484 		if (nla_put_flag(skb, TIPC_NLA_SOCK_HAS_PUBL))
3485 			return -EMSGSIZE;
3486 	}
3487 	return 0;
3488 }
3489 
3490 /* Caller should hold socket lock for the passed tipc socket. */
3491 static int __tipc_nl_add_sk(struct sk_buff *skb, struct netlink_callback *cb,
3492 			    struct tipc_sock *tsk)
3493 {
3494 	struct nlattr *attrs;
3495 	void *hdr;
3496 
3497 	hdr = genlmsg_put(skb, NETLINK_CB(cb->skb).portid, cb->nlh->nlmsg_seq,
3498 			  &tipc_genl_family, NLM_F_MULTI, TIPC_NL_SOCK_GET);
3499 	if (!hdr)
3500 		goto msg_cancel;
3501 
3502 	attrs = nla_nest_start_noflag(skb, TIPC_NLA_SOCK);
3503 	if (!attrs)
3504 		goto genlmsg_cancel;
3505 
3506 	if (__tipc_nl_add_sk_info(skb, tsk))
3507 		goto attr_msg_cancel;
3508 
3509 	nla_nest_end(skb, attrs);
3510 	genlmsg_end(skb, hdr);
3511 
3512 	return 0;
3513 
3514 attr_msg_cancel:
3515 	nla_nest_cancel(skb, attrs);
3516 genlmsg_cancel:
3517 	genlmsg_cancel(skb, hdr);
3518 msg_cancel:
3519 	return -EMSGSIZE;
3520 }
3521 
3522 int tipc_nl_sk_walk(struct sk_buff *skb, struct netlink_callback *cb,
3523 		    int (*skb_handler)(struct sk_buff *skb,
3524 				       struct netlink_callback *cb,
3525 				       struct tipc_sock *tsk))
3526 {
3527 	struct rhashtable_iter *iter = (void *)cb->args[4];
3528 	struct tipc_sock *tsk;
3529 	int err;
3530 
3531 	rhashtable_walk_start(iter);
3532 	while ((tsk = rhashtable_walk_next(iter)) != NULL) {
3533 		if (IS_ERR(tsk)) {
3534 			err = PTR_ERR(tsk);
3535 			if (err == -EAGAIN) {
3536 				err = 0;
3537 				continue;
3538 			}
3539 			break;
3540 		}
3541 
3542 		sock_hold(&tsk->sk);
3543 		rhashtable_walk_stop(iter);
3544 		lock_sock(&tsk->sk);
3545 		err = skb_handler(skb, cb, tsk);
3546 		if (err) {
3547 			release_sock(&tsk->sk);
3548 			sock_put(&tsk->sk);
3549 			goto out;
3550 		}
3551 		release_sock(&tsk->sk);
3552 		rhashtable_walk_start(iter);
3553 		sock_put(&tsk->sk);
3554 	}
3555 	rhashtable_walk_stop(iter);
3556 out:
3557 	return skb->len;
3558 }
3559 EXPORT_SYMBOL(tipc_nl_sk_walk);
3560 
3561 int tipc_dump_start(struct netlink_callback *cb)
3562 {
3563 	return __tipc_dump_start(cb, sock_net(cb->skb->sk));
3564 }
3565 EXPORT_SYMBOL(tipc_dump_start);
3566 
3567 int __tipc_dump_start(struct netlink_callback *cb, struct net *net)
3568 {
3569 	/* tipc_nl_name_table_dump() uses cb->args[0...3]. */
3570 	struct rhashtable_iter *iter = (void *)cb->args[4];
3571 	struct tipc_net *tn = tipc_net(net);
3572 
3573 	if (!iter) {
3574 		iter = kmalloc(sizeof(*iter), GFP_KERNEL);
3575 		if (!iter)
3576 			return -ENOMEM;
3577 
3578 		cb->args[4] = (long)iter;
3579 	}
3580 
3581 	rhashtable_walk_enter(&tn->sk_rht, iter);
3582 	return 0;
3583 }
3584 
3585 int tipc_dump_done(struct netlink_callback *cb)
3586 {
3587 	struct rhashtable_iter *hti = (void *)cb->args[4];
3588 
3589 	rhashtable_walk_exit(hti);
3590 	kfree(hti);
3591 	return 0;
3592 }
3593 EXPORT_SYMBOL(tipc_dump_done);
3594 
3595 int tipc_sk_fill_sock_diag(struct sk_buff *skb, struct netlink_callback *cb,
3596 			   struct tipc_sock *tsk, u32 sk_filter_state,
3597 			   u64 (*tipc_diag_gen_cookie)(struct sock *sk))
3598 {
3599 	struct sock *sk = &tsk->sk;
3600 	struct nlattr *attrs;
3601 	struct nlattr *stat;
3602 
3603 	/*filter response w.r.t sk_state*/
3604 	if (!(sk_filter_state & (1 << sk->sk_state)))
3605 		return 0;
3606 
3607 	attrs = nla_nest_start_noflag(skb, TIPC_NLA_SOCK);
3608 	if (!attrs)
3609 		goto msg_cancel;
3610 
3611 	if (__tipc_nl_add_sk_info(skb, tsk))
3612 		goto attr_msg_cancel;
3613 
3614 	if (nla_put_u32(skb, TIPC_NLA_SOCK_TYPE, (u32)sk->sk_type) ||
3615 	    nla_put_u32(skb, TIPC_NLA_SOCK_TIPC_STATE, (u32)sk->sk_state) ||
3616 	    nla_put_u32(skb, TIPC_NLA_SOCK_INO, sock_i_ino(sk)) ||
3617 	    nla_put_u32(skb, TIPC_NLA_SOCK_UID,
3618 			from_kuid_munged(sk_user_ns(NETLINK_CB(cb->skb).sk),
3619 					 sock_i_uid(sk))) ||
3620 	    nla_put_u64_64bit(skb, TIPC_NLA_SOCK_COOKIE,
3621 			      tipc_diag_gen_cookie(sk),
3622 			      TIPC_NLA_SOCK_PAD))
3623 		goto attr_msg_cancel;
3624 
3625 	stat = nla_nest_start_noflag(skb, TIPC_NLA_SOCK_STAT);
3626 	if (!stat)
3627 		goto attr_msg_cancel;
3628 
3629 	if (nla_put_u32(skb, TIPC_NLA_SOCK_STAT_RCVQ,
3630 			skb_queue_len(&sk->sk_receive_queue)) ||
3631 	    nla_put_u32(skb, TIPC_NLA_SOCK_STAT_SENDQ,
3632 			skb_queue_len(&sk->sk_write_queue)) ||
3633 	    nla_put_u32(skb, TIPC_NLA_SOCK_STAT_DROP,
3634 			atomic_read(&sk->sk_drops)))
3635 		goto stat_msg_cancel;
3636 
3637 	if (tsk->cong_link_cnt &&
3638 	    nla_put_flag(skb, TIPC_NLA_SOCK_STAT_LINK_CONG))
3639 		goto stat_msg_cancel;
3640 
3641 	if (tsk_conn_cong(tsk) &&
3642 	    nla_put_flag(skb, TIPC_NLA_SOCK_STAT_CONN_CONG))
3643 		goto stat_msg_cancel;
3644 
3645 	nla_nest_end(skb, stat);
3646 
3647 	if (tsk->group)
3648 		if (tipc_group_fill_sock_diag(tsk->group, skb))
3649 			goto stat_msg_cancel;
3650 
3651 	nla_nest_end(skb, attrs);
3652 
3653 	return 0;
3654 
3655 stat_msg_cancel:
3656 	nla_nest_cancel(skb, stat);
3657 attr_msg_cancel:
3658 	nla_nest_cancel(skb, attrs);
3659 msg_cancel:
3660 	return -EMSGSIZE;
3661 }
3662 EXPORT_SYMBOL(tipc_sk_fill_sock_diag);
3663 
3664 int tipc_nl_sk_dump(struct sk_buff *skb, struct netlink_callback *cb)
3665 {
3666 	return tipc_nl_sk_walk(skb, cb, __tipc_nl_add_sk);
3667 }
3668 
3669 /* Caller should hold socket lock for the passed tipc socket. */
3670 static int __tipc_nl_add_sk_publ(struct sk_buff *skb,
3671 				 struct netlink_callback *cb,
3672 				 struct publication *publ)
3673 {
3674 	void *hdr;
3675 	struct nlattr *attrs;
3676 
3677 	hdr = genlmsg_put(skb, NETLINK_CB(cb->skb).portid, cb->nlh->nlmsg_seq,
3678 			  &tipc_genl_family, NLM_F_MULTI, TIPC_NL_PUBL_GET);
3679 	if (!hdr)
3680 		goto msg_cancel;
3681 
3682 	attrs = nla_nest_start_noflag(skb, TIPC_NLA_PUBL);
3683 	if (!attrs)
3684 		goto genlmsg_cancel;
3685 
3686 	if (nla_put_u32(skb, TIPC_NLA_PUBL_KEY, publ->key))
3687 		goto attr_msg_cancel;
3688 	if (nla_put_u32(skb, TIPC_NLA_PUBL_TYPE, publ->type))
3689 		goto attr_msg_cancel;
3690 	if (nla_put_u32(skb, TIPC_NLA_PUBL_LOWER, publ->lower))
3691 		goto attr_msg_cancel;
3692 	if (nla_put_u32(skb, TIPC_NLA_PUBL_UPPER, publ->upper))
3693 		goto attr_msg_cancel;
3694 
3695 	nla_nest_end(skb, attrs);
3696 	genlmsg_end(skb, hdr);
3697 
3698 	return 0;
3699 
3700 attr_msg_cancel:
3701 	nla_nest_cancel(skb, attrs);
3702 genlmsg_cancel:
3703 	genlmsg_cancel(skb, hdr);
3704 msg_cancel:
3705 	return -EMSGSIZE;
3706 }
3707 
3708 /* Caller should hold socket lock for the passed tipc socket. */
3709 static int __tipc_nl_list_sk_publ(struct sk_buff *skb,
3710 				  struct netlink_callback *cb,
3711 				  struct tipc_sock *tsk, u32 *last_publ)
3712 {
3713 	int err;
3714 	struct publication *p;
3715 
3716 	if (*last_publ) {
3717 		list_for_each_entry(p, &tsk->publications, binding_sock) {
3718 			if (p->key == *last_publ)
3719 				break;
3720 		}
3721 		if (p->key != *last_publ) {
3722 			/* We never set seq or call nl_dump_check_consistent()
3723 			 * this means that setting prev_seq here will cause the
3724 			 * consistence check to fail in the netlink callback
3725 			 * handler. Resulting in the last NLMSG_DONE message
3726 			 * having the NLM_F_DUMP_INTR flag set.
3727 			 */
3728 			cb->prev_seq = 1;
3729 			*last_publ = 0;
3730 			return -EPIPE;
3731 		}
3732 	} else {
3733 		p = list_first_entry(&tsk->publications, struct publication,
3734 				     binding_sock);
3735 	}
3736 
3737 	list_for_each_entry_from(p, &tsk->publications, binding_sock) {
3738 		err = __tipc_nl_add_sk_publ(skb, cb, p);
3739 		if (err) {
3740 			*last_publ = p->key;
3741 			return err;
3742 		}
3743 	}
3744 	*last_publ = 0;
3745 
3746 	return 0;
3747 }
3748 
3749 int tipc_nl_publ_dump(struct sk_buff *skb, struct netlink_callback *cb)
3750 {
3751 	int err;
3752 	u32 tsk_portid = cb->args[0];
3753 	u32 last_publ = cb->args[1];
3754 	u32 done = cb->args[2];
3755 	struct net *net = sock_net(skb->sk);
3756 	struct tipc_sock *tsk;
3757 
3758 	if (!tsk_portid) {
3759 		struct nlattr **attrs = genl_dumpit_info(cb)->attrs;
3760 		struct nlattr *sock[TIPC_NLA_SOCK_MAX + 1];
3761 
3762 		if (!attrs[TIPC_NLA_SOCK])
3763 			return -EINVAL;
3764 
3765 		err = nla_parse_nested_deprecated(sock, TIPC_NLA_SOCK_MAX,
3766 						  attrs[TIPC_NLA_SOCK],
3767 						  tipc_nl_sock_policy, NULL);
3768 		if (err)
3769 			return err;
3770 
3771 		if (!sock[TIPC_NLA_SOCK_REF])
3772 			return -EINVAL;
3773 
3774 		tsk_portid = nla_get_u32(sock[TIPC_NLA_SOCK_REF]);
3775 	}
3776 
3777 	if (done)
3778 		return 0;
3779 
3780 	tsk = tipc_sk_lookup(net, tsk_portid);
3781 	if (!tsk)
3782 		return -EINVAL;
3783 
3784 	lock_sock(&tsk->sk);
3785 	err = __tipc_nl_list_sk_publ(skb, cb, tsk, &last_publ);
3786 	if (!err)
3787 		done = 1;
3788 	release_sock(&tsk->sk);
3789 	sock_put(&tsk->sk);
3790 
3791 	cb->args[0] = tsk_portid;
3792 	cb->args[1] = last_publ;
3793 	cb->args[2] = done;
3794 
3795 	return skb->len;
3796 }
3797 
3798 /**
3799  * tipc_sk_filtering - check if a socket should be traced
3800  * @sk: the socket to be examined
3801  * @sysctl_tipc_sk_filter[]: the socket tuple for filtering,
3802  *  (portid, sock type, name type, name lower, name upper)
3803  *
3804  * Returns true if the socket meets the socket tuple data
3805  * (value 0 = 'any') or when there is no tuple set (all = 0),
3806  * otherwise false
3807  */
3808 bool tipc_sk_filtering(struct sock *sk)
3809 {
3810 	struct tipc_sock *tsk;
3811 	struct publication *p;
3812 	u32 _port, _sktype, _type, _lower, _upper;
3813 	u32 type = 0, lower = 0, upper = 0;
3814 
3815 	if (!sk)
3816 		return true;
3817 
3818 	tsk = tipc_sk(sk);
3819 
3820 	_port = sysctl_tipc_sk_filter[0];
3821 	_sktype = sysctl_tipc_sk_filter[1];
3822 	_type = sysctl_tipc_sk_filter[2];
3823 	_lower = sysctl_tipc_sk_filter[3];
3824 	_upper = sysctl_tipc_sk_filter[4];
3825 
3826 	if (!_port && !_sktype && !_type && !_lower && !_upper)
3827 		return true;
3828 
3829 	if (_port)
3830 		return (_port == tsk->portid);
3831 
3832 	if (_sktype && _sktype != sk->sk_type)
3833 		return false;
3834 
3835 	if (tsk->published) {
3836 		p = list_first_entry_or_null(&tsk->publications,
3837 					     struct publication, binding_sock);
3838 		if (p) {
3839 			type = p->type;
3840 			lower = p->lower;
3841 			upper = p->upper;
3842 		}
3843 	}
3844 
3845 	if (!tipc_sk_type_connectionless(sk)) {
3846 		type = tsk->conn_type;
3847 		lower = tsk->conn_instance;
3848 		upper = tsk->conn_instance;
3849 	}
3850 
3851 	if ((_type && _type != type) || (_lower && _lower != lower) ||
3852 	    (_upper && _upper != upper))
3853 		return false;
3854 
3855 	return true;
3856 }
3857 
3858 u32 tipc_sock_get_portid(struct sock *sk)
3859 {
3860 	return (sk) ? (tipc_sk(sk))->portid : 0;
3861 }
3862 
3863 /**
3864  * tipc_sk_overlimit1 - check if socket rx queue is about to be overloaded,
3865  *			both the rcv and backlog queues are considered
3866  * @sk: tipc sk to be checked
3867  * @skb: tipc msg to be checked
3868  *
3869  * Returns true if the socket rx queue allocation is > 90%, otherwise false
3870  */
3871 
3872 bool tipc_sk_overlimit1(struct sock *sk, struct sk_buff *skb)
3873 {
3874 	atomic_t *dcnt = &tipc_sk(sk)->dupl_rcvcnt;
3875 	unsigned int lim = rcvbuf_limit(sk, skb) + atomic_read(dcnt);
3876 	unsigned int qsize = sk->sk_backlog.len + sk_rmem_alloc_get(sk);
3877 
3878 	return (qsize > lim * 90 / 100);
3879 }
3880 
3881 /**
3882  * tipc_sk_overlimit2 - check if socket rx queue is about to be overloaded,
3883  *			only the rcv queue is considered
3884  * @sk: tipc sk to be checked
3885  * @skb: tipc msg to be checked
3886  *
3887  * Returns true if the socket rx queue allocation is > 90%, otherwise false
3888  */
3889 
3890 bool tipc_sk_overlimit2(struct sock *sk, struct sk_buff *skb)
3891 {
3892 	unsigned int lim = rcvbuf_limit(sk, skb);
3893 	unsigned int qsize = sk_rmem_alloc_get(sk);
3894 
3895 	return (qsize > lim * 90 / 100);
3896 }
3897 
3898 /**
3899  * tipc_sk_dump - dump TIPC socket
3900  * @sk: tipc sk to be dumped
3901  * @dqueues: bitmask to decide if any socket queue to be dumped?
3902  *           - TIPC_DUMP_NONE: don't dump socket queues
3903  *           - TIPC_DUMP_SK_SNDQ: dump socket send queue
3904  *           - TIPC_DUMP_SK_RCVQ: dump socket rcv queue
3905  *           - TIPC_DUMP_SK_BKLGQ: dump socket backlog queue
3906  *           - TIPC_DUMP_ALL: dump all the socket queues above
3907  * @buf: returned buffer of dump data in format
3908  */
3909 int tipc_sk_dump(struct sock *sk, u16 dqueues, char *buf)
3910 {
3911 	int i = 0;
3912 	size_t sz = (dqueues) ? SK_LMAX : SK_LMIN;
3913 	struct tipc_sock *tsk;
3914 	struct publication *p;
3915 	bool tsk_connected;
3916 
3917 	if (!sk) {
3918 		i += scnprintf(buf, sz, "sk data: (null)\n");
3919 		return i;
3920 	}
3921 
3922 	tsk = tipc_sk(sk);
3923 	tsk_connected = !tipc_sk_type_connectionless(sk);
3924 
3925 	i += scnprintf(buf, sz, "sk data: %u", sk->sk_type);
3926 	i += scnprintf(buf + i, sz - i, " %d", sk->sk_state);
3927 	i += scnprintf(buf + i, sz - i, " %x", tsk_own_node(tsk));
3928 	i += scnprintf(buf + i, sz - i, " %u", tsk->portid);
3929 	i += scnprintf(buf + i, sz - i, " | %u", tsk_connected);
3930 	if (tsk_connected) {
3931 		i += scnprintf(buf + i, sz - i, " %x", tsk_peer_node(tsk));
3932 		i += scnprintf(buf + i, sz - i, " %u", tsk_peer_port(tsk));
3933 		i += scnprintf(buf + i, sz - i, " %u", tsk->conn_type);
3934 		i += scnprintf(buf + i, sz - i, " %u", tsk->conn_instance);
3935 	}
3936 	i += scnprintf(buf + i, sz - i, " | %u", tsk->published);
3937 	if (tsk->published) {
3938 		p = list_first_entry_or_null(&tsk->publications,
3939 					     struct publication, binding_sock);
3940 		i += scnprintf(buf + i, sz - i, " %u", (p) ? p->type : 0);
3941 		i += scnprintf(buf + i, sz - i, " %u", (p) ? p->lower : 0);
3942 		i += scnprintf(buf + i, sz - i, " %u", (p) ? p->upper : 0);
3943 	}
3944 	i += scnprintf(buf + i, sz - i, " | %u", tsk->snd_win);
3945 	i += scnprintf(buf + i, sz - i, " %u", tsk->rcv_win);
3946 	i += scnprintf(buf + i, sz - i, " %u", tsk->max_pkt);
3947 	i += scnprintf(buf + i, sz - i, " %x", tsk->peer_caps);
3948 	i += scnprintf(buf + i, sz - i, " %u", tsk->cong_link_cnt);
3949 	i += scnprintf(buf + i, sz - i, " %u", tsk->snt_unacked);
3950 	i += scnprintf(buf + i, sz - i, " %u", tsk->rcv_unacked);
3951 	i += scnprintf(buf + i, sz - i, " %u", atomic_read(&tsk->dupl_rcvcnt));
3952 	i += scnprintf(buf + i, sz - i, " %u", sk->sk_shutdown);
3953 	i += scnprintf(buf + i, sz - i, " | %d", sk_wmem_alloc_get(sk));
3954 	i += scnprintf(buf + i, sz - i, " %d", sk->sk_sndbuf);
3955 	i += scnprintf(buf + i, sz - i, " | %d", sk_rmem_alloc_get(sk));
3956 	i += scnprintf(buf + i, sz - i, " %d", sk->sk_rcvbuf);
3957 	i += scnprintf(buf + i, sz - i, " | %d\n", READ_ONCE(sk->sk_backlog.len));
3958 
3959 	if (dqueues & TIPC_DUMP_SK_SNDQ) {
3960 		i += scnprintf(buf + i, sz - i, "sk_write_queue: ");
3961 		i += tipc_list_dump(&sk->sk_write_queue, false, buf + i);
3962 	}
3963 
3964 	if (dqueues & TIPC_DUMP_SK_RCVQ) {
3965 		i += scnprintf(buf + i, sz - i, "sk_receive_queue: ");
3966 		i += tipc_list_dump(&sk->sk_receive_queue, false, buf + i);
3967 	}
3968 
3969 	if (dqueues & TIPC_DUMP_SK_BKLGQ) {
3970 		i += scnprintf(buf + i, sz - i, "sk_backlog:\n  head ");
3971 		i += tipc_skb_dump(sk->sk_backlog.head, false, buf + i);
3972 		if (sk->sk_backlog.tail != sk->sk_backlog.head) {
3973 			i += scnprintf(buf + i, sz - i, "  tail ");
3974 			i += tipc_skb_dump(sk->sk_backlog.tail, false,
3975 					   buf + i);
3976 		}
3977 	}
3978 
3979 	return i;
3980 }
3981