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