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