OSDN Git Service

net_sched: fix an OOB access in cls_tcindex
[sagit-ice-cold/kernel_xiaomi_msm8998.git] / net / tipc / socket.c
1 /*
2  * net/tipc/socket.c: TIPC socket API
3  *
4  * Copyright (c) 2001-2007, 2012-2015, 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 "core.h"
39 #include "name_table.h"
40 #include "node.h"
41 #include "link.h"
42 #include "name_distr.h"
43 #include "socket.h"
44 #include "bcast.h"
45
46 #define SS_LISTENING            -1      /* socket is listening */
47 #define SS_READY                -2      /* socket is connectionless */
48
49 #define CONN_TIMEOUT_DEFAULT    8000    /* default connect timeout = 8s */
50 #define CONN_PROBING_INTERVAL   msecs_to_jiffies(3600000)  /* [ms] => 1 h */
51 #define TIPC_FWD_MSG            1
52 #define TIPC_CONN_OK            0
53 #define TIPC_CONN_PROBING       1
54 #define TIPC_MAX_PORT           0xffffffff
55 #define TIPC_MIN_PORT           1
56
57 /**
58  * struct tipc_sock - TIPC socket structure
59  * @sk: socket - interacts with 'port' and with user via the socket API
60  * @connected: non-zero if port is currently connected to a peer port
61  * @conn_type: TIPC type used when connection was established
62  * @conn_instance: TIPC instance used when connection was established
63  * @published: non-zero if port has one or more associated names
64  * @max_pkt: maximum packet size "hint" used when building messages sent by port
65  * @portid: unique port identity in TIPC socket hash table
66  * @phdr: preformatted message header used when sending messages
67  * @port_list: adjacent ports in TIPC's global list of ports
68  * @publications: list of publications for port
69  * @pub_count: total # of publications port has made during its lifetime
70  * @probing_state:
71  * @probing_intv:
72  * @conn_timeout: the time we can wait for an unresponded setup request
73  * @dupl_rcvcnt: number of bytes counted twice, in both backlog and rcv queue
74  * @link_cong: non-zero if owner must sleep because of link congestion
75  * @sent_unacked: # messages sent by socket, and not yet acked by peer
76  * @rcv_unacked: # messages read by user, but not yet acked back to peer
77  * @remote: 'connected' peer for dgram/rdm
78  * @node: hash table node
79  * @rcu: rcu struct for tipc_sock
80  */
81 struct tipc_sock {
82         struct sock sk;
83         int connected;
84         u32 conn_type;
85         u32 conn_instance;
86         int published;
87         u32 max_pkt;
88         u32 portid;
89         struct tipc_msg phdr;
90         struct list_head sock_list;
91         struct list_head publications;
92         u32 pub_count;
93         u32 probing_state;
94         unsigned long probing_intv;
95         uint conn_timeout;
96         atomic_t dupl_rcvcnt;
97         bool link_cong;
98         uint sent_unacked;
99         uint rcv_unacked;
100         struct sockaddr_tipc remote;
101         struct rhash_head node;
102         struct rcu_head rcu;
103 };
104
105 static int tipc_backlog_rcv(struct sock *sk, struct sk_buff *skb);
106 static void tipc_data_ready(struct sock *sk);
107 static void tipc_write_space(struct sock *sk);
108 static void tipc_sock_destruct(struct sock *sk);
109 static int tipc_release(struct socket *sock);
110 static int tipc_accept(struct socket *sock, struct socket *new_sock, int flags);
111 static int tipc_wait_for_sndmsg(struct socket *sock, long *timeo_p);
112 static void tipc_sk_timeout(unsigned long data);
113 static int tipc_sk_publish(struct tipc_sock *tsk, uint scope,
114                            struct tipc_name_seq const *seq);
115 static int tipc_sk_withdraw(struct tipc_sock *tsk, uint scope,
116                             struct tipc_name_seq const *seq);
117 static struct tipc_sock *tipc_sk_lookup(struct net *net, u32 portid);
118 static int tipc_sk_insert(struct tipc_sock *tsk);
119 static void tipc_sk_remove(struct tipc_sock *tsk);
120 static int __tipc_send_stream(struct socket *sock, struct msghdr *m,
121                               size_t dsz);
122 static int __tipc_sendmsg(struct socket *sock, struct msghdr *m, size_t dsz);
123
124 static const struct proto_ops packet_ops;
125 static const struct proto_ops stream_ops;
126 static const struct proto_ops msg_ops;
127 static struct proto tipc_proto;
128
129 static const struct nla_policy tipc_nl_sock_policy[TIPC_NLA_SOCK_MAX + 1] = {
130         [TIPC_NLA_SOCK_UNSPEC]          = { .type = NLA_UNSPEC },
131         [TIPC_NLA_SOCK_ADDR]            = { .type = NLA_U32 },
132         [TIPC_NLA_SOCK_REF]             = { .type = NLA_U32 },
133         [TIPC_NLA_SOCK_CON]             = { .type = NLA_NESTED },
134         [TIPC_NLA_SOCK_HAS_PUBL]        = { .type = NLA_FLAG }
135 };
136
137 static const struct rhashtable_params tsk_rht_params;
138
139 /*
140  * Revised TIPC socket locking policy:
141  *
142  * Most socket operations take the standard socket lock when they start
143  * and hold it until they finish (or until they need to sleep).  Acquiring
144  * this lock grants the owner exclusive access to the fields of the socket
145  * data structures, with the exception of the backlog queue.  A few socket
146  * operations can be done without taking the socket lock because they only
147  * read socket information that never changes during the life of the socket.
148  *
149  * Socket operations may acquire the lock for the associated TIPC port if they
150  * need to perform an operation on the port.  If any routine needs to acquire
151  * both the socket lock and the port lock it must take the socket lock first
152  * to avoid the risk of deadlock.
153  *
154  * The dispatcher handling incoming messages cannot grab the socket lock in
155  * the standard fashion, since invoked it runs at the BH level and cannot block.
156  * Instead, it checks to see if the socket lock is currently owned by someone,
157  * and either handles the message itself or adds it to the socket's backlog
158  * queue; in the latter case the queued message is processed once the process
159  * owning the socket lock releases it.
160  *
161  * NOTE: Releasing the socket lock while an operation is sleeping overcomes
162  * the problem of a blocked socket operation preventing any other operations
163  * from occurring.  However, applications must be careful if they have
164  * multiple threads trying to send (or receive) on the same socket, as these
165  * operations might interfere with each other.  For example, doing a connect
166  * and a receive at the same time might allow the receive to consume the
167  * ACK message meant for the connect.  While additional work could be done
168  * to try and overcome this, it doesn't seem to be worthwhile at the present.
169  *
170  * NOTE: Releasing the socket lock while an operation is sleeping also ensures
171  * that another operation that must be performed in a non-blocking manner is
172  * not delayed for very long because the lock has already been taken.
173  *
174  * NOTE: This code assumes that certain fields of a port/socket pair are
175  * constant over its lifetime; such fields can be examined without taking
176  * the socket lock and/or port lock, and do not need to be re-read even
177  * after resuming processing after waiting.  These fields include:
178  *   - socket type
179  *   - pointer to socket sk structure (aka tipc_sock structure)
180  *   - pointer to port structure
181  *   - port reference
182  */
183
184 static u32 tsk_own_node(struct tipc_sock *tsk)
185 {
186         return msg_prevnode(&tsk->phdr);
187 }
188
189 static u32 tsk_peer_node(struct tipc_sock *tsk)
190 {
191         return msg_destnode(&tsk->phdr);
192 }
193
194 static u32 tsk_peer_port(struct tipc_sock *tsk)
195 {
196         return msg_destport(&tsk->phdr);
197 }
198
199 static  bool tsk_unreliable(struct tipc_sock *tsk)
200 {
201         return msg_src_droppable(&tsk->phdr) != 0;
202 }
203
204 static void tsk_set_unreliable(struct tipc_sock *tsk, bool unreliable)
205 {
206         msg_set_src_droppable(&tsk->phdr, unreliable ? 1 : 0);
207 }
208
209 static bool tsk_unreturnable(struct tipc_sock *tsk)
210 {
211         return msg_dest_droppable(&tsk->phdr) != 0;
212 }
213
214 static void tsk_set_unreturnable(struct tipc_sock *tsk, bool unreturnable)
215 {
216         msg_set_dest_droppable(&tsk->phdr, unreturnable ? 1 : 0);
217 }
218
219 static int tsk_importance(struct tipc_sock *tsk)
220 {
221         return msg_importance(&tsk->phdr);
222 }
223
224 static int tsk_set_importance(struct tipc_sock *tsk, int imp)
225 {
226         if (imp > TIPC_CRITICAL_IMPORTANCE)
227                 return -EINVAL;
228         msg_set_importance(&tsk->phdr, (u32)imp);
229         return 0;
230 }
231
232 static struct tipc_sock *tipc_sk(const struct sock *sk)
233 {
234         return container_of(sk, struct tipc_sock, sk);
235 }
236
237 static int tsk_conn_cong(struct tipc_sock *tsk)
238 {
239         return tsk->sent_unacked >= TIPC_FLOWCTRL_WIN;
240 }
241
242 /**
243  * tsk_advance_rx_queue - discard first buffer in socket receive queue
244  *
245  * Caller must hold socket lock
246  */
247 static void tsk_advance_rx_queue(struct sock *sk)
248 {
249         kfree_skb(__skb_dequeue(&sk->sk_receive_queue));
250 }
251
252 /* tipc_sk_respond() : send response message back to sender
253  */
254 static void tipc_sk_respond(struct sock *sk, struct sk_buff *skb, int err)
255 {
256         u32 selector;
257         u32 dnode;
258         u32 onode = tipc_own_addr(sock_net(sk));
259
260         if (!tipc_msg_reverse(onode, &skb, err))
261                 return;
262
263         dnode = msg_destnode(buf_msg(skb));
264         selector = msg_origport(buf_msg(skb));
265         tipc_node_xmit_skb(sock_net(sk), skb, dnode, selector);
266 }
267
268 /**
269  * tsk_rej_rx_queue - reject all buffers in socket receive queue
270  *
271  * Caller must hold socket lock
272  */
273 static void tsk_rej_rx_queue(struct sock *sk)
274 {
275         struct sk_buff *skb;
276
277         while ((skb = __skb_dequeue(&sk->sk_receive_queue)))
278                 tipc_sk_respond(sk, skb, TIPC_ERR_NO_PORT);
279 }
280
281 /* tsk_peer_msg - verify if message was sent by connected port's peer
282  *
283  * Handles cases where the node's network address has changed from
284  * the default of <0.0.0> to its configured setting.
285  */
286 static bool tsk_peer_msg(struct tipc_sock *tsk, struct tipc_msg *msg)
287 {
288         struct tipc_net *tn = net_generic(sock_net(&tsk->sk), tipc_net_id);
289         u32 peer_port = tsk_peer_port(tsk);
290         u32 orig_node;
291         u32 peer_node;
292
293         if (unlikely(!tsk->connected))
294                 return false;
295
296         if (unlikely(msg_origport(msg) != peer_port))
297                 return false;
298
299         orig_node = msg_orignode(msg);
300         peer_node = tsk_peer_node(tsk);
301
302         if (likely(orig_node == peer_node))
303                 return true;
304
305         if (!orig_node && (peer_node == tn->own_addr))
306                 return true;
307
308         if (!peer_node && (orig_node == tn->own_addr))
309                 return true;
310
311         return false;
312 }
313
314 /**
315  * tipc_sk_create - create a TIPC socket
316  * @net: network namespace (must be default network)
317  * @sock: pre-allocated socket structure
318  * @protocol: protocol indicator (must be 0)
319  * @kern: caused by kernel or by userspace?
320  *
321  * This routine creates additional data structures used by the TIPC socket,
322  * initializes them, and links them together.
323  *
324  * Returns 0 on success, errno otherwise
325  */
326 static int tipc_sk_create(struct net *net, struct socket *sock,
327                           int protocol, int kern)
328 {
329         struct tipc_net *tn;
330         const struct proto_ops *ops;
331         socket_state state;
332         struct sock *sk;
333         struct tipc_sock *tsk;
334         struct tipc_msg *msg;
335
336         /* Validate arguments */
337         if (unlikely(protocol != 0))
338                 return -EPROTONOSUPPORT;
339
340         switch (sock->type) {
341         case SOCK_STREAM:
342                 ops = &stream_ops;
343                 state = SS_UNCONNECTED;
344                 break;
345         case SOCK_SEQPACKET:
346                 ops = &packet_ops;
347                 state = SS_UNCONNECTED;
348                 break;
349         case SOCK_DGRAM:
350         case SOCK_RDM:
351                 ops = &msg_ops;
352                 state = SS_READY;
353                 break;
354         default:
355                 return -EPROTOTYPE;
356         }
357
358         /* Allocate socket's protocol area */
359         sk = sk_alloc(net, AF_TIPC, GFP_KERNEL, &tipc_proto, kern);
360         if (sk == NULL)
361                 return -ENOMEM;
362
363         tsk = tipc_sk(sk);
364         tsk->max_pkt = MAX_PKT_DEFAULT;
365         INIT_LIST_HEAD(&tsk->publications);
366         msg = &tsk->phdr;
367         tn = net_generic(sock_net(sk), tipc_net_id);
368         tipc_msg_init(tn->own_addr, msg, TIPC_LOW_IMPORTANCE, TIPC_NAMED_MSG,
369                       NAMED_H_SIZE, 0);
370
371         /* Finish initializing socket data structures */
372         sock->ops = ops;
373         sock->state = state;
374         sock_init_data(sock, sk);
375         if (tipc_sk_insert(tsk)) {
376                 pr_warn("Socket create failed; port numbrer exhausted\n");
377                 return -EINVAL;
378         }
379         msg_set_origport(msg, tsk->portid);
380         setup_timer(&sk->sk_timer, tipc_sk_timeout, (unsigned long)tsk);
381         sk->sk_backlog_rcv = tipc_backlog_rcv;
382         sk->sk_rcvbuf = sysctl_tipc_rmem[1];
383         sk->sk_data_ready = tipc_data_ready;
384         sk->sk_write_space = tipc_write_space;
385         sk->sk_destruct = tipc_sock_destruct;
386         tsk->conn_timeout = CONN_TIMEOUT_DEFAULT;
387         tsk->sent_unacked = 0;
388         atomic_set(&tsk->dupl_rcvcnt, 0);
389
390         if (sock->state == SS_READY) {
391                 tsk_set_unreturnable(tsk, true);
392                 if (sock->type == SOCK_DGRAM)
393                         tsk_set_unreliable(tsk, true);
394         }
395         return 0;
396 }
397
398 static void tipc_sk_callback(struct rcu_head *head)
399 {
400         struct tipc_sock *tsk = container_of(head, struct tipc_sock, rcu);
401
402         sock_put(&tsk->sk);
403 }
404
405 /**
406  * tipc_release - destroy a TIPC socket
407  * @sock: socket to destroy
408  *
409  * This routine cleans up any messages that are still queued on the socket.
410  * For DGRAM and RDM socket types, all queued messages are rejected.
411  * For SEQPACKET and STREAM socket types, the first message is rejected
412  * and any others are discarded.  (If the first message on a STREAM socket
413  * is partially-read, it is discarded and the next one is rejected instead.)
414  *
415  * NOTE: Rejected messages are not necessarily returned to the sender!  They
416  * are returned or discarded according to the "destination droppable" setting
417  * specified for the message by the sender.
418  *
419  * Returns 0 on success, errno otherwise
420  */
421 static int tipc_release(struct socket *sock)
422 {
423         struct sock *sk = sock->sk;
424         struct net *net;
425         struct tipc_sock *tsk;
426         struct sk_buff *skb;
427         u32 dnode;
428
429         /*
430          * Exit if socket isn't fully initialized (occurs when a failed accept()
431          * releases a pre-allocated child socket that was never used)
432          */
433         if (sk == NULL)
434                 return 0;
435
436         net = sock_net(sk);
437         tsk = tipc_sk(sk);
438         lock_sock(sk);
439
440         /*
441          * Reject all unreceived messages, except on an active connection
442          * (which disconnects locally & sends a 'FIN+' to peer)
443          */
444         dnode = tsk_peer_node(tsk);
445         while (sock->state != SS_DISCONNECTING) {
446                 skb = __skb_dequeue(&sk->sk_receive_queue);
447                 if (skb == NULL)
448                         break;
449                 if (TIPC_SKB_CB(skb)->handle != NULL)
450                         kfree_skb(skb);
451                 else {
452                         if ((sock->state == SS_CONNECTING) ||
453                             (sock->state == SS_CONNECTED)) {
454                                 sock->state = SS_DISCONNECTING;
455                                 tsk->connected = 0;
456                                 tipc_node_remove_conn(net, dnode, tsk->portid);
457                         }
458                         tipc_sk_respond(sk, skb, TIPC_ERR_NO_PORT);
459                 }
460         }
461
462         tipc_sk_withdraw(tsk, 0, NULL);
463         sk_stop_timer(sk, &sk->sk_timer);
464         tipc_sk_remove(tsk);
465         if (tsk->connected) {
466                 skb = tipc_msg_create(TIPC_CRITICAL_IMPORTANCE,
467                                       TIPC_CONN_MSG, SHORT_H_SIZE, 0, dnode,
468                                       tsk_own_node(tsk), tsk_peer_port(tsk),
469                                       tsk->portid, TIPC_ERR_NO_PORT);
470                 if (skb)
471                         tipc_node_xmit_skb(net, skb, dnode, tsk->portid);
472                 tipc_node_remove_conn(net, dnode, tsk->portid);
473         }
474
475         /* Reject any messages that accumulated in backlog queue */
476         sock->state = SS_DISCONNECTING;
477         release_sock(sk);
478
479         call_rcu(&tsk->rcu, tipc_sk_callback);
480         sock->sk = NULL;
481
482         return 0;
483 }
484
485 /**
486  * tipc_bind - associate or disassocate TIPC name(s) with a socket
487  * @sock: socket structure
488  * @uaddr: socket address describing name(s) and desired operation
489  * @uaddr_len: size of socket address data structure
490  *
491  * Name and name sequence binding is indicated using a positive scope value;
492  * a negative scope value unbinds the specified name.  Specifying no name
493  * (i.e. a socket address length of 0) unbinds all names from the socket.
494  *
495  * Returns 0 on success, errno otherwise
496  *
497  * NOTE: This routine doesn't need to take the socket lock since it doesn't
498  *       access any non-constant socket information.
499  */
500 static int tipc_bind(struct socket *sock, struct sockaddr *uaddr,
501                      int uaddr_len)
502 {
503         struct sock *sk = sock->sk;
504         struct sockaddr_tipc *addr = (struct sockaddr_tipc *)uaddr;
505         struct tipc_sock *tsk = tipc_sk(sk);
506         int res = -EINVAL;
507
508         lock_sock(sk);
509         if (unlikely(!uaddr_len)) {
510                 res = tipc_sk_withdraw(tsk, 0, NULL);
511                 goto exit;
512         }
513
514         if (uaddr_len < sizeof(struct sockaddr_tipc)) {
515                 res = -EINVAL;
516                 goto exit;
517         }
518         if (addr->family != AF_TIPC) {
519                 res = -EAFNOSUPPORT;
520                 goto exit;
521         }
522
523         if (addr->addrtype == TIPC_ADDR_NAME)
524                 addr->addr.nameseq.upper = addr->addr.nameseq.lower;
525         else if (addr->addrtype != TIPC_ADDR_NAMESEQ) {
526                 res = -EAFNOSUPPORT;
527                 goto exit;
528         }
529
530         if ((addr->addr.nameseq.type < TIPC_RESERVED_TYPES) &&
531             (addr->addr.nameseq.type != TIPC_TOP_SRV) &&
532             (addr->addr.nameseq.type != TIPC_CFG_SRV)) {
533                 res = -EACCES;
534                 goto exit;
535         }
536
537         res = (addr->scope > 0) ?
538                 tipc_sk_publish(tsk, addr->scope, &addr->addr.nameseq) :
539                 tipc_sk_withdraw(tsk, -addr->scope, &addr->addr.nameseq);
540 exit:
541         release_sock(sk);
542         return res;
543 }
544
545 /**
546  * tipc_getname - get port ID of socket or peer socket
547  * @sock: socket structure
548  * @uaddr: area for returned socket address
549  * @uaddr_len: area for returned length of socket address
550  * @peer: 0 = own ID, 1 = current peer ID, 2 = current/former peer ID
551  *
552  * Returns 0 on success, errno otherwise
553  *
554  * NOTE: This routine doesn't need to take the socket lock since it only
555  *       accesses socket information that is unchanging (or which changes in
556  *       a completely predictable manner).
557  */
558 static int tipc_getname(struct socket *sock, struct sockaddr *uaddr,
559                         int *uaddr_len, int peer)
560 {
561         struct sockaddr_tipc *addr = (struct sockaddr_tipc *)uaddr;
562         struct tipc_sock *tsk = tipc_sk(sock->sk);
563         struct tipc_net *tn = net_generic(sock_net(sock->sk), tipc_net_id);
564
565         memset(addr, 0, sizeof(*addr));
566         if (peer) {
567                 if ((sock->state != SS_CONNECTED) &&
568                         ((peer != 2) || (sock->state != SS_DISCONNECTING)))
569                         return -ENOTCONN;
570                 addr->addr.id.ref = tsk_peer_port(tsk);
571                 addr->addr.id.node = tsk_peer_node(tsk);
572         } else {
573                 addr->addr.id.ref = tsk->portid;
574                 addr->addr.id.node = tn->own_addr;
575         }
576
577         *uaddr_len = sizeof(*addr);
578         addr->addrtype = TIPC_ADDR_ID;
579         addr->family = AF_TIPC;
580         addr->scope = 0;
581         addr->addr.name.domain = 0;
582
583         return 0;
584 }
585
586 /**
587  * tipc_poll - read and possibly block on pollmask
588  * @file: file structure associated with the socket
589  * @sock: socket for which to calculate the poll bits
590  * @wait: ???
591  *
592  * Returns pollmask value
593  *
594  * COMMENTARY:
595  * It appears that the usual socket locking mechanisms are not useful here
596  * since the pollmask info is potentially out-of-date the moment this routine
597  * exits.  TCP and other protocols seem to rely on higher level poll routines
598  * to handle any preventable race conditions, so TIPC will do the same ...
599  *
600  * TIPC sets the returned events as follows:
601  *
602  * socket state         flags set
603  * ------------         ---------
604  * unconnected          no read flags
605  *                      POLLOUT if port is not congested
606  *
607  * connecting           POLLIN/POLLRDNORM if ACK/NACK in rx queue
608  *                      no write flags
609  *
610  * connected            POLLIN/POLLRDNORM if data in rx queue
611  *                      POLLOUT if port is not congested
612  *
613  * disconnecting        POLLIN/POLLRDNORM/POLLHUP
614  *                      no write flags
615  *
616  * listening            POLLIN if SYN in rx queue
617  *                      no write flags
618  *
619  * ready                POLLIN/POLLRDNORM if data in rx queue
620  * [connectionless]     POLLOUT (since port cannot be congested)
621  *
622  * IMPORTANT: The fact that a read or write operation is indicated does NOT
623  * imply that the operation will succeed, merely that it should be performed
624  * and will not block.
625  */
626 static unsigned int tipc_poll(struct file *file, struct socket *sock,
627                               poll_table *wait)
628 {
629         struct sock *sk = sock->sk;
630         struct tipc_sock *tsk = tipc_sk(sk);
631         u32 mask = 0;
632
633         sock_poll_wait(file, sk_sleep(sk), wait);
634
635         switch ((int)sock->state) {
636         case SS_UNCONNECTED:
637                 if (!tsk->link_cong)
638                         mask |= POLLOUT;
639                 break;
640         case SS_READY:
641         case SS_CONNECTED:
642                 if (!tsk->link_cong && !tsk_conn_cong(tsk))
643                         mask |= POLLOUT;
644                 /* fall thru' */
645         case SS_CONNECTING:
646         case SS_LISTENING:
647                 if (!skb_queue_empty(&sk->sk_receive_queue))
648                         mask |= (POLLIN | POLLRDNORM);
649                 break;
650         case SS_DISCONNECTING:
651                 mask = (POLLIN | POLLRDNORM | POLLHUP);
652                 break;
653         }
654
655         return mask;
656 }
657
658 /**
659  * tipc_sendmcast - send multicast message
660  * @sock: socket structure
661  * @seq: destination address
662  * @msg: message to send
663  * @dsz: total length of message data
664  * @timeo: timeout to wait for wakeup
665  *
666  * Called from function tipc_sendmsg(), which has done all sanity checks
667  * Returns the number of bytes sent on success, or errno
668  */
669 static int tipc_sendmcast(struct  socket *sock, struct tipc_name_seq *seq,
670                           struct msghdr *msg, size_t dsz, long timeo)
671 {
672         struct sock *sk = sock->sk;
673         struct tipc_sock *tsk = tipc_sk(sk);
674         struct net *net = sock_net(sk);
675         struct tipc_msg *mhdr = &tsk->phdr;
676         struct sk_buff_head pktchain;
677         struct iov_iter save = msg->msg_iter;
678         uint mtu;
679         int rc;
680
681         msg_set_type(mhdr, TIPC_MCAST_MSG);
682         msg_set_lookup_scope(mhdr, TIPC_CLUSTER_SCOPE);
683         msg_set_destport(mhdr, 0);
684         msg_set_destnode(mhdr, 0);
685         msg_set_nametype(mhdr, seq->type);
686         msg_set_namelower(mhdr, seq->lower);
687         msg_set_nameupper(mhdr, seq->upper);
688         msg_set_hdr_sz(mhdr, MCAST_H_SIZE);
689
690         skb_queue_head_init(&pktchain);
691
692 new_mtu:
693         mtu = tipc_bcast_get_mtu(net);
694         rc = tipc_msg_build(mhdr, msg, 0, dsz, mtu, &pktchain);
695         if (unlikely(rc < 0))
696                 return rc;
697
698         do {
699                 rc = tipc_bcast_xmit(net, &pktchain);
700                 if (likely(!rc))
701                         return dsz;
702
703                 if (rc == -ELINKCONG) {
704                         tsk->link_cong = 1;
705                         rc = tipc_wait_for_sndmsg(sock, &timeo);
706                         if (!rc)
707                                 continue;
708                 }
709                 __skb_queue_purge(&pktchain);
710                 if (rc == -EMSGSIZE) {
711                         msg->msg_iter = save;
712                         goto new_mtu;
713                 }
714                 break;
715         } while (1);
716         return rc;
717 }
718
719 /**
720  * tipc_sk_mcast_rcv - Deliver multicast messages to all destination sockets
721  * @arrvq: queue with arriving messages, to be cloned after destination lookup
722  * @inputq: queue with cloned messages, delivered to socket after dest lookup
723  *
724  * Multi-threaded: parallel calls with reference to same queues may occur
725  */
726 void tipc_sk_mcast_rcv(struct net *net, struct sk_buff_head *arrvq,
727                        struct sk_buff_head *inputq)
728 {
729         struct tipc_msg *msg;
730         struct tipc_plist dports;
731         u32 portid;
732         u32 scope = TIPC_CLUSTER_SCOPE;
733         struct sk_buff_head tmpq;
734         uint hsz;
735         struct sk_buff *skb, *_skb;
736
737         __skb_queue_head_init(&tmpq);
738         tipc_plist_init(&dports);
739
740         skb = tipc_skb_peek(arrvq, &inputq->lock);
741         for (; skb; skb = tipc_skb_peek(arrvq, &inputq->lock)) {
742                 msg = buf_msg(skb);
743                 hsz = skb_headroom(skb) + msg_hdr_sz(msg);
744
745                 if (in_own_node(net, msg_orignode(msg)))
746                         scope = TIPC_NODE_SCOPE;
747
748                 /* Create destination port list and message clones: */
749                 tipc_nametbl_mc_translate(net,
750                                           msg_nametype(msg), msg_namelower(msg),
751                                           msg_nameupper(msg), scope, &dports);
752                 portid = tipc_plist_pop(&dports);
753                 for (; portid; portid = tipc_plist_pop(&dports)) {
754                         _skb = __pskb_copy(skb, hsz, GFP_ATOMIC);
755                         if (_skb) {
756                                 msg_set_destport(buf_msg(_skb), portid);
757                                 __skb_queue_tail(&tmpq, _skb);
758                                 continue;
759                         }
760                         pr_warn("Failed to clone mcast rcv buffer\n");
761                 }
762                 /* Append to inputq if not already done by other thread */
763                 spin_lock_bh(&inputq->lock);
764                 if (skb_peek(arrvq) == skb) {
765                         skb_queue_splice_tail_init(&tmpq, inputq);
766                         kfree_skb(__skb_dequeue(arrvq));
767                 }
768                 spin_unlock_bh(&inputq->lock);
769                 __skb_queue_purge(&tmpq);
770                 kfree_skb(skb);
771         }
772         tipc_sk_rcv(net, inputq);
773 }
774
775 /**
776  * tipc_sk_proto_rcv - receive a connection mng protocol message
777  * @tsk: receiving socket
778  * @skb: pointer to message buffer.
779  */
780 static void tipc_sk_proto_rcv(struct tipc_sock *tsk, struct sk_buff *skb,
781                               struct sk_buff_head *xmitq)
782 {
783         struct sock *sk = &tsk->sk;
784         u32 onode = tsk_own_node(tsk);
785         struct tipc_msg *hdr = buf_msg(skb);
786         int mtyp = msg_type(hdr);
787         int conn_cong;
788
789         /* Ignore if connection cannot be validated: */
790         if (!tsk_peer_msg(tsk, hdr))
791                 goto exit;
792
793         tsk->probing_state = TIPC_CONN_OK;
794
795         if (mtyp == CONN_PROBE) {
796                 msg_set_type(hdr, CONN_PROBE_REPLY);
797                 if (tipc_msg_reverse(onode, &skb, TIPC_OK))
798                         __skb_queue_tail(xmitq, skb);
799                 return;
800         } else if (mtyp == CONN_ACK) {
801                 conn_cong = tsk_conn_cong(tsk);
802                 tsk->sent_unacked -= msg_msgcnt(hdr);
803                 if (conn_cong)
804                         sk->sk_write_space(sk);
805         } else if (mtyp != CONN_PROBE_REPLY) {
806                 pr_warn("Received unknown CONN_PROTO msg\n");
807         }
808 exit:
809         kfree_skb(skb);
810 }
811
812 static int tipc_wait_for_sndmsg(struct socket *sock, long *timeo_p)
813 {
814         struct sock *sk = sock->sk;
815         struct tipc_sock *tsk = tipc_sk(sk);
816         DEFINE_WAIT(wait);
817         int done;
818
819         do {
820                 int err = sock_error(sk);
821                 if (err)
822                         return err;
823                 if (sock->state == SS_DISCONNECTING)
824                         return -EPIPE;
825                 if (!*timeo_p)
826                         return -EAGAIN;
827                 if (signal_pending(current))
828                         return sock_intr_errno(*timeo_p);
829
830                 prepare_to_wait(sk_sleep(sk), &wait, TASK_INTERRUPTIBLE);
831                 done = sk_wait_event(sk, timeo_p, !tsk->link_cong);
832                 finish_wait(sk_sleep(sk), &wait);
833         } while (!done);
834         return 0;
835 }
836
837 /**
838  * tipc_sendmsg - send message in connectionless manner
839  * @sock: socket structure
840  * @m: message to send
841  * @dsz: amount of user data to be sent
842  *
843  * Message must have an destination specified explicitly.
844  * Used for SOCK_RDM and SOCK_DGRAM messages,
845  * and for 'SYN' messages on SOCK_SEQPACKET and SOCK_STREAM connections.
846  * (Note: 'SYN+' is prohibited on SOCK_STREAM.)
847  *
848  * Returns the number of bytes sent on success, or errno otherwise
849  */
850 static int tipc_sendmsg(struct socket *sock,
851                         struct msghdr *m, size_t dsz)
852 {
853         struct sock *sk = sock->sk;
854         int ret;
855
856         lock_sock(sk);
857         ret = __tipc_sendmsg(sock, m, dsz);
858         release_sock(sk);
859
860         return ret;
861 }
862
863 static int __tipc_sendmsg(struct socket *sock, struct msghdr *m, size_t dsz)
864 {
865         DECLARE_SOCKADDR(struct sockaddr_tipc *, dest, m->msg_name);
866         struct sock *sk = sock->sk;
867         struct tipc_sock *tsk = tipc_sk(sk);
868         struct net *net = sock_net(sk);
869         struct tipc_msg *mhdr = &tsk->phdr;
870         u32 dnode, dport;
871         struct sk_buff_head pktchain;
872         struct sk_buff *skb;
873         struct tipc_name_seq *seq;
874         struct iov_iter save;
875         u32 mtu;
876         long timeo;
877         int rc;
878
879         if (dsz > TIPC_MAX_USER_MSG_SIZE)
880                 return -EMSGSIZE;
881         if (unlikely(!dest)) {
882                 if (tsk->connected && sock->state == SS_READY)
883                         dest = &tsk->remote;
884                 else
885                         return -EDESTADDRREQ;
886         } else if (unlikely(m->msg_namelen < sizeof(*dest)) ||
887                    dest->family != AF_TIPC) {
888                 return -EINVAL;
889         }
890         if (unlikely(sock->state != SS_READY)) {
891                 if (sock->state == SS_LISTENING)
892                         return -EPIPE;
893                 if (sock->state != SS_UNCONNECTED)
894                         return -EISCONN;
895                 if (tsk->published)
896                         return -EOPNOTSUPP;
897                 if (dest->addrtype == TIPC_ADDR_NAME) {
898                         tsk->conn_type = dest->addr.name.name.type;
899                         tsk->conn_instance = dest->addr.name.name.instance;
900                 }
901         }
902         seq = &dest->addr.nameseq;
903         timeo = sock_sndtimeo(sk, m->msg_flags & MSG_DONTWAIT);
904
905         if (dest->addrtype == TIPC_ADDR_MCAST) {
906                 return tipc_sendmcast(sock, seq, m, dsz, timeo);
907         } else if (dest->addrtype == TIPC_ADDR_NAME) {
908                 u32 type = dest->addr.name.name.type;
909                 u32 inst = dest->addr.name.name.instance;
910                 u32 domain = dest->addr.name.domain;
911
912                 dnode = domain;
913                 msg_set_type(mhdr, TIPC_NAMED_MSG);
914                 msg_set_hdr_sz(mhdr, NAMED_H_SIZE);
915                 msg_set_nametype(mhdr, type);
916                 msg_set_nameinst(mhdr, inst);
917                 msg_set_lookup_scope(mhdr, tipc_addr_scope(domain));
918                 dport = tipc_nametbl_translate(net, type, inst, &dnode);
919                 msg_set_destnode(mhdr, dnode);
920                 msg_set_destport(mhdr, dport);
921                 if (unlikely(!dport && !dnode))
922                         return -EHOSTUNREACH;
923         } else if (dest->addrtype == TIPC_ADDR_ID) {
924                 dnode = dest->addr.id.node;
925                 msg_set_type(mhdr, TIPC_DIRECT_MSG);
926                 msg_set_lookup_scope(mhdr, 0);
927                 msg_set_destnode(mhdr, dnode);
928                 msg_set_destport(mhdr, dest->addr.id.ref);
929                 msg_set_hdr_sz(mhdr, BASIC_H_SIZE);
930         }
931
932         skb_queue_head_init(&pktchain);
933         save = m->msg_iter;
934 new_mtu:
935         mtu = tipc_node_get_mtu(net, dnode, tsk->portid);
936         rc = tipc_msg_build(mhdr, m, 0, dsz, mtu, &pktchain);
937         if (rc < 0)
938                 return rc;
939
940         do {
941                 skb = skb_peek(&pktchain);
942                 TIPC_SKB_CB(skb)->wakeup_pending = tsk->link_cong;
943                 rc = tipc_node_xmit(net, &pktchain, dnode, tsk->portid);
944                 if (likely(!rc)) {
945                         if (sock->state != SS_READY)
946                                 sock->state = SS_CONNECTING;
947                         return dsz;
948                 }
949                 if (rc == -ELINKCONG) {
950                         tsk->link_cong = 1;
951                         rc = tipc_wait_for_sndmsg(sock, &timeo);
952                         if (!rc)
953                                 continue;
954                 }
955                 __skb_queue_purge(&pktchain);
956                 if (rc == -EMSGSIZE) {
957                         m->msg_iter = save;
958                         goto new_mtu;
959                 }
960                 break;
961         } while (1);
962
963         return rc;
964 }
965
966 static int tipc_wait_for_sndpkt(struct socket *sock, long *timeo_p)
967 {
968         struct sock *sk = sock->sk;
969         struct tipc_sock *tsk = tipc_sk(sk);
970         DEFINE_WAIT(wait);
971         int done;
972
973         do {
974                 int err = sock_error(sk);
975                 if (err)
976                         return err;
977                 if (sock->state == SS_DISCONNECTING)
978                         return -EPIPE;
979                 else if (sock->state != SS_CONNECTED)
980                         return -ENOTCONN;
981                 if (!*timeo_p)
982                         return -EAGAIN;
983                 if (signal_pending(current))
984                         return sock_intr_errno(*timeo_p);
985
986                 prepare_to_wait(sk_sleep(sk), &wait, TASK_INTERRUPTIBLE);
987                 done = sk_wait_event(sk, timeo_p,
988                                      (!tsk->link_cong &&
989                                       !tsk_conn_cong(tsk)) ||
990                                      !tsk->connected);
991                 finish_wait(sk_sleep(sk), &wait);
992         } while (!done);
993         return 0;
994 }
995
996 /**
997  * tipc_send_stream - send stream-oriented data
998  * @sock: socket structure
999  * @m: data to send
1000  * @dsz: total length of data to be transmitted
1001  *
1002  * Used for SOCK_STREAM data.
1003  *
1004  * Returns the number of bytes sent on success (or partial success),
1005  * or errno if no data sent
1006  */
1007 static int tipc_send_stream(struct socket *sock, struct msghdr *m, size_t dsz)
1008 {
1009         struct sock *sk = sock->sk;
1010         int ret;
1011
1012         lock_sock(sk);
1013         ret = __tipc_send_stream(sock, m, dsz);
1014         release_sock(sk);
1015
1016         return ret;
1017 }
1018
1019 static int __tipc_send_stream(struct socket *sock, struct msghdr *m, size_t dsz)
1020 {
1021         struct sock *sk = sock->sk;
1022         struct net *net = sock_net(sk);
1023         struct tipc_sock *tsk = tipc_sk(sk);
1024         struct tipc_msg *mhdr = &tsk->phdr;
1025         struct sk_buff_head pktchain;
1026         DECLARE_SOCKADDR(struct sockaddr_tipc *, dest, m->msg_name);
1027         u32 portid = tsk->portid;
1028         int rc = -EINVAL;
1029         long timeo;
1030         u32 dnode;
1031         uint mtu, send, sent = 0;
1032         struct iov_iter save;
1033
1034         /* Handle implied connection establishment */
1035         if (unlikely(dest)) {
1036                 rc = __tipc_sendmsg(sock, m, dsz);
1037                 if (dsz && (dsz == rc))
1038                         tsk->sent_unacked = 1;
1039                 return rc;
1040         }
1041         if (dsz > (uint)INT_MAX)
1042                 return -EMSGSIZE;
1043
1044         if (unlikely(sock->state != SS_CONNECTED)) {
1045                 if (sock->state == SS_DISCONNECTING)
1046                         return -EPIPE;
1047                 else
1048                         return -ENOTCONN;
1049         }
1050
1051         timeo = sock_sndtimeo(sk, m->msg_flags & MSG_DONTWAIT);
1052         dnode = tsk_peer_node(tsk);
1053         skb_queue_head_init(&pktchain);
1054
1055 next:
1056         save = m->msg_iter;
1057         mtu = tsk->max_pkt;
1058         send = min_t(uint, dsz - sent, TIPC_MAX_USER_MSG_SIZE);
1059         rc = tipc_msg_build(mhdr, m, sent, send, mtu, &pktchain);
1060         if (unlikely(rc < 0))
1061                 return rc;
1062
1063         do {
1064                 if (likely(!tsk_conn_cong(tsk))) {
1065                         rc = tipc_node_xmit(net, &pktchain, dnode, portid);
1066                         if (likely(!rc)) {
1067                                 tsk->sent_unacked++;
1068                                 sent += send;
1069                                 if (sent == dsz)
1070                                         return dsz;
1071                                 goto next;
1072                         }
1073                         if (rc == -EMSGSIZE) {
1074                                 __skb_queue_purge(&pktchain);
1075                                 tsk->max_pkt = tipc_node_get_mtu(net, dnode,
1076                                                                  portid);
1077                                 m->msg_iter = save;
1078                                 goto next;
1079                         }
1080                         if (rc != -ELINKCONG)
1081                                 break;
1082
1083                         tsk->link_cong = 1;
1084                 }
1085                 rc = tipc_wait_for_sndpkt(sock, &timeo);
1086         } while (!rc);
1087
1088         __skb_queue_purge(&pktchain);
1089         return sent ? sent : rc;
1090 }
1091
1092 /**
1093  * tipc_send_packet - send a connection-oriented message
1094  * @sock: socket structure
1095  * @m: message to send
1096  * @dsz: length of data to be transmitted
1097  *
1098  * Used for SOCK_SEQPACKET messages.
1099  *
1100  * Returns the number of bytes sent on success, or errno otherwise
1101  */
1102 static int tipc_send_packet(struct socket *sock, struct msghdr *m, size_t dsz)
1103 {
1104         if (dsz > TIPC_MAX_USER_MSG_SIZE)
1105                 return -EMSGSIZE;
1106
1107         return tipc_send_stream(sock, m, dsz);
1108 }
1109
1110 /* tipc_sk_finish_conn - complete the setup of a connection
1111  */
1112 static void tipc_sk_finish_conn(struct tipc_sock *tsk, u32 peer_port,
1113                                 u32 peer_node)
1114 {
1115         struct sock *sk = &tsk->sk;
1116         struct net *net = sock_net(sk);
1117         struct tipc_msg *msg = &tsk->phdr;
1118
1119         msg_set_destnode(msg, peer_node);
1120         msg_set_destport(msg, peer_port);
1121         msg_set_type(msg, TIPC_CONN_MSG);
1122         msg_set_lookup_scope(msg, 0);
1123         msg_set_hdr_sz(msg, SHORT_H_SIZE);
1124
1125         tsk->probing_intv = CONN_PROBING_INTERVAL;
1126         tsk->probing_state = TIPC_CONN_OK;
1127         tsk->connected = 1;
1128         sk_reset_timer(sk, &sk->sk_timer, jiffies + tsk->probing_intv);
1129         tipc_node_add_conn(net, peer_node, tsk->portid, peer_port);
1130         tsk->max_pkt = tipc_node_get_mtu(net, peer_node, tsk->portid);
1131 }
1132
1133 /**
1134  * set_orig_addr - capture sender's address for received message
1135  * @m: descriptor for message info
1136  * @msg: received message header
1137  *
1138  * Note: Address is not captured if not requested by receiver.
1139  */
1140 static void set_orig_addr(struct msghdr *m, struct tipc_msg *msg)
1141 {
1142         DECLARE_SOCKADDR(struct sockaddr_tipc *, addr, m->msg_name);
1143
1144         if (addr) {
1145                 addr->family = AF_TIPC;
1146                 addr->addrtype = TIPC_ADDR_ID;
1147                 memset(&addr->addr, 0, sizeof(addr->addr));
1148                 addr->addr.id.ref = msg_origport(msg);
1149                 addr->addr.id.node = msg_orignode(msg);
1150                 addr->addr.name.domain = 0;     /* could leave uninitialized */
1151                 addr->scope = 0;                /* could leave uninitialized */
1152                 m->msg_namelen = sizeof(struct sockaddr_tipc);
1153         }
1154 }
1155
1156 /**
1157  * tipc_sk_anc_data_recv - optionally capture ancillary data for received message
1158  * @m: descriptor for message info
1159  * @msg: received message header
1160  * @tsk: TIPC port associated with message
1161  *
1162  * Note: Ancillary data is not captured if not requested by receiver.
1163  *
1164  * Returns 0 if successful, otherwise errno
1165  */
1166 static int tipc_sk_anc_data_recv(struct msghdr *m, struct tipc_msg *msg,
1167                                  struct tipc_sock *tsk)
1168 {
1169         u32 anc_data[3];
1170         u32 err;
1171         u32 dest_type;
1172         int has_name;
1173         int res;
1174
1175         if (likely(m->msg_controllen == 0))
1176                 return 0;
1177
1178         /* Optionally capture errored message object(s) */
1179         err = msg ? msg_errcode(msg) : 0;
1180         if (unlikely(err)) {
1181                 anc_data[0] = err;
1182                 anc_data[1] = msg_data_sz(msg);
1183                 res = put_cmsg(m, SOL_TIPC, TIPC_ERRINFO, 8, anc_data);
1184                 if (res)
1185                         return res;
1186                 if (anc_data[1]) {
1187                         res = put_cmsg(m, SOL_TIPC, TIPC_RETDATA, anc_data[1],
1188                                        msg_data(msg));
1189                         if (res)
1190                                 return res;
1191                 }
1192         }
1193
1194         /* Optionally capture message destination object */
1195         dest_type = msg ? msg_type(msg) : TIPC_DIRECT_MSG;
1196         switch (dest_type) {
1197         case TIPC_NAMED_MSG:
1198                 has_name = 1;
1199                 anc_data[0] = msg_nametype(msg);
1200                 anc_data[1] = msg_namelower(msg);
1201                 anc_data[2] = msg_namelower(msg);
1202                 break;
1203         case TIPC_MCAST_MSG:
1204                 has_name = 1;
1205                 anc_data[0] = msg_nametype(msg);
1206                 anc_data[1] = msg_namelower(msg);
1207                 anc_data[2] = msg_nameupper(msg);
1208                 break;
1209         case TIPC_CONN_MSG:
1210                 has_name = (tsk->conn_type != 0);
1211                 anc_data[0] = tsk->conn_type;
1212                 anc_data[1] = tsk->conn_instance;
1213                 anc_data[2] = tsk->conn_instance;
1214                 break;
1215         default:
1216                 has_name = 0;
1217         }
1218         if (has_name) {
1219                 res = put_cmsg(m, SOL_TIPC, TIPC_DESTNAME, 12, anc_data);
1220                 if (res)
1221                         return res;
1222         }
1223
1224         return 0;
1225 }
1226
1227 static void tipc_sk_send_ack(struct tipc_sock *tsk, uint ack)
1228 {
1229         struct net *net = sock_net(&tsk->sk);
1230         struct sk_buff *skb = NULL;
1231         struct tipc_msg *msg;
1232         u32 peer_port = tsk_peer_port(tsk);
1233         u32 dnode = tsk_peer_node(tsk);
1234
1235         if (!tsk->connected)
1236                 return;
1237         skb = tipc_msg_create(CONN_MANAGER, CONN_ACK, INT_H_SIZE, 0,
1238                               dnode, tsk_own_node(tsk), peer_port,
1239                               tsk->portid, TIPC_OK);
1240         if (!skb)
1241                 return;
1242         msg = buf_msg(skb);
1243         msg_set_msgcnt(msg, ack);
1244         tipc_node_xmit_skb(net, skb, dnode, msg_link_selector(msg));
1245 }
1246
1247 static int tipc_wait_for_rcvmsg(struct socket *sock, long *timeop)
1248 {
1249         struct sock *sk = sock->sk;
1250         DEFINE_WAIT(wait);
1251         long timeo = *timeop;
1252         int err;
1253
1254         for (;;) {
1255                 prepare_to_wait(sk_sleep(sk), &wait, TASK_INTERRUPTIBLE);
1256                 if (timeo && skb_queue_empty(&sk->sk_receive_queue)) {
1257                         if (sock->state == SS_DISCONNECTING) {
1258                                 err = -ENOTCONN;
1259                                 break;
1260                         }
1261                         release_sock(sk);
1262                         timeo = schedule_timeout(timeo);
1263                         lock_sock(sk);
1264                 }
1265                 err = 0;
1266                 if (!skb_queue_empty(&sk->sk_receive_queue))
1267                         break;
1268                 err = -EAGAIN;
1269                 if (!timeo)
1270                         break;
1271                 err = sock_intr_errno(timeo);
1272                 if (signal_pending(current))
1273                         break;
1274         }
1275         finish_wait(sk_sleep(sk), &wait);
1276         *timeop = timeo;
1277         return err;
1278 }
1279
1280 /**
1281  * tipc_recvmsg - receive packet-oriented message
1282  * @m: descriptor for message info
1283  * @buf_len: total size of user buffer area
1284  * @flags: receive flags
1285  *
1286  * Used for SOCK_DGRAM, SOCK_RDM, and SOCK_SEQPACKET messages.
1287  * If the complete message doesn't fit in user area, truncate it.
1288  *
1289  * Returns size of returned message data, errno otherwise
1290  */
1291 static int tipc_recvmsg(struct socket *sock, struct msghdr *m, size_t buf_len,
1292                         int flags)
1293 {
1294         struct sock *sk = sock->sk;
1295         struct tipc_sock *tsk = tipc_sk(sk);
1296         struct sk_buff *buf;
1297         struct tipc_msg *msg;
1298         long timeo;
1299         unsigned int sz;
1300         u32 err;
1301         int res;
1302
1303         /* Catch invalid receive requests */
1304         if (unlikely(!buf_len))
1305                 return -EINVAL;
1306
1307         lock_sock(sk);
1308
1309         if (unlikely(sock->state == SS_UNCONNECTED)) {
1310                 res = -ENOTCONN;
1311                 goto exit;
1312         }
1313
1314         timeo = sock_rcvtimeo(sk, flags & MSG_DONTWAIT);
1315 restart:
1316
1317         /* Look for a message in receive queue; wait if necessary */
1318         res = tipc_wait_for_rcvmsg(sock, &timeo);
1319         if (res)
1320                 goto exit;
1321
1322         /* Look at first message in receive queue */
1323         buf = skb_peek(&sk->sk_receive_queue);
1324         msg = buf_msg(buf);
1325         sz = msg_data_sz(msg);
1326         err = msg_errcode(msg);
1327
1328         /* Discard an empty non-errored message & try again */
1329         if ((!sz) && (!err)) {
1330                 tsk_advance_rx_queue(sk);
1331                 goto restart;
1332         }
1333
1334         /* Capture sender's address (optional) */
1335         set_orig_addr(m, msg);
1336
1337         /* Capture ancillary data (optional) */
1338         res = tipc_sk_anc_data_recv(m, msg, tsk);
1339         if (res)
1340                 goto exit;
1341
1342         /* Capture message data (if valid) & compute return value (always) */
1343         if (!err) {
1344                 if (unlikely(buf_len < sz)) {
1345                         sz = buf_len;
1346                         m->msg_flags |= MSG_TRUNC;
1347                 }
1348                 res = skb_copy_datagram_msg(buf, msg_hdr_sz(msg), m, sz);
1349                 if (res)
1350                         goto exit;
1351                 res = sz;
1352         } else {
1353                 if ((sock->state == SS_READY) ||
1354                     ((err == TIPC_CONN_SHUTDOWN) || m->msg_control))
1355                         res = 0;
1356                 else
1357                         res = -ECONNRESET;
1358         }
1359
1360         /* Consume received message (optional) */
1361         if (likely(!(flags & MSG_PEEK))) {
1362                 if ((sock->state != SS_READY) &&
1363                     (++tsk->rcv_unacked >= TIPC_CONNACK_INTV)) {
1364                         tipc_sk_send_ack(tsk, tsk->rcv_unacked);
1365                         tsk->rcv_unacked = 0;
1366                 }
1367                 tsk_advance_rx_queue(sk);
1368         }
1369 exit:
1370         release_sock(sk);
1371         return res;
1372 }
1373
1374 /**
1375  * tipc_recv_stream - receive stream-oriented data
1376  * @m: descriptor for message info
1377  * @buf_len: total size of user buffer area
1378  * @flags: receive flags
1379  *
1380  * Used for SOCK_STREAM messages only.  If not enough data is available
1381  * will optionally wait for more; never truncates data.
1382  *
1383  * Returns size of returned message data, errno otherwise
1384  */
1385 static int tipc_recv_stream(struct socket *sock, struct msghdr *m,
1386                             size_t buf_len, int flags)
1387 {
1388         struct sock *sk = sock->sk;
1389         struct tipc_sock *tsk = tipc_sk(sk);
1390         struct sk_buff *buf;
1391         struct tipc_msg *msg;
1392         long timeo;
1393         unsigned int sz;
1394         int sz_to_copy, target, needed;
1395         int sz_copied = 0;
1396         u32 err;
1397         int res = 0;
1398
1399         /* Catch invalid receive attempts */
1400         if (unlikely(!buf_len))
1401                 return -EINVAL;
1402
1403         lock_sock(sk);
1404
1405         if (unlikely(sock->state == SS_UNCONNECTED)) {
1406                 res = -ENOTCONN;
1407                 goto exit;
1408         }
1409
1410         target = sock_rcvlowat(sk, flags & MSG_WAITALL, buf_len);
1411         timeo = sock_rcvtimeo(sk, flags & MSG_DONTWAIT);
1412
1413 restart:
1414         /* Look for a message in receive queue; wait if necessary */
1415         res = tipc_wait_for_rcvmsg(sock, &timeo);
1416         if (res)
1417                 goto exit;
1418
1419         /* Look at first message in receive queue */
1420         buf = skb_peek(&sk->sk_receive_queue);
1421         msg = buf_msg(buf);
1422         sz = msg_data_sz(msg);
1423         err = msg_errcode(msg);
1424
1425         /* Discard an empty non-errored message & try again */
1426         if ((!sz) && (!err)) {
1427                 tsk_advance_rx_queue(sk);
1428                 goto restart;
1429         }
1430
1431         /* Optionally capture sender's address & ancillary data of first msg */
1432         if (sz_copied == 0) {
1433                 set_orig_addr(m, msg);
1434                 res = tipc_sk_anc_data_recv(m, msg, tsk);
1435                 if (res)
1436                         goto exit;
1437         }
1438
1439         /* Capture message data (if valid) & compute return value (always) */
1440         if (!err) {
1441                 u32 offset = (u32)(unsigned long)(TIPC_SKB_CB(buf)->handle);
1442
1443                 sz -= offset;
1444                 needed = (buf_len - sz_copied);
1445                 sz_to_copy = (sz <= needed) ? sz : needed;
1446
1447                 res = skb_copy_datagram_msg(buf, msg_hdr_sz(msg) + offset,
1448                                             m, sz_to_copy);
1449                 if (res)
1450                         goto exit;
1451
1452                 sz_copied += sz_to_copy;
1453
1454                 if (sz_to_copy < sz) {
1455                         if (!(flags & MSG_PEEK))
1456                                 TIPC_SKB_CB(buf)->handle =
1457                                 (void *)(unsigned long)(offset + sz_to_copy);
1458                         goto exit;
1459                 }
1460         } else {
1461                 if (sz_copied != 0)
1462                         goto exit; /* can't add error msg to valid data */
1463
1464                 if ((err == TIPC_CONN_SHUTDOWN) || m->msg_control)
1465                         res = 0;
1466                 else
1467                         res = -ECONNRESET;
1468         }
1469
1470         /* Consume received message (optional) */
1471         if (likely(!(flags & MSG_PEEK))) {
1472                 if (unlikely(++tsk->rcv_unacked >= TIPC_CONNACK_INTV)) {
1473                         tipc_sk_send_ack(tsk, tsk->rcv_unacked);
1474                         tsk->rcv_unacked = 0;
1475                 }
1476                 tsk_advance_rx_queue(sk);
1477         }
1478
1479         /* Loop around if more data is required */
1480         if ((sz_copied < buf_len) &&    /* didn't get all requested data */
1481             (!skb_queue_empty(&sk->sk_receive_queue) ||
1482             (sz_copied < target)) &&    /* and more is ready or required */
1483             (!(flags & MSG_PEEK)) &&    /* and aren't just peeking at data */
1484             (!err))                     /* and haven't reached a FIN */
1485                 goto restart;
1486
1487 exit:
1488         release_sock(sk);
1489         return sz_copied ? sz_copied : res;
1490 }
1491
1492 /**
1493  * tipc_write_space - wake up thread if port congestion is released
1494  * @sk: socket
1495  */
1496 static void tipc_write_space(struct sock *sk)
1497 {
1498         struct socket_wq *wq;
1499
1500         rcu_read_lock();
1501         wq = rcu_dereference(sk->sk_wq);
1502         if (wq_has_sleeper(wq))
1503                 wake_up_interruptible_sync_poll(&wq->wait, POLLOUT |
1504                                                 POLLWRNORM | POLLWRBAND);
1505         rcu_read_unlock();
1506 }
1507
1508 /**
1509  * tipc_data_ready - wake up threads to indicate messages have been received
1510  * @sk: socket
1511  * @len: the length of messages
1512  */
1513 static void tipc_data_ready(struct sock *sk)
1514 {
1515         struct socket_wq *wq;
1516
1517         rcu_read_lock();
1518         wq = rcu_dereference(sk->sk_wq);
1519         if (wq_has_sleeper(wq))
1520                 wake_up_interruptible_sync_poll(&wq->wait, POLLIN |
1521                                                 POLLRDNORM | POLLRDBAND);
1522         rcu_read_unlock();
1523 }
1524
1525 static void tipc_sock_destruct(struct sock *sk)
1526 {
1527         __skb_queue_purge(&sk->sk_receive_queue);
1528 }
1529
1530 /**
1531  * filter_connect - Handle all incoming messages for a connection-based socket
1532  * @tsk: TIPC socket
1533  * @skb: pointer to message buffer. Set to NULL if buffer is consumed
1534  *
1535  * Returns true if everything ok, false otherwise
1536  */
1537 static bool filter_connect(struct tipc_sock *tsk, struct sk_buff *skb)
1538 {
1539         struct sock *sk = &tsk->sk;
1540         struct net *net = sock_net(sk);
1541         struct socket *sock = sk->sk_socket;
1542         struct tipc_msg *hdr = buf_msg(skb);
1543
1544         if (unlikely(msg_mcast(hdr)))
1545                 return false;
1546
1547         switch ((int)sock->state) {
1548         case SS_CONNECTED:
1549
1550                 /* Accept only connection-based messages sent by peer */
1551                 if (unlikely(!tsk_peer_msg(tsk, hdr)))
1552                         return false;
1553
1554                 if (unlikely(msg_errcode(hdr))) {
1555                         sock->state = SS_DISCONNECTING;
1556                         tsk->connected = 0;
1557                         /* Let timer expire on it's own */
1558                         tipc_node_remove_conn(net, tsk_peer_node(tsk),
1559                                               tsk->portid);
1560                 }
1561                 return true;
1562
1563         case SS_CONNECTING:
1564
1565                 /* Accept only ACK or NACK message */
1566                 if (unlikely(!msg_connected(hdr)))
1567                         return false;
1568
1569                 if (unlikely(msg_errcode(hdr))) {
1570                         sock->state = SS_DISCONNECTING;
1571                         sk->sk_err = ECONNREFUSED;
1572                         return true;
1573                 }
1574
1575                 if (unlikely(!msg_isdata(hdr))) {
1576                         sock->state = SS_DISCONNECTING;
1577                         sk->sk_err = EINVAL;
1578                         return true;
1579                 }
1580
1581                 tipc_sk_finish_conn(tsk, msg_origport(hdr), msg_orignode(hdr));
1582                 msg_set_importance(&tsk->phdr, msg_importance(hdr));
1583                 sock->state = SS_CONNECTED;
1584
1585                 /* If 'ACK+' message, add to socket receive queue */
1586                 if (msg_data_sz(hdr))
1587                         return true;
1588
1589                 /* If empty 'ACK-' message, wake up sleeping connect() */
1590                 if (waitqueue_active(sk_sleep(sk)))
1591                         wake_up_interruptible(sk_sleep(sk));
1592
1593                 /* 'ACK-' message is neither accepted nor rejected: */
1594                 msg_set_dest_droppable(hdr, 1);
1595                 return false;
1596
1597         case SS_LISTENING:
1598         case SS_UNCONNECTED:
1599
1600                 /* Accept only SYN message */
1601                 if (!msg_connected(hdr) && !(msg_errcode(hdr)))
1602                         return true;
1603                 break;
1604         case SS_DISCONNECTING:
1605                 break;
1606         default:
1607                 pr_err("Unknown socket state %u\n", sock->state);
1608         }
1609         return false;
1610 }
1611
1612 /**
1613  * rcvbuf_limit - get proper overload limit of socket receive queue
1614  * @sk: socket
1615  * @buf: message
1616  *
1617  * For all connection oriented messages, irrespective of importance,
1618  * the default overload value (i.e. 67MB) is set as limit.
1619  *
1620  * For all connectionless messages, by default new queue limits are
1621  * as belows:
1622  *
1623  * TIPC_LOW_IMPORTANCE       (4 MB)
1624  * TIPC_MEDIUM_IMPORTANCE    (8 MB)
1625  * TIPC_HIGH_IMPORTANCE      (16 MB)
1626  * TIPC_CRITICAL_IMPORTANCE  (32 MB)
1627  *
1628  * Returns overload limit according to corresponding message importance
1629  */
1630 static unsigned int rcvbuf_limit(struct sock *sk, struct sk_buff *buf)
1631 {
1632         struct tipc_msg *msg = buf_msg(buf);
1633
1634         if (msg_connected(msg))
1635                 return sysctl_tipc_rmem[2];
1636
1637         return sk->sk_rcvbuf >> TIPC_CRITICAL_IMPORTANCE <<
1638                 msg_importance(msg);
1639 }
1640
1641 /**
1642  * filter_rcv - validate incoming message
1643  * @sk: socket
1644  * @skb: pointer to message.
1645  *
1646  * Enqueues message on receive queue if acceptable; optionally handles
1647  * disconnect indication for a connected socket.
1648  *
1649  * Called with socket lock already taken
1650  *
1651  * Returns true if message was added to socket receive queue, otherwise false
1652  */
1653 static bool filter_rcv(struct sock *sk, struct sk_buff *skb,
1654                        struct sk_buff_head *xmitq)
1655 {
1656         struct socket *sock = sk->sk_socket;
1657         struct tipc_sock *tsk = tipc_sk(sk);
1658         struct tipc_msg *hdr = buf_msg(skb);
1659         unsigned int limit = rcvbuf_limit(sk, skb);
1660         int err = TIPC_OK;
1661         int usr = msg_user(hdr);
1662
1663         if (unlikely(msg_user(hdr) == CONN_MANAGER)) {
1664                 tipc_sk_proto_rcv(tsk, skb, xmitq);
1665                 return false;
1666         }
1667
1668         if (unlikely(usr == SOCK_WAKEUP)) {
1669                 kfree_skb(skb);
1670                 tsk->link_cong = 0;
1671                 sk->sk_write_space(sk);
1672                 return false;
1673         }
1674
1675         /* Drop if illegal message type */
1676         if (unlikely(msg_type(hdr) > TIPC_DIRECT_MSG)) {
1677                 kfree_skb(skb);
1678                 return false;
1679         }
1680
1681         /* Reject if wrong message type for current socket state */
1682         if (unlikely(sock->state == SS_READY)) {
1683                 if (msg_connected(hdr)) {
1684                         err = TIPC_ERR_NO_PORT;
1685                         goto reject;
1686                 }
1687         } else if (unlikely(!filter_connect(tsk, skb))) {
1688                 err = TIPC_ERR_NO_PORT;
1689                 goto reject;
1690         }
1691
1692         /* Reject message if there isn't room to queue it */
1693         if (unlikely(sk_rmem_alloc_get(sk) + skb->truesize >= limit)) {
1694                 err = TIPC_ERR_OVERLOAD;
1695                 goto reject;
1696         }
1697
1698         /* Enqueue message */
1699         TIPC_SKB_CB(skb)->handle = NULL;
1700         __skb_queue_tail(&sk->sk_receive_queue, skb);
1701         skb_set_owner_r(skb, sk);
1702
1703         sk->sk_data_ready(sk);
1704         return true;
1705
1706 reject:
1707         if (tipc_msg_reverse(tsk_own_node(tsk), &skb, err))
1708                 __skb_queue_tail(xmitq, skb);
1709         return false;
1710 }
1711
1712 /**
1713  * tipc_backlog_rcv - handle incoming message from backlog queue
1714  * @sk: socket
1715  * @skb: message
1716  *
1717  * Caller must hold socket lock
1718  *
1719  * Returns 0
1720  */
1721 static int tipc_backlog_rcv(struct sock *sk, struct sk_buff *skb)
1722 {
1723         unsigned int truesize = skb->truesize;
1724         struct sk_buff_head xmitq;
1725         u32 dnode, selector;
1726
1727         __skb_queue_head_init(&xmitq);
1728
1729         if (likely(filter_rcv(sk, skb, &xmitq))) {
1730                 atomic_add(truesize, &tipc_sk(sk)->dupl_rcvcnt);
1731                 return 0;
1732         }
1733
1734         if (skb_queue_empty(&xmitq))
1735                 return 0;
1736
1737         /* Send response/rejected message */
1738         skb = __skb_dequeue(&xmitq);
1739         dnode = msg_destnode(buf_msg(skb));
1740         selector = msg_origport(buf_msg(skb));
1741         tipc_node_xmit_skb(sock_net(sk), skb, dnode, selector);
1742         return 0;
1743 }
1744
1745 /**
1746  * tipc_sk_enqueue - extract all buffers with destination 'dport' from
1747  *                   inputq and try adding them to socket or backlog queue
1748  * @inputq: list of incoming buffers with potentially different destinations
1749  * @sk: socket where the buffers should be enqueued
1750  * @dport: port number for the socket
1751  *
1752  * Caller must hold socket lock
1753  */
1754 static void tipc_sk_enqueue(struct sk_buff_head *inputq, struct sock *sk,
1755                             u32 dport, struct sk_buff_head *xmitq)
1756 {
1757         unsigned long time_limit = jiffies + 2;
1758         struct sk_buff *skb;
1759         unsigned int lim;
1760         atomic_t *dcnt;
1761         u32 onode;
1762
1763         while (skb_queue_len(inputq)) {
1764                 if (unlikely(time_after_eq(jiffies, time_limit)))
1765                         return;
1766
1767                 skb = tipc_skb_dequeue(inputq, dport);
1768                 if (unlikely(!skb))
1769                         return;
1770
1771                 /* Add message directly to receive queue if possible */
1772                 if (!sock_owned_by_user(sk)) {
1773                         filter_rcv(sk, skb, xmitq);
1774                         continue;
1775                 }
1776
1777                 /* Try backlog, compensating for double-counted bytes */
1778                 dcnt = &tipc_sk(sk)->dupl_rcvcnt;
1779                 if (!sk->sk_backlog.len)
1780                         atomic_set(dcnt, 0);
1781                 lim = rcvbuf_limit(sk, skb) + atomic_read(dcnt);
1782                 if (likely(!sk_add_backlog(sk, skb, lim)))
1783                         continue;
1784
1785                 /* Overload => reject message back to sender */
1786                 onode = tipc_own_addr(sock_net(sk));
1787                 if (tipc_msg_reverse(onode, &skb, TIPC_ERR_OVERLOAD))
1788                         __skb_queue_tail(xmitq, skb);
1789                 break;
1790         }
1791 }
1792
1793 /**
1794  * tipc_sk_rcv - handle a chain of incoming buffers
1795  * @inputq: buffer list containing the buffers
1796  * Consumes all buffers in list until inputq is empty
1797  * Note: may be called in multiple threads referring to the same queue
1798  */
1799 void tipc_sk_rcv(struct net *net, struct sk_buff_head *inputq)
1800 {
1801         struct sk_buff_head xmitq;
1802         u32 dnode, dport = 0;
1803         int err;
1804         struct tipc_sock *tsk;
1805         struct sock *sk;
1806         struct sk_buff *skb;
1807
1808         __skb_queue_head_init(&xmitq);
1809         while (skb_queue_len(inputq)) {
1810                 dport = tipc_skb_peek_port(inputq, dport);
1811                 tsk = tipc_sk_lookup(net, dport);
1812
1813                 if (likely(tsk)) {
1814                         sk = &tsk->sk;
1815                         if (likely(spin_trylock_bh(&sk->sk_lock.slock))) {
1816                                 tipc_sk_enqueue(inputq, sk, dport, &xmitq);
1817                                 spin_unlock_bh(&sk->sk_lock.slock);
1818                         }
1819                         /* Send pending response/rejected messages, if any */
1820                         while ((skb = __skb_dequeue(&xmitq))) {
1821                                 dnode = msg_destnode(buf_msg(skb));
1822                                 tipc_node_xmit_skb(net, skb, dnode, dport);
1823                         }
1824                         sock_put(sk);
1825                         continue;
1826                 }
1827
1828                 /* No destination socket => dequeue skb if still there */
1829                 skb = tipc_skb_dequeue(inputq, dport);
1830                 if (!skb)
1831                         return;
1832
1833                 /* Try secondary lookup if unresolved named message */
1834                 err = TIPC_ERR_NO_PORT;
1835                 if (tipc_msg_lookup_dest(net, skb, &err))
1836                         goto xmit;
1837
1838                 /* Prepare for message rejection */
1839                 if (!tipc_msg_reverse(tipc_own_addr(net), &skb, err))
1840                         continue;
1841 xmit:
1842                 dnode = msg_destnode(buf_msg(skb));
1843                 tipc_node_xmit_skb(net, skb, dnode, dport);
1844         }
1845 }
1846
1847 static int tipc_wait_for_connect(struct socket *sock, long *timeo_p)
1848 {
1849         struct sock *sk = sock->sk;
1850         DEFINE_WAIT(wait);
1851         int done;
1852
1853         do {
1854                 int err = sock_error(sk);
1855                 if (err)
1856                         return err;
1857                 if (!*timeo_p)
1858                         return -ETIMEDOUT;
1859                 if (signal_pending(current))
1860                         return sock_intr_errno(*timeo_p);
1861
1862                 prepare_to_wait(sk_sleep(sk), &wait, TASK_INTERRUPTIBLE);
1863                 done = sk_wait_event(sk, timeo_p, sock->state != SS_CONNECTING);
1864                 finish_wait(sk_sleep(sk), &wait);
1865         } while (!done);
1866         return 0;
1867 }
1868
1869 /**
1870  * tipc_connect - establish a connection to another TIPC port
1871  * @sock: socket structure
1872  * @dest: socket address for destination port
1873  * @destlen: size of socket address data structure
1874  * @flags: file-related flags associated with socket
1875  *
1876  * Returns 0 on success, errno otherwise
1877  */
1878 static int tipc_connect(struct socket *sock, struct sockaddr *dest,
1879                         int destlen, int flags)
1880 {
1881         struct sock *sk = sock->sk;
1882         struct tipc_sock *tsk = tipc_sk(sk);
1883         struct sockaddr_tipc *dst = (struct sockaddr_tipc *)dest;
1884         struct msghdr m = {NULL,};
1885         long timeout = (flags & O_NONBLOCK) ? 0 : tsk->conn_timeout;
1886         socket_state previous;
1887         int res = 0;
1888
1889         lock_sock(sk);
1890
1891         /* DGRAM/RDM connect(), just save the destaddr */
1892         if (sock->state == SS_READY) {
1893                 if (dst->family == AF_UNSPEC) {
1894                         memset(&tsk->remote, 0, sizeof(struct sockaddr_tipc));
1895                         tsk->connected = 0;
1896                 } else if (destlen != sizeof(struct sockaddr_tipc)) {
1897                         res = -EINVAL;
1898                 } else {
1899                         memcpy(&tsk->remote, dest, destlen);
1900                         tsk->connected = 1;
1901                 }
1902                 goto exit;
1903         }
1904
1905         /*
1906          * Reject connection attempt using multicast address
1907          *
1908          * Note: send_msg() validates the rest of the address fields,
1909          *       so there's no need to do it here
1910          */
1911         if (dst->addrtype == TIPC_ADDR_MCAST) {
1912                 res = -EINVAL;
1913                 goto exit;
1914         }
1915
1916         previous = sock->state;
1917         switch (sock->state) {
1918         case SS_UNCONNECTED:
1919                 /* Send a 'SYN-' to destination */
1920                 m.msg_name = dest;
1921                 m.msg_namelen = destlen;
1922
1923                 /* If connect is in non-blocking case, set MSG_DONTWAIT to
1924                  * indicate send_msg() is never blocked.
1925                  */
1926                 if (!timeout)
1927                         m.msg_flags = MSG_DONTWAIT;
1928
1929                 res = __tipc_sendmsg(sock, &m, 0);
1930                 if ((res < 0) && (res != -EWOULDBLOCK))
1931                         goto exit;
1932
1933                 /* Just entered SS_CONNECTING state; the only
1934                  * difference is that return value in non-blocking
1935                  * case is EINPROGRESS, rather than EALREADY.
1936                  */
1937                 res = -EINPROGRESS;
1938         case SS_CONNECTING:
1939                 if (previous == SS_CONNECTING)
1940                         res = -EALREADY;
1941                 if (!timeout)
1942                         goto exit;
1943                 timeout = msecs_to_jiffies(timeout);
1944                 /* Wait until an 'ACK' or 'RST' arrives, or a timeout occurs */
1945                 res = tipc_wait_for_connect(sock, &timeout);
1946                 break;
1947         case SS_CONNECTED:
1948                 res = -EISCONN;
1949                 break;
1950         default:
1951                 res = -EINVAL;
1952                 break;
1953         }
1954 exit:
1955         release_sock(sk);
1956         return res;
1957 }
1958
1959 /**
1960  * tipc_listen - allow socket to listen for incoming connections
1961  * @sock: socket structure
1962  * @len: (unused)
1963  *
1964  * Returns 0 on success, errno otherwise
1965  */
1966 static int tipc_listen(struct socket *sock, int len)
1967 {
1968         struct sock *sk = sock->sk;
1969         int res;
1970
1971         lock_sock(sk);
1972
1973         if (sock->state != SS_UNCONNECTED)
1974                 res = -EINVAL;
1975         else {
1976                 sock->state = SS_LISTENING;
1977                 res = 0;
1978         }
1979
1980         release_sock(sk);
1981         return res;
1982 }
1983
1984 static int tipc_wait_for_accept(struct socket *sock, long timeo)
1985 {
1986         struct sock *sk = sock->sk;
1987         DEFINE_WAIT(wait);
1988         int err;
1989
1990         /* True wake-one mechanism for incoming connections: only
1991          * one process gets woken up, not the 'whole herd'.
1992          * Since we do not 'race & poll' for established sockets
1993          * anymore, the common case will execute the loop only once.
1994         */
1995         for (;;) {
1996                 prepare_to_wait_exclusive(sk_sleep(sk), &wait,
1997                                           TASK_INTERRUPTIBLE);
1998                 if (timeo && skb_queue_empty(&sk->sk_receive_queue)) {
1999                         release_sock(sk);
2000                         timeo = schedule_timeout(timeo);
2001                         lock_sock(sk);
2002                 }
2003                 err = 0;
2004                 if (!skb_queue_empty(&sk->sk_receive_queue))
2005                         break;
2006                 err = -EINVAL;
2007                 if (sock->state != SS_LISTENING)
2008                         break;
2009                 err = -EAGAIN;
2010                 if (!timeo)
2011                         break;
2012                 err = sock_intr_errno(timeo);
2013                 if (signal_pending(current))
2014                         break;
2015         }
2016         finish_wait(sk_sleep(sk), &wait);
2017         return err;
2018 }
2019
2020 /**
2021  * tipc_accept - wait for connection request
2022  * @sock: listening socket
2023  * @newsock: new socket that is to be connected
2024  * @flags: file-related flags associated with socket
2025  *
2026  * Returns 0 on success, errno otherwise
2027  */
2028 static int tipc_accept(struct socket *sock, struct socket *new_sock, int flags)
2029 {
2030         struct sock *new_sk, *sk = sock->sk;
2031         struct sk_buff *buf;
2032         struct tipc_sock *new_tsock;
2033         struct tipc_msg *msg;
2034         long timeo;
2035         int res;
2036
2037         lock_sock(sk);
2038
2039         if (sock->state != SS_LISTENING) {
2040                 res = -EINVAL;
2041                 goto exit;
2042         }
2043         timeo = sock_rcvtimeo(sk, flags & O_NONBLOCK);
2044         res = tipc_wait_for_accept(sock, timeo);
2045         if (res)
2046                 goto exit;
2047
2048         buf = skb_peek(&sk->sk_receive_queue);
2049
2050         res = tipc_sk_create(sock_net(sock->sk), new_sock, 0, 1);
2051         if (res)
2052                 goto exit;
2053         security_sk_clone(sock->sk, new_sock->sk);
2054
2055         new_sk = new_sock->sk;
2056         new_tsock = tipc_sk(new_sk);
2057         msg = buf_msg(buf);
2058
2059         /* we lock on new_sk; but lockdep sees the lock on sk */
2060         lock_sock_nested(new_sk, SINGLE_DEPTH_NESTING);
2061
2062         /*
2063          * Reject any stray messages received by new socket
2064          * before the socket lock was taken (very, very unlikely)
2065          */
2066         tsk_rej_rx_queue(new_sk);
2067
2068         /* Connect new socket to it's peer */
2069         tipc_sk_finish_conn(new_tsock, msg_origport(msg), msg_orignode(msg));
2070         new_sock->state = SS_CONNECTED;
2071
2072         tsk_set_importance(new_tsock, msg_importance(msg));
2073         if (msg_named(msg)) {
2074                 new_tsock->conn_type = msg_nametype(msg);
2075                 new_tsock->conn_instance = msg_nameinst(msg);
2076         }
2077
2078         /*
2079          * Respond to 'SYN-' by discarding it & returning 'ACK'-.
2080          * Respond to 'SYN+' by queuing it on new socket.
2081          */
2082         if (!msg_data_sz(msg)) {
2083                 struct msghdr m = {NULL,};
2084
2085                 tsk_advance_rx_queue(sk);
2086                 __tipc_send_stream(new_sock, &m, 0);
2087         } else {
2088                 __skb_dequeue(&sk->sk_receive_queue);
2089                 __skb_queue_head(&new_sk->sk_receive_queue, buf);
2090                 skb_set_owner_r(buf, new_sk);
2091         }
2092         release_sock(new_sk);
2093 exit:
2094         release_sock(sk);
2095         return res;
2096 }
2097
2098 /**
2099  * tipc_shutdown - shutdown socket connection
2100  * @sock: socket structure
2101  * @how: direction to close (must be SHUT_RDWR)
2102  *
2103  * Terminates connection (if necessary), then purges socket's receive queue.
2104  *
2105  * Returns 0 on success, errno otherwise
2106  */
2107 static int tipc_shutdown(struct socket *sock, int how)
2108 {
2109         struct sock *sk = sock->sk;
2110         struct net *net = sock_net(sk);
2111         struct tipc_sock *tsk = tipc_sk(sk);
2112         struct sk_buff *skb;
2113         u32 dnode = tsk_peer_node(tsk);
2114         u32 dport = tsk_peer_port(tsk);
2115         u32 onode = tipc_own_addr(net);
2116         u32 oport = tsk->portid;
2117         int res;
2118
2119         if (how != SHUT_RDWR)
2120                 return -EINVAL;
2121
2122         lock_sock(sk);
2123
2124         switch (sock->state) {
2125         case SS_CONNECTING:
2126         case SS_CONNECTED:
2127
2128 restart:
2129                 dnode = tsk_peer_node(tsk);
2130
2131                 /* Disconnect and send a 'FIN+' or 'FIN-' message to peer */
2132                 skb = __skb_dequeue(&sk->sk_receive_queue);
2133                 if (skb) {
2134                         if (TIPC_SKB_CB(skb)->handle != NULL) {
2135                                 kfree_skb(skb);
2136                                 goto restart;
2137                         }
2138                         tipc_sk_respond(sk, skb, TIPC_CONN_SHUTDOWN);
2139                 } else {
2140                         skb = tipc_msg_create(TIPC_CRITICAL_IMPORTANCE,
2141                                               TIPC_CONN_MSG, SHORT_H_SIZE,
2142                                               0, dnode, onode, dport, oport,
2143                                               TIPC_CONN_SHUTDOWN);
2144                         if (skb)
2145                                 tipc_node_xmit_skb(net, skb, dnode, tsk->portid);
2146                 }
2147                 tsk->connected = 0;
2148                 sock->state = SS_DISCONNECTING;
2149                 tipc_node_remove_conn(net, dnode, tsk->portid);
2150                 /* fall through */
2151
2152         case SS_DISCONNECTING:
2153
2154                 /* Discard any unreceived messages */
2155                 __skb_queue_purge(&sk->sk_receive_queue);
2156
2157                 /* Wake up anyone sleeping in poll */
2158                 sk->sk_state_change(sk);
2159                 res = 0;
2160                 break;
2161
2162         default:
2163                 res = -ENOTCONN;
2164         }
2165
2166         release_sock(sk);
2167         return res;
2168 }
2169
2170 static void tipc_sk_timeout(unsigned long data)
2171 {
2172         struct tipc_sock *tsk = (struct tipc_sock *)data;
2173         struct sock *sk = &tsk->sk;
2174         struct sk_buff *skb = NULL;
2175         u32 peer_port, peer_node;
2176         u32 own_node = tsk_own_node(tsk);
2177
2178         bh_lock_sock(sk);
2179         if (!tsk->connected) {
2180                 bh_unlock_sock(sk);
2181                 goto exit;
2182         }
2183         peer_port = tsk_peer_port(tsk);
2184         peer_node = tsk_peer_node(tsk);
2185
2186         if (tsk->probing_state == TIPC_CONN_PROBING) {
2187                 if (!sock_owned_by_user(sk)) {
2188                         sk->sk_socket->state = SS_DISCONNECTING;
2189                         tsk->connected = 0;
2190                         tipc_node_remove_conn(sock_net(sk), tsk_peer_node(tsk),
2191                                               tsk_peer_port(tsk));
2192                         sk->sk_state_change(sk);
2193                 } else {
2194                         /* Try again later */
2195                         sk_reset_timer(sk, &sk->sk_timer, (HZ / 20));
2196                 }
2197
2198         } else {
2199                 skb = tipc_msg_create(CONN_MANAGER, CONN_PROBE,
2200                                       INT_H_SIZE, 0, peer_node, own_node,
2201                                       peer_port, tsk->portid, TIPC_OK);
2202                 tsk->probing_state = TIPC_CONN_PROBING;
2203                 sk_reset_timer(sk, &sk->sk_timer, jiffies + tsk->probing_intv);
2204         }
2205         bh_unlock_sock(sk);
2206         if (skb)
2207                 tipc_node_xmit_skb(sock_net(sk), skb, peer_node, tsk->portid);
2208 exit:
2209         sock_put(sk);
2210 }
2211
2212 static int tipc_sk_publish(struct tipc_sock *tsk, uint scope,
2213                            struct tipc_name_seq const *seq)
2214 {
2215         struct net *net = sock_net(&tsk->sk);
2216         struct publication *publ;
2217         u32 key;
2218
2219         if (tsk->connected)
2220                 return -EINVAL;
2221         key = tsk->portid + tsk->pub_count + 1;
2222         if (key == tsk->portid)
2223                 return -EADDRINUSE;
2224
2225         publ = tipc_nametbl_publish(net, seq->type, seq->lower, seq->upper,
2226                                     scope, tsk->portid, key);
2227         if (unlikely(!publ))
2228                 return -EINVAL;
2229
2230         list_add(&publ->pport_list, &tsk->publications);
2231         tsk->pub_count++;
2232         tsk->published = 1;
2233         return 0;
2234 }
2235
2236 static int tipc_sk_withdraw(struct tipc_sock *tsk, uint scope,
2237                             struct tipc_name_seq const *seq)
2238 {
2239         struct net *net = sock_net(&tsk->sk);
2240         struct publication *publ;
2241         struct publication *safe;
2242         int rc = -EINVAL;
2243
2244         list_for_each_entry_safe(publ, safe, &tsk->publications, pport_list) {
2245                 if (seq) {
2246                         if (publ->scope != scope)
2247                                 continue;
2248                         if (publ->type != seq->type)
2249                                 continue;
2250                         if (publ->lower != seq->lower)
2251                                 continue;
2252                         if (publ->upper != seq->upper)
2253                                 break;
2254                         tipc_nametbl_withdraw(net, publ->type, publ->lower,
2255                                               publ->ref, publ->key);
2256                         rc = 0;
2257                         break;
2258                 }
2259                 tipc_nametbl_withdraw(net, publ->type, publ->lower,
2260                                       publ->ref, publ->key);
2261                 rc = 0;
2262         }
2263         if (list_empty(&tsk->publications))
2264                 tsk->published = 0;
2265         return rc;
2266 }
2267
2268 /* tipc_sk_reinit: set non-zero address in all existing sockets
2269  *                 when we go from standalone to network mode.
2270  */
2271 void tipc_sk_reinit(struct net *net)
2272 {
2273         struct tipc_net *tn = net_generic(net, tipc_net_id);
2274         const struct bucket_table *tbl;
2275         struct rhash_head *pos;
2276         struct tipc_sock *tsk;
2277         struct tipc_msg *msg;
2278         int i;
2279
2280         rcu_read_lock();
2281         tbl = rht_dereference_rcu((&tn->sk_rht)->tbl, &tn->sk_rht);
2282         for (i = 0; i < tbl->size; i++) {
2283                 rht_for_each_entry_rcu(tsk, pos, tbl, i, node) {
2284                         spin_lock_bh(&tsk->sk.sk_lock.slock);
2285                         msg = &tsk->phdr;
2286                         msg_set_prevnode(msg, tn->own_addr);
2287                         msg_set_orignode(msg, tn->own_addr);
2288                         spin_unlock_bh(&tsk->sk.sk_lock.slock);
2289                 }
2290         }
2291         rcu_read_unlock();
2292 }
2293
2294 static struct tipc_sock *tipc_sk_lookup(struct net *net, u32 portid)
2295 {
2296         struct tipc_net *tn = net_generic(net, tipc_net_id);
2297         struct tipc_sock *tsk;
2298
2299         rcu_read_lock();
2300         tsk = rhashtable_lookup_fast(&tn->sk_rht, &portid, tsk_rht_params);
2301         if (tsk)
2302                 sock_hold(&tsk->sk);
2303         rcu_read_unlock();
2304
2305         return tsk;
2306 }
2307
2308 static int tipc_sk_insert(struct tipc_sock *tsk)
2309 {
2310         struct sock *sk = &tsk->sk;
2311         struct net *net = sock_net(sk);
2312         struct tipc_net *tn = net_generic(net, tipc_net_id);
2313         u32 remaining = (TIPC_MAX_PORT - TIPC_MIN_PORT) + 1;
2314         u32 portid = prandom_u32() % remaining + TIPC_MIN_PORT;
2315
2316         while (remaining--) {
2317                 portid++;
2318                 if ((portid < TIPC_MIN_PORT) || (portid > TIPC_MAX_PORT))
2319                         portid = TIPC_MIN_PORT;
2320                 tsk->portid = portid;
2321                 sock_hold(&tsk->sk);
2322                 if (!rhashtable_lookup_insert_fast(&tn->sk_rht, &tsk->node,
2323                                                    tsk_rht_params))
2324                         return 0;
2325                 sock_put(&tsk->sk);
2326         }
2327
2328         return -1;
2329 }
2330
2331 static void tipc_sk_remove(struct tipc_sock *tsk)
2332 {
2333         struct sock *sk = &tsk->sk;
2334         struct tipc_net *tn = net_generic(sock_net(sk), tipc_net_id);
2335
2336         if (!rhashtable_remove_fast(&tn->sk_rht, &tsk->node, tsk_rht_params)) {
2337                 WARN_ON(atomic_read(&sk->sk_refcnt) == 1);
2338                 __sock_put(sk);
2339         }
2340 }
2341
2342 static const struct rhashtable_params tsk_rht_params = {
2343         .nelem_hint = 192,
2344         .head_offset = offsetof(struct tipc_sock, node),
2345         .key_offset = offsetof(struct tipc_sock, portid),
2346         .key_len = sizeof(u32), /* portid */
2347         .max_size = 1048576,
2348         .min_size = 256,
2349         .automatic_shrinking = true,
2350 };
2351
2352 int tipc_sk_rht_init(struct net *net)
2353 {
2354         struct tipc_net *tn = net_generic(net, tipc_net_id);
2355
2356         return rhashtable_init(&tn->sk_rht, &tsk_rht_params);
2357 }
2358
2359 void tipc_sk_rht_destroy(struct net *net)
2360 {
2361         struct tipc_net *tn = net_generic(net, tipc_net_id);
2362
2363         /* Wait for socket readers to complete */
2364         synchronize_net();
2365
2366         rhashtable_destroy(&tn->sk_rht);
2367 }
2368
2369 /**
2370  * tipc_setsockopt - set socket option
2371  * @sock: socket structure
2372  * @lvl: option level
2373  * @opt: option identifier
2374  * @ov: pointer to new option value
2375  * @ol: length of option value
2376  *
2377  * For stream sockets only, accepts and ignores all IPPROTO_TCP options
2378  * (to ease compatibility).
2379  *
2380  * Returns 0 on success, errno otherwise
2381  */
2382 static int tipc_setsockopt(struct socket *sock, int lvl, int opt,
2383                            char __user *ov, unsigned int ol)
2384 {
2385         struct sock *sk = sock->sk;
2386         struct tipc_sock *tsk = tipc_sk(sk);
2387         u32 value;
2388         int res;
2389
2390         if ((lvl == IPPROTO_TCP) && (sock->type == SOCK_STREAM))
2391                 return 0;
2392         if (lvl != SOL_TIPC)
2393                 return -ENOPROTOOPT;
2394         if (ol < sizeof(value))
2395                 return -EINVAL;
2396         res = get_user(value, (u32 __user *)ov);
2397         if (res)
2398                 return res;
2399
2400         lock_sock(sk);
2401
2402         switch (opt) {
2403         case TIPC_IMPORTANCE:
2404                 res = tsk_set_importance(tsk, value);
2405                 break;
2406         case TIPC_SRC_DROPPABLE:
2407                 if (sock->type != SOCK_STREAM)
2408                         tsk_set_unreliable(tsk, value);
2409                 else
2410                         res = -ENOPROTOOPT;
2411                 break;
2412         case TIPC_DEST_DROPPABLE:
2413                 tsk_set_unreturnable(tsk, value);
2414                 break;
2415         case TIPC_CONN_TIMEOUT:
2416                 tipc_sk(sk)->conn_timeout = value;
2417                 /* no need to set "res", since already 0 at this point */
2418                 break;
2419         default:
2420                 res = -EINVAL;
2421         }
2422
2423         release_sock(sk);
2424
2425         return res;
2426 }
2427
2428 /**
2429  * tipc_getsockopt - get socket option
2430  * @sock: socket structure
2431  * @lvl: option level
2432  * @opt: option identifier
2433  * @ov: receptacle for option value
2434  * @ol: receptacle for length of option value
2435  *
2436  * For stream sockets only, returns 0 length result for all IPPROTO_TCP options
2437  * (to ease compatibility).
2438  *
2439  * Returns 0 on success, errno otherwise
2440  */
2441 static int tipc_getsockopt(struct socket *sock, int lvl, int opt,
2442                            char __user *ov, int __user *ol)
2443 {
2444         struct sock *sk = sock->sk;
2445         struct tipc_sock *tsk = tipc_sk(sk);
2446         int len;
2447         u32 value;
2448         int res;
2449
2450         if ((lvl == IPPROTO_TCP) && (sock->type == SOCK_STREAM))
2451                 return put_user(0, ol);
2452         if (lvl != SOL_TIPC)
2453                 return -ENOPROTOOPT;
2454         res = get_user(len, ol);
2455         if (res)
2456                 return res;
2457
2458         lock_sock(sk);
2459
2460         switch (opt) {
2461         case TIPC_IMPORTANCE:
2462                 value = tsk_importance(tsk);
2463                 break;
2464         case TIPC_SRC_DROPPABLE:
2465                 value = tsk_unreliable(tsk);
2466                 break;
2467         case TIPC_DEST_DROPPABLE:
2468                 value = tsk_unreturnable(tsk);
2469                 break;
2470         case TIPC_CONN_TIMEOUT:
2471                 value = tsk->conn_timeout;
2472                 /* no need to set "res", since already 0 at this point */
2473                 break;
2474         case TIPC_NODE_RECVQ_DEPTH:
2475                 value = 0; /* was tipc_queue_size, now obsolete */
2476                 break;
2477         case TIPC_SOCK_RECVQ_DEPTH:
2478                 value = skb_queue_len(&sk->sk_receive_queue);
2479                 break;
2480         default:
2481                 res = -EINVAL;
2482         }
2483
2484         release_sock(sk);
2485
2486         if (res)
2487                 return res;     /* "get" failed */
2488
2489         if (len < sizeof(value))
2490                 return -EINVAL;
2491
2492         if (copy_to_user(ov, &value, sizeof(value)))
2493                 return -EFAULT;
2494
2495         return put_user(sizeof(value), ol);
2496 }
2497
2498 static int tipc_ioctl(struct socket *sock, unsigned int cmd, unsigned long arg)
2499 {
2500         struct sock *sk = sock->sk;
2501         struct tipc_sioc_ln_req lnr;
2502         void __user *argp = (void __user *)arg;
2503
2504         switch (cmd) {
2505         case SIOCGETLINKNAME:
2506                 if (copy_from_user(&lnr, argp, sizeof(lnr)))
2507                         return -EFAULT;
2508                 if (!tipc_node_get_linkname(sock_net(sk),
2509                                             lnr.bearer_id & 0xffff, lnr.peer,
2510                                             lnr.linkname, TIPC_MAX_LINK_NAME)) {
2511                         if (copy_to_user(argp, &lnr, sizeof(lnr)))
2512                                 return -EFAULT;
2513                         return 0;
2514                 }
2515                 return -EADDRNOTAVAIL;
2516         default:
2517                 return -ENOIOCTLCMD;
2518         }
2519 }
2520
2521 /* Protocol switches for the various types of TIPC sockets */
2522
2523 static const struct proto_ops msg_ops = {
2524         .owner          = THIS_MODULE,
2525         .family         = AF_TIPC,
2526         .release        = tipc_release,
2527         .bind           = tipc_bind,
2528         .connect        = tipc_connect,
2529         .socketpair     = sock_no_socketpair,
2530         .accept         = sock_no_accept,
2531         .getname        = tipc_getname,
2532         .poll           = tipc_poll,
2533         .ioctl          = tipc_ioctl,
2534         .listen         = sock_no_listen,
2535         .shutdown       = tipc_shutdown,
2536         .setsockopt     = tipc_setsockopt,
2537         .getsockopt     = tipc_getsockopt,
2538         .sendmsg        = tipc_sendmsg,
2539         .recvmsg        = tipc_recvmsg,
2540         .mmap           = sock_no_mmap,
2541         .sendpage       = sock_no_sendpage
2542 };
2543
2544 static const struct proto_ops packet_ops = {
2545         .owner          = THIS_MODULE,
2546         .family         = AF_TIPC,
2547         .release        = tipc_release,
2548         .bind           = tipc_bind,
2549         .connect        = tipc_connect,
2550         .socketpair     = sock_no_socketpair,
2551         .accept         = tipc_accept,
2552         .getname        = tipc_getname,
2553         .poll           = tipc_poll,
2554         .ioctl          = tipc_ioctl,
2555         .listen         = tipc_listen,
2556         .shutdown       = tipc_shutdown,
2557         .setsockopt     = tipc_setsockopt,
2558         .getsockopt     = tipc_getsockopt,
2559         .sendmsg        = tipc_send_packet,
2560         .recvmsg        = tipc_recvmsg,
2561         .mmap           = sock_no_mmap,
2562         .sendpage       = sock_no_sendpage
2563 };
2564
2565 static const struct proto_ops stream_ops = {
2566         .owner          = THIS_MODULE,
2567         .family         = AF_TIPC,
2568         .release        = tipc_release,
2569         .bind           = tipc_bind,
2570         .connect        = tipc_connect,
2571         .socketpair     = sock_no_socketpair,
2572         .accept         = tipc_accept,
2573         .getname        = tipc_getname,
2574         .poll           = tipc_poll,
2575         .ioctl          = tipc_ioctl,
2576         .listen         = tipc_listen,
2577         .shutdown       = tipc_shutdown,
2578         .setsockopt     = tipc_setsockopt,
2579         .getsockopt     = tipc_getsockopt,
2580         .sendmsg        = tipc_send_stream,
2581         .recvmsg        = tipc_recv_stream,
2582         .mmap           = sock_no_mmap,
2583         .sendpage       = sock_no_sendpage
2584 };
2585
2586 static const struct net_proto_family tipc_family_ops = {
2587         .owner          = THIS_MODULE,
2588         .family         = AF_TIPC,
2589         .create         = tipc_sk_create
2590 };
2591
2592 static struct proto tipc_proto = {
2593         .name           = "TIPC",
2594         .owner          = THIS_MODULE,
2595         .obj_size       = sizeof(struct tipc_sock),
2596         .sysctl_rmem    = sysctl_tipc_rmem
2597 };
2598
2599 /**
2600  * tipc_socket_init - initialize TIPC socket interface
2601  *
2602  * Returns 0 on success, errno otherwise
2603  */
2604 int tipc_socket_init(void)
2605 {
2606         int res;
2607
2608         res = proto_register(&tipc_proto, 1);
2609         if (res) {
2610                 pr_err("Failed to register TIPC protocol type\n");
2611                 goto out;
2612         }
2613
2614         res = sock_register(&tipc_family_ops);
2615         if (res) {
2616                 pr_err("Failed to register TIPC socket type\n");
2617                 proto_unregister(&tipc_proto);
2618                 goto out;
2619         }
2620  out:
2621         return res;
2622 }
2623
2624 /**
2625  * tipc_socket_stop - stop TIPC socket interface
2626  */
2627 void tipc_socket_stop(void)
2628 {
2629         sock_unregister(tipc_family_ops.family);
2630         proto_unregister(&tipc_proto);
2631 }
2632
2633 /* Caller should hold socket lock for the passed tipc socket. */
2634 static int __tipc_nl_add_sk_con(struct sk_buff *skb, struct tipc_sock *tsk)
2635 {
2636         u32 peer_node;
2637         u32 peer_port;
2638         struct nlattr *nest;
2639
2640         peer_node = tsk_peer_node(tsk);
2641         peer_port = tsk_peer_port(tsk);
2642
2643         nest = nla_nest_start(skb, TIPC_NLA_SOCK_CON);
2644
2645         if (nla_put_u32(skb, TIPC_NLA_CON_NODE, peer_node))
2646                 goto msg_full;
2647         if (nla_put_u32(skb, TIPC_NLA_CON_SOCK, peer_port))
2648                 goto msg_full;
2649
2650         if (tsk->conn_type != 0) {
2651                 if (nla_put_flag(skb, TIPC_NLA_CON_FLAG))
2652                         goto msg_full;
2653                 if (nla_put_u32(skb, TIPC_NLA_CON_TYPE, tsk->conn_type))
2654                         goto msg_full;
2655                 if (nla_put_u32(skb, TIPC_NLA_CON_INST, tsk->conn_instance))
2656                         goto msg_full;
2657         }
2658         nla_nest_end(skb, nest);
2659
2660         return 0;
2661
2662 msg_full:
2663         nla_nest_cancel(skb, nest);
2664
2665         return -EMSGSIZE;
2666 }
2667
2668 /* Caller should hold socket lock for the passed tipc socket. */
2669 static int __tipc_nl_add_sk(struct sk_buff *skb, struct netlink_callback *cb,
2670                             struct tipc_sock *tsk)
2671 {
2672         int err;
2673         void *hdr;
2674         struct nlattr *attrs;
2675         struct net *net = sock_net(skb->sk);
2676         struct tipc_net *tn = net_generic(net, tipc_net_id);
2677
2678         hdr = genlmsg_put(skb, NETLINK_CB(cb->skb).portid, cb->nlh->nlmsg_seq,
2679                           &tipc_genl_family, NLM_F_MULTI, TIPC_NL_SOCK_GET);
2680         if (!hdr)
2681                 goto msg_cancel;
2682
2683         attrs = nla_nest_start(skb, TIPC_NLA_SOCK);
2684         if (!attrs)
2685                 goto genlmsg_cancel;
2686         if (nla_put_u32(skb, TIPC_NLA_SOCK_REF, tsk->portid))
2687                 goto attr_msg_cancel;
2688         if (nla_put_u32(skb, TIPC_NLA_SOCK_ADDR, tn->own_addr))
2689                 goto attr_msg_cancel;
2690
2691         if (tsk->connected) {
2692                 err = __tipc_nl_add_sk_con(skb, tsk);
2693                 if (err)
2694                         goto attr_msg_cancel;
2695         } else if (!list_empty(&tsk->publications)) {
2696                 if (nla_put_flag(skb, TIPC_NLA_SOCK_HAS_PUBL))
2697                         goto attr_msg_cancel;
2698         }
2699         nla_nest_end(skb, attrs);
2700         genlmsg_end(skb, hdr);
2701
2702         return 0;
2703
2704 attr_msg_cancel:
2705         nla_nest_cancel(skb, attrs);
2706 genlmsg_cancel:
2707         genlmsg_cancel(skb, hdr);
2708 msg_cancel:
2709         return -EMSGSIZE;
2710 }
2711
2712 int tipc_nl_sk_dump(struct sk_buff *skb, struct netlink_callback *cb)
2713 {
2714         int err;
2715         struct tipc_sock *tsk;
2716         const struct bucket_table *tbl;
2717         struct rhash_head *pos;
2718         struct net *net = sock_net(skb->sk);
2719         struct tipc_net *tn = net_generic(net, tipc_net_id);
2720         u32 tbl_id = cb->args[0];
2721         u32 prev_portid = cb->args[1];
2722
2723         rcu_read_lock();
2724         tbl = rht_dereference_rcu((&tn->sk_rht)->tbl, &tn->sk_rht);
2725         for (; tbl_id < tbl->size; tbl_id++) {
2726                 rht_for_each_entry_rcu(tsk, pos, tbl, tbl_id, node) {
2727                         spin_lock_bh(&tsk->sk.sk_lock.slock);
2728                         if (prev_portid && prev_portid != tsk->portid) {
2729                                 spin_unlock_bh(&tsk->sk.sk_lock.slock);
2730                                 continue;
2731                         }
2732
2733                         err = __tipc_nl_add_sk(skb, cb, tsk);
2734                         if (err) {
2735                                 prev_portid = tsk->portid;
2736                                 spin_unlock_bh(&tsk->sk.sk_lock.slock);
2737                                 goto out;
2738                         }
2739                         prev_portid = 0;
2740                         spin_unlock_bh(&tsk->sk.sk_lock.slock);
2741                 }
2742         }
2743 out:
2744         rcu_read_unlock();
2745         cb->args[0] = tbl_id;
2746         cb->args[1] = prev_portid;
2747
2748         return skb->len;
2749 }
2750
2751 /* Caller should hold socket lock for the passed tipc socket. */
2752 static int __tipc_nl_add_sk_publ(struct sk_buff *skb,
2753                                  struct netlink_callback *cb,
2754                                  struct publication *publ)
2755 {
2756         void *hdr;
2757         struct nlattr *attrs;
2758
2759         hdr = genlmsg_put(skb, NETLINK_CB(cb->skb).portid, cb->nlh->nlmsg_seq,
2760                           &tipc_genl_family, NLM_F_MULTI, TIPC_NL_PUBL_GET);
2761         if (!hdr)
2762                 goto msg_cancel;
2763
2764         attrs = nla_nest_start(skb, TIPC_NLA_PUBL);
2765         if (!attrs)
2766                 goto genlmsg_cancel;
2767
2768         if (nla_put_u32(skb, TIPC_NLA_PUBL_KEY, publ->key))
2769                 goto attr_msg_cancel;
2770         if (nla_put_u32(skb, TIPC_NLA_PUBL_TYPE, publ->type))
2771                 goto attr_msg_cancel;
2772         if (nla_put_u32(skb, TIPC_NLA_PUBL_LOWER, publ->lower))
2773                 goto attr_msg_cancel;
2774         if (nla_put_u32(skb, TIPC_NLA_PUBL_UPPER, publ->upper))
2775                 goto attr_msg_cancel;
2776
2777         nla_nest_end(skb, attrs);
2778         genlmsg_end(skb, hdr);
2779
2780         return 0;
2781
2782 attr_msg_cancel:
2783         nla_nest_cancel(skb, attrs);
2784 genlmsg_cancel:
2785         genlmsg_cancel(skb, hdr);
2786 msg_cancel:
2787         return -EMSGSIZE;
2788 }
2789
2790 /* Caller should hold socket lock for the passed tipc socket. */
2791 static int __tipc_nl_list_sk_publ(struct sk_buff *skb,
2792                                   struct netlink_callback *cb,
2793                                   struct tipc_sock *tsk, u32 *last_publ)
2794 {
2795         int err;
2796         struct publication *p;
2797
2798         if (*last_publ) {
2799                 list_for_each_entry(p, &tsk->publications, pport_list) {
2800                         if (p->key == *last_publ)
2801                                 break;
2802                 }
2803                 if (p->key != *last_publ) {
2804                         /* We never set seq or call nl_dump_check_consistent()
2805                          * this means that setting prev_seq here will cause the
2806                          * consistence check to fail in the netlink callback
2807                          * handler. Resulting in the last NLMSG_DONE message
2808                          * having the NLM_F_DUMP_INTR flag set.
2809                          */
2810                         cb->prev_seq = 1;
2811                         *last_publ = 0;
2812                         return -EPIPE;
2813                 }
2814         } else {
2815                 p = list_first_entry(&tsk->publications, struct publication,
2816                                      pport_list);
2817         }
2818
2819         list_for_each_entry_from(p, &tsk->publications, pport_list) {
2820                 err = __tipc_nl_add_sk_publ(skb, cb, p);
2821                 if (err) {
2822                         *last_publ = p->key;
2823                         return err;
2824                 }
2825         }
2826         *last_publ = 0;
2827
2828         return 0;
2829 }
2830
2831 int tipc_nl_publ_dump(struct sk_buff *skb, struct netlink_callback *cb)
2832 {
2833         int err;
2834         u32 tsk_portid = cb->args[0];
2835         u32 last_publ = cb->args[1];
2836         u32 done = cb->args[2];
2837         struct net *net = sock_net(skb->sk);
2838         struct tipc_sock *tsk;
2839
2840         if (!tsk_portid) {
2841                 struct nlattr **attrs;
2842                 struct nlattr *sock[TIPC_NLA_SOCK_MAX + 1];
2843
2844                 err = tipc_nlmsg_parse(cb->nlh, &attrs);
2845                 if (err)
2846                         return err;
2847
2848                 if (!attrs[TIPC_NLA_SOCK])
2849                         return -EINVAL;
2850
2851                 err = nla_parse_nested(sock, TIPC_NLA_SOCK_MAX,
2852                                        attrs[TIPC_NLA_SOCK],
2853                                        tipc_nl_sock_policy);
2854                 if (err)
2855                         return err;
2856
2857                 if (!sock[TIPC_NLA_SOCK_REF])
2858                         return -EINVAL;
2859
2860                 tsk_portid = nla_get_u32(sock[TIPC_NLA_SOCK_REF]);
2861         }
2862
2863         if (done)
2864                 return 0;
2865
2866         tsk = tipc_sk_lookup(net, tsk_portid);
2867         if (!tsk)
2868                 return -EINVAL;
2869
2870         lock_sock(&tsk->sk);
2871         err = __tipc_nl_list_sk_publ(skb, cb, tsk, &last_publ);
2872         if (!err)
2873                 done = 1;
2874         release_sock(&tsk->sk);
2875         sock_put(&tsk->sk);
2876
2877         cb->args[0] = tsk_portid;
2878         cb->args[1] = last_publ;
2879         cb->args[2] = done;
2880
2881         return skb->len;
2882 }