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