2 * net/tipc/socket.c: TIPC socket API
4 * Copyright (c) 2001-2007, 2012-2014, Ericsson AB
5 * Copyright (c) 2004-2008, 2010-2013, Wind River Systems
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions are met:
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.
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.
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.
40 #include "name_table.h"
43 #include <linux/export.h>
46 #define SS_LISTENING -1 /* socket is listening */
47 #define SS_READY -2 /* socket is connectionless */
49 #define CONN_TIMEOUT_DEFAULT 8000 /* default connect timeout = 8s */
50 #define CONN_PROBING_INTERVAL 3600000 /* [ms] => 1 h */
51 #define TIPC_FWD_MSG 1
53 static int tipc_backlog_rcv(struct sock *sk, struct sk_buff *skb);
54 static void tipc_data_ready(struct sock *sk);
55 static void tipc_write_space(struct sock *sk);
56 static int tipc_release(struct socket *sock);
57 static int tipc_accept(struct socket *sock, struct socket *new_sock, int flags);
58 static int tipc_wait_for_sndmsg(struct socket *sock, long *timeo_p);
59 static void tipc_sk_timeout(unsigned long ref);
60 static int tipc_sk_publish(struct tipc_port *port, uint scope,
61 struct tipc_name_seq const *seq);
62 static int tipc_sk_withdraw(struct tipc_port *port, uint scope,
63 struct tipc_name_seq const *seq);
65 static const struct proto_ops packet_ops;
66 static const struct proto_ops stream_ops;
67 static const struct proto_ops msg_ops;
69 static struct proto tipc_proto;
70 static struct proto tipc_proto_kern;
73 * Revised TIPC socket locking policy:
75 * Most socket operations take the standard socket lock when they start
76 * and hold it until they finish (or until they need to sleep). Acquiring
77 * this lock grants the owner exclusive access to the fields of the socket
78 * data structures, with the exception of the backlog queue. A few socket
79 * operations can be done without taking the socket lock because they only
80 * read socket information that never changes during the life of the socket.
82 * Socket operations may acquire the lock for the associated TIPC port if they
83 * need to perform an operation on the port. If any routine needs to acquire
84 * both the socket lock and the port lock it must take the socket lock first
85 * to avoid the risk of deadlock.
87 * The dispatcher handling incoming messages cannot grab the socket lock in
88 * the standard fashion, since invoked it runs at the BH level and cannot block.
89 * Instead, it checks to see if the socket lock is currently owned by someone,
90 * and either handles the message itself or adds it to the socket's backlog
91 * queue; in the latter case the queued message is processed once the process
92 * owning the socket lock releases it.
94 * NOTE: Releasing the socket lock while an operation is sleeping overcomes
95 * the problem of a blocked socket operation preventing any other operations
96 * from occurring. However, applications must be careful if they have
97 * multiple threads trying to send (or receive) on the same socket, as these
98 * operations might interfere with each other. For example, doing a connect
99 * and a receive at the same time might allow the receive to consume the
100 * ACK message meant for the connect. While additional work could be done
101 * to try and overcome this, it doesn't seem to be worthwhile at the present.
103 * NOTE: Releasing the socket lock while an operation is sleeping also ensures
104 * that another operation that must be performed in a non-blocking manner is
105 * not delayed for very long because the lock has already been taken.
107 * NOTE: This code assumes that certain fields of a port/socket pair are
108 * constant over its lifetime; such fields can be examined without taking
109 * the socket lock and/or port lock, and do not need to be re-read even
110 * after resuming processing after waiting. These fields include:
112 * - pointer to socket sk structure (aka tipc_sock structure)
113 * - pointer to port structure
120 * advance_rx_queue - discard first buffer in socket receive queue
122 * Caller must hold socket lock
124 static void advance_rx_queue(struct sock *sk)
126 kfree_skb(__skb_dequeue(&sk->sk_receive_queue));
130 * reject_rx_queue - reject all buffers in socket receive queue
132 * Caller must hold socket lock
134 static void reject_rx_queue(struct sock *sk)
139 while ((buf = __skb_dequeue(&sk->sk_receive_queue))) {
140 if (tipc_msg_reverse(buf, &dnode, TIPC_ERR_NO_PORT))
141 tipc_link_xmit(buf, dnode, 0);
145 /* tipc_sk_peer_msg - verify if message was sent by connected port's peer
147 * Handles cases where the node's network address has changed from
148 * the default of <0.0.0> to its configured setting.
150 static bool tipc_sk_peer_msg(struct tipc_sock *tsk, struct tipc_msg *msg)
152 u32 peer_port = tipc_port_peerport(&tsk->port);
156 if (unlikely(!tsk->port.connected))
159 if (unlikely(msg_origport(msg) != peer_port))
162 orig_node = msg_orignode(msg);
163 peer_node = tipc_port_peernode(&tsk->port);
165 if (likely(orig_node == peer_node))
168 if (!orig_node && (peer_node == tipc_own_addr))
171 if (!peer_node && (orig_node == tipc_own_addr))
178 * tipc_sk_create - create a TIPC socket
179 * @net: network namespace (must be default network)
180 * @sock: pre-allocated socket structure
181 * @protocol: protocol indicator (must be 0)
182 * @kern: caused by kernel or by userspace?
184 * This routine creates additional data structures used by the TIPC socket,
185 * initializes them, and links them together.
187 * Returns 0 on success, errno otherwise
189 static int tipc_sk_create(struct net *net, struct socket *sock,
190 int protocol, int kern)
192 const struct proto_ops *ops;
195 struct tipc_sock *tsk;
196 struct tipc_port *port;
197 struct tipc_msg *msg;
200 /* Validate arguments */
201 if (unlikely(protocol != 0))
202 return -EPROTONOSUPPORT;
204 switch (sock->type) {
207 state = SS_UNCONNECTED;
211 state = SS_UNCONNECTED;
222 /* Allocate socket's protocol area */
224 sk = sk_alloc(net, AF_TIPC, GFP_KERNEL, &tipc_proto);
226 sk = sk_alloc(net, AF_TIPC, GFP_KERNEL, &tipc_proto_kern);
233 ref = tipc_ref_acquire(tsk);
235 pr_warn("Socket create failed; reference table exhausted\n");
238 port->max_pkt = MAX_PKT_DEFAULT;
240 INIT_LIST_HEAD(&port->publications);
243 tipc_msg_init(msg, TIPC_LOW_IMPORTANCE, TIPC_NAMED_MSG,
245 msg_set_origport(msg, ref);
247 /* Finish initializing socket data structures */
250 sock_init_data(sock, sk);
251 k_init_timer(&port->timer, (Handler)tipc_sk_timeout, ref);
252 sk->sk_backlog_rcv = tipc_backlog_rcv;
253 sk->sk_rcvbuf = sysctl_tipc_rmem[1];
254 sk->sk_data_ready = tipc_data_ready;
255 sk->sk_write_space = tipc_write_space;
256 tsk->conn_timeout = CONN_TIMEOUT_DEFAULT;
257 tsk->sent_unacked = 0;
258 atomic_set(&tsk->dupl_rcvcnt, 0);
260 if (sock->state == SS_READY) {
261 tipc_port_set_unreturnable(port, true);
262 if (sock->type == SOCK_DGRAM)
263 tipc_port_set_unreliable(port, true);
269 * tipc_sock_create_local - create TIPC socket from inside TIPC module
270 * @type: socket type - SOCK_RDM or SOCK_SEQPACKET
272 * We cannot use sock_creat_kern here because it bumps module user count.
273 * Since socket owner and creator is the same module we must make sure
274 * that module count remains zero for module local sockets, otherwise
275 * we cannot do rmmod.
277 * Returns 0 on success, errno otherwise
279 int tipc_sock_create_local(int type, struct socket **res)
283 rc = sock_create_lite(AF_TIPC, type, 0, res);
285 pr_err("Failed to create kernel socket\n");
288 tipc_sk_create(&init_net, *res, 0, 1);
294 * tipc_sock_release_local - release socket created by tipc_sock_create_local
295 * @sock: the socket to be released.
297 * Module reference count is not incremented when such sockets are created,
298 * so we must keep it from being decremented when they are released.
300 void tipc_sock_release_local(struct socket *sock)
308 * tipc_sock_accept_local - accept a connection on a socket created
309 * with tipc_sock_create_local. Use this function to avoid that
310 * module reference count is inadvertently incremented.
312 * @sock: the accepting socket
313 * @newsock: reference to the new socket to be created
314 * @flags: socket flags
317 int tipc_sock_accept_local(struct socket *sock, struct socket **newsock,
320 struct sock *sk = sock->sk;
323 ret = sock_create_lite(sk->sk_family, sk->sk_type,
324 sk->sk_protocol, newsock);
328 ret = tipc_accept(sock, *newsock, flags);
330 sock_release(*newsock);
333 (*newsock)->ops = sock->ops;
338 * tipc_release - destroy a TIPC socket
339 * @sock: socket to destroy
341 * This routine cleans up any messages that are still queued on the socket.
342 * For DGRAM and RDM socket types, all queued messages are rejected.
343 * For SEQPACKET and STREAM socket types, the first message is rejected
344 * and any others are discarded. (If the first message on a STREAM socket
345 * is partially-read, it is discarded and the next one is rejected instead.)
347 * NOTE: Rejected messages are not necessarily returned to the sender! They
348 * are returned or discarded according to the "destination droppable" setting
349 * specified for the message by the sender.
351 * Returns 0 on success, errno otherwise
353 static int tipc_release(struct socket *sock)
355 struct sock *sk = sock->sk;
356 struct tipc_sock *tsk;
357 struct tipc_port *port;
362 * Exit if socket isn't fully initialized (occurs when a failed accept()
363 * releases a pre-allocated child socket that was never used)
373 * Reject all unreceived messages, except on an active connection
374 * (which disconnects locally & sends a 'FIN+' to peer)
376 dnode = tipc_port_peernode(port);
377 while (sock->state != SS_DISCONNECTING) {
378 buf = __skb_dequeue(&sk->sk_receive_queue);
381 if (TIPC_SKB_CB(buf)->handle != NULL)
384 if ((sock->state == SS_CONNECTING) ||
385 (sock->state == SS_CONNECTED)) {
386 sock->state = SS_DISCONNECTING;
388 tipc_node_remove_conn(dnode, port->ref);
390 if (tipc_msg_reverse(buf, &dnode, TIPC_ERR_NO_PORT))
391 tipc_link_xmit(buf, dnode, 0);
395 tipc_sk_withdraw(port, 0, NULL);
396 tipc_ref_discard(port->ref);
397 k_cancel_timer(&port->timer);
398 if (port->connected) {
399 buf = tipc_msg_create(TIPC_CRITICAL_IMPORTANCE, TIPC_CONN_MSG,
400 SHORT_H_SIZE, 0, dnode, tipc_own_addr,
401 tipc_port_peerport(port),
402 port->ref, TIPC_ERR_NO_PORT);
404 tipc_link_xmit(buf, dnode, port->ref);
405 tipc_node_remove_conn(dnode, port->ref);
407 k_term_timer(&port->timer);
409 /* Discard any remaining (connection-based) messages in receive queue */
410 __skb_queue_purge(&sk->sk_receive_queue);
412 /* Reject any messages that accumulated in backlog queue */
413 sock->state = SS_DISCONNECTING;
422 * tipc_bind - associate or disassocate TIPC name(s) with a socket
423 * @sock: socket structure
424 * @uaddr: socket address describing name(s) and desired operation
425 * @uaddr_len: size of socket address data structure
427 * Name and name sequence binding is indicated using a positive scope value;
428 * a negative scope value unbinds the specified name. Specifying no name
429 * (i.e. a socket address length of 0) unbinds all names from the socket.
431 * Returns 0 on success, errno otherwise
433 * NOTE: This routine doesn't need to take the socket lock since it doesn't
434 * access any non-constant socket information.
436 static int tipc_bind(struct socket *sock, struct sockaddr *uaddr,
439 struct sock *sk = sock->sk;
440 struct sockaddr_tipc *addr = (struct sockaddr_tipc *)uaddr;
441 struct tipc_sock *tsk = tipc_sk(sk);
445 if (unlikely(!uaddr_len)) {
446 res = tipc_sk_withdraw(&tsk->port, 0, NULL);
450 if (uaddr_len < sizeof(struct sockaddr_tipc)) {
454 if (addr->family != AF_TIPC) {
459 if (addr->addrtype == TIPC_ADDR_NAME)
460 addr->addr.nameseq.upper = addr->addr.nameseq.lower;
461 else if (addr->addrtype != TIPC_ADDR_NAMESEQ) {
466 if ((addr->addr.nameseq.type < TIPC_RESERVED_TYPES) &&
467 (addr->addr.nameseq.type != TIPC_TOP_SRV) &&
468 (addr->addr.nameseq.type != TIPC_CFG_SRV)) {
473 res = (addr->scope > 0) ?
474 tipc_sk_publish(&tsk->port, addr->scope, &addr->addr.nameseq) :
475 tipc_sk_withdraw(&tsk->port, -addr->scope, &addr->addr.nameseq);
482 * tipc_getname - get port ID of socket or peer socket
483 * @sock: socket structure
484 * @uaddr: area for returned socket address
485 * @uaddr_len: area for returned length of socket address
486 * @peer: 0 = own ID, 1 = current peer ID, 2 = current/former peer ID
488 * Returns 0 on success, errno otherwise
490 * NOTE: This routine doesn't need to take the socket lock since it only
491 * accesses socket information that is unchanging (or which changes in
492 * a completely predictable manner).
494 static int tipc_getname(struct socket *sock, struct sockaddr *uaddr,
495 int *uaddr_len, int peer)
497 struct sockaddr_tipc *addr = (struct sockaddr_tipc *)uaddr;
498 struct tipc_sock *tsk = tipc_sk(sock->sk);
500 memset(addr, 0, sizeof(*addr));
502 if ((sock->state != SS_CONNECTED) &&
503 ((peer != 2) || (sock->state != SS_DISCONNECTING)))
505 addr->addr.id.ref = tipc_port_peerport(&tsk->port);
506 addr->addr.id.node = tipc_port_peernode(&tsk->port);
508 addr->addr.id.ref = tsk->port.ref;
509 addr->addr.id.node = tipc_own_addr;
512 *uaddr_len = sizeof(*addr);
513 addr->addrtype = TIPC_ADDR_ID;
514 addr->family = AF_TIPC;
516 addr->addr.name.domain = 0;
522 * tipc_poll - read and possibly block on pollmask
523 * @file: file structure associated with the socket
524 * @sock: socket for which to calculate the poll bits
527 * Returns pollmask value
530 * It appears that the usual socket locking mechanisms are not useful here
531 * since the pollmask info is potentially out-of-date the moment this routine
532 * exits. TCP and other protocols seem to rely on higher level poll routines
533 * to handle any preventable race conditions, so TIPC will do the same ...
535 * TIPC sets the returned events as follows:
537 * socket state flags set
538 * ------------ ---------
539 * unconnected no read flags
540 * POLLOUT if port is not congested
542 * connecting POLLIN/POLLRDNORM if ACK/NACK in rx queue
545 * connected POLLIN/POLLRDNORM if data in rx queue
546 * POLLOUT if port is not congested
548 * disconnecting POLLIN/POLLRDNORM/POLLHUP
551 * listening POLLIN if SYN in rx queue
554 * ready POLLIN/POLLRDNORM if data in rx queue
555 * [connectionless] POLLOUT (since port cannot be congested)
557 * IMPORTANT: The fact that a read or write operation is indicated does NOT
558 * imply that the operation will succeed, merely that it should be performed
559 * and will not block.
561 static unsigned int tipc_poll(struct file *file, struct socket *sock,
564 struct sock *sk = sock->sk;
565 struct tipc_sock *tsk = tipc_sk(sk);
568 sock_poll_wait(file, sk_sleep(sk), wait);
570 switch ((int)sock->state) {
577 if (!tsk->link_cong && !tipc_sk_conn_cong(tsk))
582 if (!skb_queue_empty(&sk->sk_receive_queue))
583 mask |= (POLLIN | POLLRDNORM);
585 case SS_DISCONNECTING:
586 mask = (POLLIN | POLLRDNORM | POLLHUP);
594 * tipc_sendmcast - send multicast message
595 * @sock: socket structure
596 * @seq: destination address
597 * @iov: message data to send
598 * @dsz: total length of message data
599 * @timeo: timeout to wait for wakeup
601 * Called from function tipc_sendmsg(), which has done all sanity checks
602 * Returns the number of bytes sent on success, or errno
604 static int tipc_sendmcast(struct socket *sock, struct tipc_name_seq *seq,
605 struct iovec *iov, size_t dsz, long timeo)
607 struct sock *sk = sock->sk;
608 struct tipc_msg *mhdr = &tipc_sk(sk)->port.phdr;
613 msg_set_type(mhdr, TIPC_MCAST_MSG);
614 msg_set_lookup_scope(mhdr, TIPC_CLUSTER_SCOPE);
615 msg_set_destport(mhdr, 0);
616 msg_set_destnode(mhdr, 0);
617 msg_set_nametype(mhdr, seq->type);
618 msg_set_namelower(mhdr, seq->lower);
619 msg_set_nameupper(mhdr, seq->upper);
620 msg_set_hdr_sz(mhdr, MCAST_H_SIZE);
623 mtu = tipc_bclink_get_mtu();
624 rc = tipc_msg_build(mhdr, iov, 0, dsz, mtu, &buf);
625 if (unlikely(rc < 0))
629 rc = tipc_bclink_xmit(buf);
630 if (likely(rc >= 0)) {
636 if (rc != -ELINKCONG)
638 tipc_sk(sk)->link_cong = 1;
639 rc = tipc_wait_for_sndmsg(sock, &timeo);
646 /* tipc_sk_mcast_rcv - Deliver multicast message to all destination sockets
648 void tipc_sk_mcast_rcv(struct sk_buff *buf)
650 struct tipc_msg *msg = buf_msg(buf);
651 struct tipc_port_list dports = {0, NULL, };
652 struct tipc_port_list *item;
654 uint i, last, dst = 0;
655 u32 scope = TIPC_CLUSTER_SCOPE;
657 if (in_own_node(msg_orignode(msg)))
658 scope = TIPC_NODE_SCOPE;
660 /* Create destination port list: */
661 tipc_nametbl_mc_translate(msg_nametype(msg),
672 for (item = &dports; item; item = item->next) {
673 for (i = 0; i < PLSIZE && ++dst <= last; i++) {
674 b = (dst != last) ? skb_clone(buf, GFP_ATOMIC) : buf;
676 pr_warn("Failed do clone mcast rcv buffer\n");
679 msg_set_destport(msg, item->ports[i]);
683 tipc_port_list_free(&dports);
687 * tipc_sk_proto_rcv - receive a connection mng protocol message
688 * @tsk: receiving socket
689 * @dnode: node to send response message to, if any
690 * @buf: buffer containing protocol message
691 * Returns 0 (TIPC_OK) if message was consumed, 1 (TIPC_FWD_MSG) if
692 * (CONN_PROBE_REPLY) message should be forwarded.
694 static int tipc_sk_proto_rcv(struct tipc_sock *tsk, u32 *dnode,
697 struct tipc_msg *msg = buf_msg(buf);
698 struct tipc_port *port = &tsk->port;
701 /* Ignore if connection cannot be validated: */
702 if (!tipc_sk_peer_msg(tsk, msg))
705 port->probing_state = TIPC_CONN_OK;
707 if (msg_type(msg) == CONN_ACK) {
708 conn_cong = tipc_sk_conn_cong(tsk);
709 tsk->sent_unacked -= msg_msgcnt(msg);
711 tsk->sk.sk_write_space(&tsk->sk);
712 } else if (msg_type(msg) == CONN_PROBE) {
713 if (!tipc_msg_reverse(buf, dnode, TIPC_OK))
715 msg_set_type(msg, CONN_PROBE_REPLY);
718 /* Do nothing if msg_type() == CONN_PROBE_REPLY */
725 * dest_name_check - verify user is permitted to send to specified port name
726 * @dest: destination address
727 * @m: descriptor for message to be sent
729 * Prevents restricted configuration commands from being issued by
730 * unauthorized users.
732 * Returns 0 if permission is granted, otherwise errno
734 static int dest_name_check(struct sockaddr_tipc *dest, struct msghdr *m)
736 struct tipc_cfg_msg_hdr hdr;
738 if (unlikely(dest->addrtype == TIPC_ADDR_ID))
740 if (likely(dest->addr.name.name.type >= TIPC_RESERVED_TYPES))
742 if (likely(dest->addr.name.name.type == TIPC_TOP_SRV))
744 if (likely(dest->addr.name.name.type != TIPC_CFG_SRV))
747 if (!m->msg_iovlen || (m->msg_iov[0].iov_len < sizeof(hdr)))
749 if (copy_from_user(&hdr, m->msg_iov[0].iov_base, sizeof(hdr)))
751 if ((ntohs(hdr.tcm_type) & 0xC000) && (!capable(CAP_NET_ADMIN)))
757 static int tipc_wait_for_sndmsg(struct socket *sock, long *timeo_p)
759 struct sock *sk = sock->sk;
760 struct tipc_sock *tsk = tipc_sk(sk);
765 int err = sock_error(sk);
768 if (sock->state == SS_DISCONNECTING)
772 if (signal_pending(current))
773 return sock_intr_errno(*timeo_p);
775 prepare_to_wait(sk_sleep(sk), &wait, TASK_INTERRUPTIBLE);
776 done = sk_wait_event(sk, timeo_p, !tsk->link_cong);
777 finish_wait(sk_sleep(sk), &wait);
783 * tipc_sendmsg - send message in connectionless manner
784 * @iocb: if NULL, indicates that socket lock is already held
785 * @sock: socket structure
786 * @m: message to send
787 * @dsz: amount of user data to be sent
789 * Message must have an destination specified explicitly.
790 * Used for SOCK_RDM and SOCK_DGRAM messages,
791 * and for 'SYN' messages on SOCK_SEQPACKET and SOCK_STREAM connections.
792 * (Note: 'SYN+' is prohibited on SOCK_STREAM.)
794 * Returns the number of bytes sent on success, or errno otherwise
796 static int tipc_sendmsg(struct kiocb *iocb, struct socket *sock,
797 struct msghdr *m, size_t dsz)
799 DECLARE_SOCKADDR(struct sockaddr_tipc *, dest, m->msg_name);
800 struct sock *sk = sock->sk;
801 struct tipc_sock *tsk = tipc_sk(sk);
802 struct tipc_port *port = &tsk->port;
803 struct tipc_msg *mhdr = &port->phdr;
804 struct iovec *iov = m->msg_iov;
807 struct tipc_name_seq *seq = &dest->addr.nameseq;
813 return -EDESTADDRREQ;
815 if (unlikely((m->msg_namelen < sizeof(*dest)) ||
816 (dest->family != AF_TIPC)))
819 if (dsz > TIPC_MAX_USER_MSG_SIZE)
825 if (unlikely(sock->state != SS_READY)) {
826 if (sock->state == SS_LISTENING) {
830 if (sock->state != SS_UNCONNECTED) {
834 if (tsk->port.published) {
838 if (dest->addrtype == TIPC_ADDR_NAME) {
839 tsk->port.conn_type = dest->addr.name.name.type;
840 tsk->port.conn_instance = dest->addr.name.name.instance;
843 rc = dest_name_check(dest, m);
847 timeo = sock_sndtimeo(sk, m->msg_flags & MSG_DONTWAIT);
849 if (dest->addrtype == TIPC_ADDR_MCAST) {
850 rc = tipc_sendmcast(sock, seq, iov, dsz, timeo);
852 } else if (dest->addrtype == TIPC_ADDR_NAME) {
853 u32 type = dest->addr.name.name.type;
854 u32 inst = dest->addr.name.name.instance;
855 u32 domain = dest->addr.name.domain;
858 msg_set_type(mhdr, TIPC_NAMED_MSG);
859 msg_set_hdr_sz(mhdr, NAMED_H_SIZE);
860 msg_set_nametype(mhdr, type);
861 msg_set_nameinst(mhdr, inst);
862 msg_set_lookup_scope(mhdr, tipc_addr_scope(domain));
863 dport = tipc_nametbl_translate(type, inst, &dnode);
864 msg_set_destnode(mhdr, dnode);
865 msg_set_destport(mhdr, dport);
866 if (unlikely(!dport && !dnode)) {
870 } else if (dest->addrtype == TIPC_ADDR_ID) {
871 dnode = dest->addr.id.node;
872 msg_set_type(mhdr, TIPC_DIRECT_MSG);
873 msg_set_lookup_scope(mhdr, 0);
874 msg_set_destnode(mhdr, dnode);
875 msg_set_destport(mhdr, dest->addr.id.ref);
876 msg_set_hdr_sz(mhdr, BASIC_H_SIZE);
880 mtu = tipc_node_get_mtu(dnode, tsk->port.ref);
881 rc = tipc_msg_build(mhdr, iov, 0, dsz, mtu, &buf);
886 TIPC_SKB_CB(buf)->wakeup_pending = tsk->link_cong;
887 rc = tipc_link_xmit(buf, dnode, tsk->port.ref);
888 if (likely(rc >= 0)) {
889 if (sock->state != SS_READY)
890 sock->state = SS_CONNECTING;
896 if (rc != -ELINKCONG)
899 rc = tipc_wait_for_sndmsg(sock, &timeo);
910 static int tipc_wait_for_sndpkt(struct socket *sock, long *timeo_p)
912 struct sock *sk = sock->sk;
913 struct tipc_sock *tsk = tipc_sk(sk);
918 int err = sock_error(sk);
921 if (sock->state == SS_DISCONNECTING)
923 else if (sock->state != SS_CONNECTED)
927 if (signal_pending(current))
928 return sock_intr_errno(*timeo_p);
930 prepare_to_wait(sk_sleep(sk), &wait, TASK_INTERRUPTIBLE);
931 done = sk_wait_event(sk, timeo_p,
933 !tipc_sk_conn_cong(tsk)) ||
934 !tsk->port.connected);
935 finish_wait(sk_sleep(sk), &wait);
941 * tipc_send_stream - send stream-oriented data
943 * @sock: socket structure
945 * @dsz: total length of data to be transmitted
947 * Used for SOCK_STREAM data.
949 * Returns the number of bytes sent on success (or partial success),
950 * or errno if no data sent
952 static int tipc_send_stream(struct kiocb *iocb, struct socket *sock,
953 struct msghdr *m, size_t dsz)
955 struct sock *sk = sock->sk;
956 struct tipc_sock *tsk = tipc_sk(sk);
957 struct tipc_port *port = &tsk->port;
958 struct tipc_msg *mhdr = &port->phdr;
960 DECLARE_SOCKADDR(struct sockaddr_tipc *, dest, m->msg_name);
965 uint mtu, send, sent = 0;
967 /* Handle implied connection establishment */
968 if (unlikely(dest)) {
969 rc = tipc_sendmsg(iocb, sock, m, dsz);
970 if (dsz && (dsz == rc))
971 tsk->sent_unacked = 1;
974 if (dsz > (uint)INT_MAX)
980 if (unlikely(sock->state != SS_CONNECTED)) {
981 if (sock->state == SS_DISCONNECTING)
988 timeo = sock_sndtimeo(sk, m->msg_flags & MSG_DONTWAIT);
989 dnode = tipc_port_peernode(port);
993 send = min_t(uint, dsz - sent, TIPC_MAX_USER_MSG_SIZE);
994 rc = tipc_msg_build(mhdr, m->msg_iov, sent, send, mtu, &buf);
995 if (unlikely(rc < 0))
998 if (likely(!tipc_sk_conn_cong(tsk))) {
999 rc = tipc_link_xmit(buf, dnode, ref);
1001 tsk->sent_unacked++;
1007 if (rc == -EMSGSIZE) {
1008 port->max_pkt = tipc_node_get_mtu(dnode, ref);
1011 if (rc != -ELINKCONG)
1015 rc = tipc_wait_for_sndpkt(sock, &timeo);
1017 kfree_skb_list(buf);
1022 return sent ? sent : rc;
1026 * tipc_send_packet - send a connection-oriented message
1027 * @iocb: if NULL, indicates that socket lock is already held
1028 * @sock: socket structure
1029 * @m: message to send
1030 * @dsz: length of data to be transmitted
1032 * Used for SOCK_SEQPACKET messages.
1034 * Returns the number of bytes sent on success, or errno otherwise
1036 static int tipc_send_packet(struct kiocb *iocb, struct socket *sock,
1037 struct msghdr *m, size_t dsz)
1039 if (dsz > TIPC_MAX_USER_MSG_SIZE)
1042 return tipc_send_stream(iocb, sock, m, dsz);
1045 /* tipc_sk_finish_conn - complete the setup of a connection
1047 static void tipc_sk_finish_conn(struct tipc_port *port, u32 peer_port,
1050 struct tipc_msg *msg = &port->phdr;
1052 msg_set_destnode(msg, peer_node);
1053 msg_set_destport(msg, peer_port);
1054 msg_set_type(msg, TIPC_CONN_MSG);
1055 msg_set_lookup_scope(msg, 0);
1056 msg_set_hdr_sz(msg, SHORT_H_SIZE);
1058 port->probing_interval = CONN_PROBING_INTERVAL;
1059 port->probing_state = TIPC_CONN_OK;
1060 port->connected = 1;
1061 k_start_timer(&port->timer, port->probing_interval);
1062 tipc_node_add_conn(peer_node, port->ref, peer_port);
1063 port->max_pkt = tipc_node_get_mtu(peer_node, port->ref);
1067 * set_orig_addr - capture sender's address for received message
1068 * @m: descriptor for message info
1069 * @msg: received message header
1071 * Note: Address is not captured if not requested by receiver.
1073 static void set_orig_addr(struct msghdr *m, struct tipc_msg *msg)
1075 DECLARE_SOCKADDR(struct sockaddr_tipc *, addr, m->msg_name);
1078 addr->family = AF_TIPC;
1079 addr->addrtype = TIPC_ADDR_ID;
1080 memset(&addr->addr, 0, sizeof(addr->addr));
1081 addr->addr.id.ref = msg_origport(msg);
1082 addr->addr.id.node = msg_orignode(msg);
1083 addr->addr.name.domain = 0; /* could leave uninitialized */
1084 addr->scope = 0; /* could leave uninitialized */
1085 m->msg_namelen = sizeof(struct sockaddr_tipc);
1090 * anc_data_recv - optionally capture ancillary data for received message
1091 * @m: descriptor for message info
1092 * @msg: received message header
1093 * @tport: TIPC port associated with message
1095 * Note: Ancillary data is not captured if not requested by receiver.
1097 * Returns 0 if successful, otherwise errno
1099 static int anc_data_recv(struct msghdr *m, struct tipc_msg *msg,
1100 struct tipc_port *tport)
1108 if (likely(m->msg_controllen == 0))
1111 /* Optionally capture errored message object(s) */
1112 err = msg ? msg_errcode(msg) : 0;
1113 if (unlikely(err)) {
1115 anc_data[1] = msg_data_sz(msg);
1116 res = put_cmsg(m, SOL_TIPC, TIPC_ERRINFO, 8, anc_data);
1120 res = put_cmsg(m, SOL_TIPC, TIPC_RETDATA, anc_data[1],
1127 /* Optionally capture message destination object */
1128 dest_type = msg ? msg_type(msg) : TIPC_DIRECT_MSG;
1129 switch (dest_type) {
1130 case TIPC_NAMED_MSG:
1132 anc_data[0] = msg_nametype(msg);
1133 anc_data[1] = msg_namelower(msg);
1134 anc_data[2] = msg_namelower(msg);
1136 case TIPC_MCAST_MSG:
1138 anc_data[0] = msg_nametype(msg);
1139 anc_data[1] = msg_namelower(msg);
1140 anc_data[2] = msg_nameupper(msg);
1143 has_name = (tport->conn_type != 0);
1144 anc_data[0] = tport->conn_type;
1145 anc_data[1] = tport->conn_instance;
1146 anc_data[2] = tport->conn_instance;
1152 res = put_cmsg(m, SOL_TIPC, TIPC_DESTNAME, 12, anc_data);
1160 static void tipc_sk_send_ack(struct tipc_port *port, uint ack)
1162 struct sk_buff *buf = NULL;
1163 struct tipc_msg *msg;
1164 u32 peer_port = tipc_port_peerport(port);
1165 u32 dnode = tipc_port_peernode(port);
1167 if (!port->connected)
1169 buf = tipc_msg_create(CONN_MANAGER, CONN_ACK, INT_H_SIZE, 0, dnode,
1170 tipc_own_addr, peer_port, port->ref, TIPC_OK);
1174 msg_set_msgcnt(msg, ack);
1175 tipc_link_xmit(buf, dnode, msg_link_selector(msg));
1178 static int tipc_wait_for_rcvmsg(struct socket *sock, long *timeop)
1180 struct sock *sk = sock->sk;
1182 long timeo = *timeop;
1186 prepare_to_wait(sk_sleep(sk), &wait, TASK_INTERRUPTIBLE);
1187 if (timeo && skb_queue_empty(&sk->sk_receive_queue)) {
1188 if (sock->state == SS_DISCONNECTING) {
1193 timeo = schedule_timeout(timeo);
1197 if (!skb_queue_empty(&sk->sk_receive_queue))
1199 err = sock_intr_errno(timeo);
1200 if (signal_pending(current))
1206 finish_wait(sk_sleep(sk), &wait);
1212 * tipc_recvmsg - receive packet-oriented message
1214 * @m: descriptor for message info
1215 * @buf_len: total size of user buffer area
1216 * @flags: receive flags
1218 * Used for SOCK_DGRAM, SOCK_RDM, and SOCK_SEQPACKET messages.
1219 * If the complete message doesn't fit in user area, truncate it.
1221 * Returns size of returned message data, errno otherwise
1223 static int tipc_recvmsg(struct kiocb *iocb, struct socket *sock,
1224 struct msghdr *m, size_t buf_len, int flags)
1226 struct sock *sk = sock->sk;
1227 struct tipc_sock *tsk = tipc_sk(sk);
1228 struct tipc_port *port = &tsk->port;
1229 struct sk_buff *buf;
1230 struct tipc_msg *msg;
1236 /* Catch invalid receive requests */
1237 if (unlikely(!buf_len))
1242 if (unlikely(sock->state == SS_UNCONNECTED)) {
1247 timeo = sock_rcvtimeo(sk, flags & MSG_DONTWAIT);
1250 /* Look for a message in receive queue; wait if necessary */
1251 res = tipc_wait_for_rcvmsg(sock, &timeo);
1255 /* Look at first message in receive queue */
1256 buf = skb_peek(&sk->sk_receive_queue);
1258 sz = msg_data_sz(msg);
1259 err = msg_errcode(msg);
1261 /* Discard an empty non-errored message & try again */
1262 if ((!sz) && (!err)) {
1263 advance_rx_queue(sk);
1267 /* Capture sender's address (optional) */
1268 set_orig_addr(m, msg);
1270 /* Capture ancillary data (optional) */
1271 res = anc_data_recv(m, msg, port);
1275 /* Capture message data (if valid) & compute return value (always) */
1277 if (unlikely(buf_len < sz)) {
1279 m->msg_flags |= MSG_TRUNC;
1281 res = skb_copy_datagram_iovec(buf, msg_hdr_sz(msg),
1287 if ((sock->state == SS_READY) ||
1288 ((err == TIPC_CONN_SHUTDOWN) || m->msg_control))
1294 /* Consume received message (optional) */
1295 if (likely(!(flags & MSG_PEEK))) {
1296 if ((sock->state != SS_READY) &&
1297 (++tsk->rcv_unacked >= TIPC_CONNACK_INTV)) {
1298 tipc_sk_send_ack(port, tsk->rcv_unacked);
1299 tsk->rcv_unacked = 0;
1301 advance_rx_queue(sk);
1309 * tipc_recv_stream - receive stream-oriented data
1311 * @m: descriptor for message info
1312 * @buf_len: total size of user buffer area
1313 * @flags: receive flags
1315 * Used for SOCK_STREAM messages only. If not enough data is available
1316 * will optionally wait for more; never truncates data.
1318 * Returns size of returned message data, errno otherwise
1320 static int tipc_recv_stream(struct kiocb *iocb, struct socket *sock,
1321 struct msghdr *m, size_t buf_len, int flags)
1323 struct sock *sk = sock->sk;
1324 struct tipc_sock *tsk = tipc_sk(sk);
1325 struct tipc_port *port = &tsk->port;
1326 struct sk_buff *buf;
1327 struct tipc_msg *msg;
1330 int sz_to_copy, target, needed;
1335 /* Catch invalid receive attempts */
1336 if (unlikely(!buf_len))
1341 if (unlikely(sock->state == SS_UNCONNECTED)) {
1346 target = sock_rcvlowat(sk, flags & MSG_WAITALL, buf_len);
1347 timeo = sock_rcvtimeo(sk, flags & MSG_DONTWAIT);
1350 /* Look for a message in receive queue; wait if necessary */
1351 res = tipc_wait_for_rcvmsg(sock, &timeo);
1355 /* Look at first message in receive queue */
1356 buf = skb_peek(&sk->sk_receive_queue);
1358 sz = msg_data_sz(msg);
1359 err = msg_errcode(msg);
1361 /* Discard an empty non-errored message & try again */
1362 if ((!sz) && (!err)) {
1363 advance_rx_queue(sk);
1367 /* Optionally capture sender's address & ancillary data of first msg */
1368 if (sz_copied == 0) {
1369 set_orig_addr(m, msg);
1370 res = anc_data_recv(m, msg, port);
1375 /* Capture message data (if valid) & compute return value (always) */
1377 u32 offset = (u32)(unsigned long)(TIPC_SKB_CB(buf)->handle);
1380 needed = (buf_len - sz_copied);
1381 sz_to_copy = (sz <= needed) ? sz : needed;
1383 res = skb_copy_datagram_iovec(buf, msg_hdr_sz(msg) + offset,
1384 m->msg_iov, sz_to_copy);
1388 sz_copied += sz_to_copy;
1390 if (sz_to_copy < sz) {
1391 if (!(flags & MSG_PEEK))
1392 TIPC_SKB_CB(buf)->handle =
1393 (void *)(unsigned long)(offset + sz_to_copy);
1398 goto exit; /* can't add error msg to valid data */
1400 if ((err == TIPC_CONN_SHUTDOWN) || m->msg_control)
1406 /* Consume received message (optional) */
1407 if (likely(!(flags & MSG_PEEK))) {
1408 if (unlikely(++tsk->rcv_unacked >= TIPC_CONNACK_INTV)) {
1409 tipc_sk_send_ack(port, tsk->rcv_unacked);
1410 tsk->rcv_unacked = 0;
1412 advance_rx_queue(sk);
1415 /* Loop around if more data is required */
1416 if ((sz_copied < buf_len) && /* didn't get all requested data */
1417 (!skb_queue_empty(&sk->sk_receive_queue) ||
1418 (sz_copied < target)) && /* and more is ready or required */
1419 (!(flags & MSG_PEEK)) && /* and aren't just peeking at data */
1420 (!err)) /* and haven't reached a FIN */
1425 return sz_copied ? sz_copied : res;
1429 * tipc_write_space - wake up thread if port congestion is released
1432 static void tipc_write_space(struct sock *sk)
1434 struct socket_wq *wq;
1437 wq = rcu_dereference(sk->sk_wq);
1438 if (wq_has_sleeper(wq))
1439 wake_up_interruptible_sync_poll(&wq->wait, POLLOUT |
1440 POLLWRNORM | POLLWRBAND);
1445 * tipc_data_ready - wake up threads to indicate messages have been received
1447 * @len: the length of messages
1449 static void tipc_data_ready(struct sock *sk)
1451 struct socket_wq *wq;
1454 wq = rcu_dereference(sk->sk_wq);
1455 if (wq_has_sleeper(wq))
1456 wake_up_interruptible_sync_poll(&wq->wait, POLLIN |
1457 POLLRDNORM | POLLRDBAND);
1462 * filter_connect - Handle all incoming messages for a connection-based socket
1466 * Returns 0 (TIPC_OK) if everyting ok, -TIPC_ERR_NO_PORT otherwise
1468 static int filter_connect(struct tipc_sock *tsk, struct sk_buff **buf)
1470 struct sock *sk = &tsk->sk;
1471 struct tipc_port *port = &tsk->port;
1472 struct socket *sock = sk->sk_socket;
1473 struct tipc_msg *msg = buf_msg(*buf);
1475 int retval = -TIPC_ERR_NO_PORT;
1480 switch ((int)sock->state) {
1482 /* Accept only connection-based messages sent by peer */
1483 if (tipc_sk_peer_msg(tsk, msg)) {
1484 if (unlikely(msg_errcode(msg))) {
1485 sock->state = SS_DISCONNECTING;
1486 port->connected = 0;
1487 /* let timer expire on it's own */
1488 tipc_node_remove_conn(tipc_port_peernode(port),
1495 /* Accept only ACK or NACK message */
1497 if (unlikely(!msg_connected(msg)))
1500 if (unlikely(msg_errcode(msg))) {
1501 sock->state = SS_DISCONNECTING;
1502 sk->sk_err = ECONNREFUSED;
1507 if (unlikely(msg_importance(msg) > TIPC_CRITICAL_IMPORTANCE)) {
1508 sock->state = SS_DISCONNECTING;
1509 sk->sk_err = EINVAL;
1514 tipc_sk_finish_conn(port, msg_origport(msg), msg_orignode(msg));
1515 msg_set_importance(&port->phdr, msg_importance(msg));
1516 sock->state = SS_CONNECTED;
1518 /* If an incoming message is an 'ACK-', it should be
1519 * discarded here because it doesn't contain useful
1520 * data. In addition, we should try to wake up
1521 * connect() routine if sleeping.
1523 if (msg_data_sz(msg) == 0) {
1526 if (waitqueue_active(sk_sleep(sk)))
1527 wake_up_interruptible(sk_sleep(sk));
1532 case SS_UNCONNECTED:
1533 /* Accept only SYN message */
1534 if (!msg_connected(msg) && !(msg_errcode(msg)))
1537 case SS_DISCONNECTING:
1540 pr_err("Unknown socket state %u\n", sock->state);
1546 * rcvbuf_limit - get proper overload limit of socket receive queue
1550 * For all connection oriented messages, irrespective of importance,
1551 * the default overload value (i.e. 67MB) is set as limit.
1553 * For all connectionless messages, by default new queue limits are
1556 * TIPC_LOW_IMPORTANCE (4 MB)
1557 * TIPC_MEDIUM_IMPORTANCE (8 MB)
1558 * TIPC_HIGH_IMPORTANCE (16 MB)
1559 * TIPC_CRITICAL_IMPORTANCE (32 MB)
1561 * Returns overload limit according to corresponding message importance
1563 static unsigned int rcvbuf_limit(struct sock *sk, struct sk_buff *buf)
1565 struct tipc_msg *msg = buf_msg(buf);
1567 if (msg_connected(msg))
1568 return sysctl_tipc_rmem[2];
1570 return sk->sk_rcvbuf >> TIPC_CRITICAL_IMPORTANCE <<
1571 msg_importance(msg);
1575 * filter_rcv - validate incoming message
1579 * Enqueues message on receive queue if acceptable; optionally handles
1580 * disconnect indication for a connected socket.
1582 * Called with socket lock already taken; port lock may also be taken.
1584 * Returns 0 (TIPC_OK) if message was consumed, -TIPC error code if message
1585 * to be rejected, 1 (TIPC_FWD_MSG) if (CONN_MANAGER) message to be forwarded
1587 static int filter_rcv(struct sock *sk, struct sk_buff *buf)
1589 struct socket *sock = sk->sk_socket;
1590 struct tipc_sock *tsk = tipc_sk(sk);
1591 struct tipc_msg *msg = buf_msg(buf);
1592 unsigned int limit = rcvbuf_limit(sk, buf);
1596 if (unlikely(msg_user(msg) == CONN_MANAGER))
1597 return tipc_sk_proto_rcv(tsk, &onode, buf);
1599 if (unlikely(msg_user(msg) == SOCK_WAKEUP)) {
1602 sk->sk_write_space(sk);
1606 /* Reject message if it is wrong sort of message for socket */
1607 if (msg_type(msg) > TIPC_DIRECT_MSG)
1608 return -TIPC_ERR_NO_PORT;
1610 if (sock->state == SS_READY) {
1611 if (msg_connected(msg))
1612 return -TIPC_ERR_NO_PORT;
1614 rc = filter_connect(tsk, &buf);
1615 if (rc != TIPC_OK || buf == NULL)
1619 /* Reject message if there isn't room to queue it */
1620 if (sk_rmem_alloc_get(sk) + buf->truesize >= limit)
1621 return -TIPC_ERR_OVERLOAD;
1623 /* Enqueue message */
1624 TIPC_SKB_CB(buf)->handle = NULL;
1625 __skb_queue_tail(&sk->sk_receive_queue, buf);
1626 skb_set_owner_r(buf, sk);
1628 sk->sk_data_ready(sk);
1633 * tipc_backlog_rcv - handle incoming message from backlog queue
1637 * Caller must hold socket lock, but not port lock.
1641 static int tipc_backlog_rcv(struct sock *sk, struct sk_buff *buf)
1645 struct tipc_sock *tsk = tipc_sk(sk);
1646 uint truesize = buf->truesize;
1648 rc = filter_rcv(sk, buf);
1651 if (atomic_read(&tsk->dupl_rcvcnt) < TIPC_CONN_OVERLOAD_LIMIT)
1652 atomic_add(truesize, &tsk->dupl_rcvcnt);
1656 if ((rc < 0) && !tipc_msg_reverse(buf, &onode, -rc))
1659 tipc_link_xmit(buf, onode, 0);
1665 * tipc_sk_rcv - handle incoming message
1666 * @buf: buffer containing arriving message
1668 * Returns 0 if success, or errno: -EHOSTUNREACH
1670 int tipc_sk_rcv(struct sk_buff *buf)
1672 struct tipc_sock *tsk;
1673 struct tipc_port *port;
1675 u32 dport = msg_destport(buf_msg(buf));
1680 /* Validate destination and message */
1681 tsk = tipc_sk_get(dport);
1682 if (unlikely(!tsk)) {
1683 rc = tipc_msg_eval(buf, &dnode);
1692 if (!sock_owned_by_user(sk)) {
1693 rc = filter_rcv(sk, buf);
1695 if (sk->sk_backlog.len == 0)
1696 atomic_set(&tsk->dupl_rcvcnt, 0);
1697 limit = rcvbuf_limit(sk, buf) + atomic_read(&tsk->dupl_rcvcnt);
1698 if (sk_add_backlog(sk, buf, limit))
1699 rc = -TIPC_ERR_OVERLOAD;
1706 if ((rc < 0) && !tipc_msg_reverse(buf, &dnode, -rc))
1707 return -EHOSTUNREACH;
1709 tipc_link_xmit(buf, dnode, 0);
1710 return (rc < 0) ? -EHOSTUNREACH : 0;
1713 static int tipc_wait_for_connect(struct socket *sock, long *timeo_p)
1715 struct sock *sk = sock->sk;
1720 int err = sock_error(sk);
1725 if (signal_pending(current))
1726 return sock_intr_errno(*timeo_p);
1728 prepare_to_wait(sk_sleep(sk), &wait, TASK_INTERRUPTIBLE);
1729 done = sk_wait_event(sk, timeo_p, sock->state != SS_CONNECTING);
1730 finish_wait(sk_sleep(sk), &wait);
1736 * tipc_connect - establish a connection to another TIPC port
1737 * @sock: socket structure
1738 * @dest: socket address for destination port
1739 * @destlen: size of socket address data structure
1740 * @flags: file-related flags associated with socket
1742 * Returns 0 on success, errno otherwise
1744 static int tipc_connect(struct socket *sock, struct sockaddr *dest,
1745 int destlen, int flags)
1747 struct sock *sk = sock->sk;
1748 struct sockaddr_tipc *dst = (struct sockaddr_tipc *)dest;
1749 struct msghdr m = {NULL,};
1750 long timeout = (flags & O_NONBLOCK) ? 0 : tipc_sk(sk)->conn_timeout;
1751 socket_state previous;
1756 /* For now, TIPC does not allow use of connect() with DGRAM/RDM types */
1757 if (sock->state == SS_READY) {
1763 * Reject connection attempt using multicast address
1765 * Note: send_msg() validates the rest of the address fields,
1766 * so there's no need to do it here
1768 if (dst->addrtype == TIPC_ADDR_MCAST) {
1773 previous = sock->state;
1774 switch (sock->state) {
1775 case SS_UNCONNECTED:
1776 /* Send a 'SYN-' to destination */
1778 m.msg_namelen = destlen;
1780 /* If connect is in non-blocking case, set MSG_DONTWAIT to
1781 * indicate send_msg() is never blocked.
1784 m.msg_flags = MSG_DONTWAIT;
1786 res = tipc_sendmsg(NULL, sock, &m, 0);
1787 if ((res < 0) && (res != -EWOULDBLOCK))
1790 /* Just entered SS_CONNECTING state; the only
1791 * difference is that return value in non-blocking
1792 * case is EINPROGRESS, rather than EALREADY.
1796 if (previous == SS_CONNECTING)
1800 timeout = msecs_to_jiffies(timeout);
1801 /* Wait until an 'ACK' or 'RST' arrives, or a timeout occurs */
1802 res = tipc_wait_for_connect(sock, &timeout);
1817 * tipc_listen - allow socket to listen for incoming connections
1818 * @sock: socket structure
1821 * Returns 0 on success, errno otherwise
1823 static int tipc_listen(struct socket *sock, int len)
1825 struct sock *sk = sock->sk;
1830 if (sock->state != SS_UNCONNECTED)
1833 sock->state = SS_LISTENING;
1841 static int tipc_wait_for_accept(struct socket *sock, long timeo)
1843 struct sock *sk = sock->sk;
1847 /* True wake-one mechanism for incoming connections: only
1848 * one process gets woken up, not the 'whole herd'.
1849 * Since we do not 'race & poll' for established sockets
1850 * anymore, the common case will execute the loop only once.
1853 prepare_to_wait_exclusive(sk_sleep(sk), &wait,
1854 TASK_INTERRUPTIBLE);
1855 if (timeo && skb_queue_empty(&sk->sk_receive_queue)) {
1857 timeo = schedule_timeout(timeo);
1861 if (!skb_queue_empty(&sk->sk_receive_queue))
1864 if (sock->state != SS_LISTENING)
1866 err = sock_intr_errno(timeo);
1867 if (signal_pending(current))
1873 finish_wait(sk_sleep(sk), &wait);
1878 * tipc_accept - wait for connection request
1879 * @sock: listening socket
1880 * @newsock: new socket that is to be connected
1881 * @flags: file-related flags associated with socket
1883 * Returns 0 on success, errno otherwise
1885 static int tipc_accept(struct socket *sock, struct socket *new_sock, int flags)
1887 struct sock *new_sk, *sk = sock->sk;
1888 struct sk_buff *buf;
1889 struct tipc_port *new_port;
1890 struct tipc_msg *msg;
1896 if (sock->state != SS_LISTENING) {
1900 timeo = sock_rcvtimeo(sk, flags & O_NONBLOCK);
1901 res = tipc_wait_for_accept(sock, timeo);
1905 buf = skb_peek(&sk->sk_receive_queue);
1907 res = tipc_sk_create(sock_net(sock->sk), new_sock, 0, 1);
1911 new_sk = new_sock->sk;
1912 new_port = &tipc_sk(new_sk)->port;
1915 /* we lock on new_sk; but lockdep sees the lock on sk */
1916 lock_sock_nested(new_sk, SINGLE_DEPTH_NESTING);
1919 * Reject any stray messages received by new socket
1920 * before the socket lock was taken (very, very unlikely)
1922 reject_rx_queue(new_sk);
1924 /* Connect new socket to it's peer */
1925 tipc_sk_finish_conn(new_port, msg_origport(msg), msg_orignode(msg));
1926 new_sock->state = SS_CONNECTED;
1928 tipc_port_set_importance(new_port, msg_importance(msg));
1929 if (msg_named(msg)) {
1930 new_port->conn_type = msg_nametype(msg);
1931 new_port->conn_instance = msg_nameinst(msg);
1935 * Respond to 'SYN-' by discarding it & returning 'ACK'-.
1936 * Respond to 'SYN+' by queuing it on new socket.
1938 if (!msg_data_sz(msg)) {
1939 struct msghdr m = {NULL,};
1941 advance_rx_queue(sk);
1942 tipc_send_packet(NULL, new_sock, &m, 0);
1944 __skb_dequeue(&sk->sk_receive_queue);
1945 __skb_queue_head(&new_sk->sk_receive_queue, buf);
1946 skb_set_owner_r(buf, new_sk);
1948 release_sock(new_sk);
1955 * tipc_shutdown - shutdown socket connection
1956 * @sock: socket structure
1957 * @how: direction to close (must be SHUT_RDWR)
1959 * Terminates connection (if necessary), then purges socket's receive queue.
1961 * Returns 0 on success, errno otherwise
1963 static int tipc_shutdown(struct socket *sock, int how)
1965 struct sock *sk = sock->sk;
1966 struct tipc_sock *tsk = tipc_sk(sk);
1967 struct tipc_port *port = &tsk->port;
1968 struct sk_buff *buf;
1972 if (how != SHUT_RDWR)
1977 switch (sock->state) {
1982 /* Disconnect and send a 'FIN+' or 'FIN-' message to peer */
1983 buf = __skb_dequeue(&sk->sk_receive_queue);
1985 if (TIPC_SKB_CB(buf)->handle != NULL) {
1989 if (tipc_msg_reverse(buf, &dnode, TIPC_CONN_SHUTDOWN))
1990 tipc_link_xmit(buf, dnode, port->ref);
1991 tipc_node_remove_conn(dnode, port->ref);
1993 dnode = tipc_port_peernode(port);
1994 buf = tipc_msg_create(TIPC_CRITICAL_IMPORTANCE,
1995 TIPC_CONN_MSG, SHORT_H_SIZE,
1996 0, dnode, tipc_own_addr,
1997 tipc_port_peerport(port),
1998 port->ref, TIPC_CONN_SHUTDOWN);
1999 tipc_link_xmit(buf, dnode, port->ref);
2001 port->connected = 0;
2002 sock->state = SS_DISCONNECTING;
2003 tipc_node_remove_conn(dnode, port->ref);
2006 case SS_DISCONNECTING:
2008 /* Discard any unreceived messages */
2009 __skb_queue_purge(&sk->sk_receive_queue);
2011 /* Wake up anyone sleeping in poll */
2012 sk->sk_state_change(sk);
2024 static void tipc_sk_timeout(unsigned long ref)
2026 struct tipc_sock *tsk;
2027 struct tipc_port *port;
2029 struct sk_buff *buf = NULL;
2030 u32 peer_port, peer_node;
2032 tsk = tipc_sk_get(ref);
2039 if (!port->connected) {
2043 peer_port = tipc_port_peerport(port);
2044 peer_node = tipc_port_peernode(port);
2046 if (port->probing_state == TIPC_CONN_PROBING) {
2047 /* Previous probe not answered -> self abort */
2048 buf = tipc_msg_create(TIPC_CRITICAL_IMPORTANCE, TIPC_CONN_MSG,
2049 SHORT_H_SIZE, 0, tipc_own_addr,
2050 peer_node, ref, peer_port,
2053 buf = tipc_msg_create(CONN_MANAGER, CONN_PROBE, INT_H_SIZE,
2054 0, peer_node, tipc_own_addr,
2055 peer_port, ref, TIPC_OK);
2056 port->probing_state = TIPC_CONN_PROBING;
2057 k_start_timer(&port->timer, port->probing_interval);
2061 tipc_link_xmit(buf, peer_node, ref);
2066 static int tipc_sk_publish(struct tipc_port *port, uint scope,
2067 struct tipc_name_seq const *seq)
2069 struct publication *publ;
2072 if (port->connected)
2074 key = port->ref + port->pub_count + 1;
2075 if (key == port->ref)
2078 publ = tipc_nametbl_publish(seq->type, seq->lower, seq->upper,
2079 scope, port->ref, key);
2080 if (unlikely(!publ))
2083 list_add(&publ->pport_list, &port->publications);
2085 port->published = 1;
2089 static int tipc_sk_withdraw(struct tipc_port *port, uint scope,
2090 struct tipc_name_seq const *seq)
2092 struct publication *publ;
2093 struct publication *safe;
2096 list_for_each_entry_safe(publ, safe, &port->publications, pport_list) {
2098 if (publ->scope != scope)
2100 if (publ->type != seq->type)
2102 if (publ->lower != seq->lower)
2104 if (publ->upper != seq->upper)
2106 tipc_nametbl_withdraw(publ->type, publ->lower,
2107 publ->ref, publ->key);
2111 tipc_nametbl_withdraw(publ->type, publ->lower,
2112 publ->ref, publ->key);
2115 if (list_empty(&port->publications))
2116 port->published = 0;
2120 static int tipc_sk_show(struct tipc_port *port, char *buf,
2121 int len, int full_id)
2123 struct publication *publ;
2127 ret = tipc_snprintf(buf, len, "<%u.%u.%u:%u>:",
2128 tipc_zone(tipc_own_addr),
2129 tipc_cluster(tipc_own_addr),
2130 tipc_node(tipc_own_addr), port->ref);
2132 ret = tipc_snprintf(buf, len, "%-10u:", port->ref);
2134 if (port->connected) {
2135 u32 dport = tipc_port_peerport(port);
2136 u32 destnode = tipc_port_peernode(port);
2138 ret += tipc_snprintf(buf + ret, len - ret,
2139 " connected to <%u.%u.%u:%u>",
2140 tipc_zone(destnode),
2141 tipc_cluster(destnode),
2142 tipc_node(destnode), dport);
2143 if (port->conn_type != 0)
2144 ret += tipc_snprintf(buf + ret, len - ret,
2145 " via {%u,%u}", port->conn_type,
2146 port->conn_instance);
2147 } else if (port->published) {
2148 ret += tipc_snprintf(buf + ret, len - ret, " bound to");
2149 list_for_each_entry(publ, &port->publications, pport_list) {
2150 if (publ->lower == publ->upper)
2151 ret += tipc_snprintf(buf + ret, len - ret,
2152 " {%u,%u}", publ->type,
2155 ret += tipc_snprintf(buf + ret, len - ret,
2156 " {%u,%u,%u}", publ->type,
2157 publ->lower, publ->upper);
2160 ret += tipc_snprintf(buf + ret, len - ret, "\n");
2164 struct sk_buff *tipc_sk_socks_show(void)
2166 struct sk_buff *buf;
2167 struct tlv_desc *rep_tlv;
2170 struct tipc_sock *tsk;
2174 buf = tipc_cfg_reply_alloc(TLV_SPACE(ULTRA_STRING_MAX_LEN));
2177 rep_tlv = (struct tlv_desc *)buf->data;
2178 pb = TLV_DATA(rep_tlv);
2179 pb_len = ULTRA_STRING_MAX_LEN;
2181 tsk = tipc_sk_get_next(&ref);
2182 for (; tsk; tsk = tipc_sk_get_next(&ref)) {
2183 lock_sock(&tsk->sk);
2184 str_len += tipc_sk_show(&tsk->port, pb + str_len,
2185 pb_len - str_len, 0);
2186 release_sock(&tsk->sk);
2189 str_len += 1; /* for "\0" */
2190 skb_put(buf, TLV_SPACE(str_len));
2191 TLV_SET(rep_tlv, TIPC_TLV_ULTRA_STRING, NULL, str_len);
2196 /* tipc_sk_reinit: set non-zero address in all existing sockets
2197 * when we go from standalone to network mode.
2199 void tipc_sk_reinit(void)
2201 struct tipc_msg *msg;
2203 struct tipc_sock *tsk = tipc_sk_get_next(&ref);
2205 for (; tsk; tsk = tipc_sk_get_next(&ref)) {
2206 lock_sock(&tsk->sk);
2207 msg = &tsk->port.phdr;
2208 msg_set_prevnode(msg, tipc_own_addr);
2209 msg_set_orignode(msg, tipc_own_addr);
2210 release_sock(&tsk->sk);
2216 * tipc_setsockopt - set socket option
2217 * @sock: socket structure
2218 * @lvl: option level
2219 * @opt: option identifier
2220 * @ov: pointer to new option value
2221 * @ol: length of option value
2223 * For stream sockets only, accepts and ignores all IPPROTO_TCP options
2224 * (to ease compatibility).
2226 * Returns 0 on success, errno otherwise
2228 static int tipc_setsockopt(struct socket *sock, int lvl, int opt,
2229 char __user *ov, unsigned int ol)
2231 struct sock *sk = sock->sk;
2232 struct tipc_sock *tsk = tipc_sk(sk);
2233 struct tipc_port *port = &tsk->port;
2237 if ((lvl == IPPROTO_TCP) && (sock->type == SOCK_STREAM))
2239 if (lvl != SOL_TIPC)
2240 return -ENOPROTOOPT;
2241 if (ol < sizeof(value))
2243 res = get_user(value, (u32 __user *)ov);
2250 case TIPC_IMPORTANCE:
2251 res = tipc_port_set_importance(port, value);
2253 case TIPC_SRC_DROPPABLE:
2254 if (sock->type != SOCK_STREAM)
2255 tipc_port_set_unreliable(port, value);
2259 case TIPC_DEST_DROPPABLE:
2260 tipc_port_set_unreturnable(port, value);
2262 case TIPC_CONN_TIMEOUT:
2263 tipc_sk(sk)->conn_timeout = value;
2264 /* no need to set "res", since already 0 at this point */
2276 * tipc_getsockopt - get socket option
2277 * @sock: socket structure
2278 * @lvl: option level
2279 * @opt: option identifier
2280 * @ov: receptacle for option value
2281 * @ol: receptacle for length of option value
2283 * For stream sockets only, returns 0 length result for all IPPROTO_TCP options
2284 * (to ease compatibility).
2286 * Returns 0 on success, errno otherwise
2288 static int tipc_getsockopt(struct socket *sock, int lvl, int opt,
2289 char __user *ov, int __user *ol)
2291 struct sock *sk = sock->sk;
2292 struct tipc_sock *tsk = tipc_sk(sk);
2293 struct tipc_port *port = &tsk->port;
2298 if ((lvl == IPPROTO_TCP) && (sock->type == SOCK_STREAM))
2299 return put_user(0, ol);
2300 if (lvl != SOL_TIPC)
2301 return -ENOPROTOOPT;
2302 res = get_user(len, ol);
2309 case TIPC_IMPORTANCE:
2310 value = tipc_port_importance(port);
2312 case TIPC_SRC_DROPPABLE:
2313 value = tipc_port_unreliable(port);
2315 case TIPC_DEST_DROPPABLE:
2316 value = tipc_port_unreturnable(port);
2318 case TIPC_CONN_TIMEOUT:
2319 value = tipc_sk(sk)->conn_timeout;
2320 /* no need to set "res", since already 0 at this point */
2322 case TIPC_NODE_RECVQ_DEPTH:
2323 value = 0; /* was tipc_queue_size, now obsolete */
2325 case TIPC_SOCK_RECVQ_DEPTH:
2326 value = skb_queue_len(&sk->sk_receive_queue);
2335 return res; /* "get" failed */
2337 if (len < sizeof(value))
2340 if (copy_to_user(ov, &value, sizeof(value)))
2343 return put_user(sizeof(value), ol);
2346 static int tipc_ioctl(struct socket *sk, unsigned int cmd, unsigned long arg)
2348 struct tipc_sioc_ln_req lnr;
2349 void __user *argp = (void __user *)arg;
2352 case SIOCGETLINKNAME:
2353 if (copy_from_user(&lnr, argp, sizeof(lnr)))
2355 if (!tipc_node_get_linkname(lnr.bearer_id, lnr.peer,
2356 lnr.linkname, TIPC_MAX_LINK_NAME)) {
2357 if (copy_to_user(argp, &lnr, sizeof(lnr)))
2361 return -EADDRNOTAVAIL;
2363 return -ENOIOCTLCMD;
2367 /* Protocol switches for the various types of TIPC sockets */
2369 static const struct proto_ops msg_ops = {
2370 .owner = THIS_MODULE,
2372 .release = tipc_release,
2374 .connect = tipc_connect,
2375 .socketpair = sock_no_socketpair,
2376 .accept = sock_no_accept,
2377 .getname = tipc_getname,
2379 .ioctl = tipc_ioctl,
2380 .listen = sock_no_listen,
2381 .shutdown = tipc_shutdown,
2382 .setsockopt = tipc_setsockopt,
2383 .getsockopt = tipc_getsockopt,
2384 .sendmsg = tipc_sendmsg,
2385 .recvmsg = tipc_recvmsg,
2386 .mmap = sock_no_mmap,
2387 .sendpage = sock_no_sendpage
2390 static const struct proto_ops packet_ops = {
2391 .owner = THIS_MODULE,
2393 .release = tipc_release,
2395 .connect = tipc_connect,
2396 .socketpair = sock_no_socketpair,
2397 .accept = tipc_accept,
2398 .getname = tipc_getname,
2400 .ioctl = tipc_ioctl,
2401 .listen = tipc_listen,
2402 .shutdown = tipc_shutdown,
2403 .setsockopt = tipc_setsockopt,
2404 .getsockopt = tipc_getsockopt,
2405 .sendmsg = tipc_send_packet,
2406 .recvmsg = tipc_recvmsg,
2407 .mmap = sock_no_mmap,
2408 .sendpage = sock_no_sendpage
2411 static const struct proto_ops stream_ops = {
2412 .owner = THIS_MODULE,
2414 .release = tipc_release,
2416 .connect = tipc_connect,
2417 .socketpair = sock_no_socketpair,
2418 .accept = tipc_accept,
2419 .getname = tipc_getname,
2421 .ioctl = tipc_ioctl,
2422 .listen = tipc_listen,
2423 .shutdown = tipc_shutdown,
2424 .setsockopt = tipc_setsockopt,
2425 .getsockopt = tipc_getsockopt,
2426 .sendmsg = tipc_send_stream,
2427 .recvmsg = tipc_recv_stream,
2428 .mmap = sock_no_mmap,
2429 .sendpage = sock_no_sendpage
2432 static const struct net_proto_family tipc_family_ops = {
2433 .owner = THIS_MODULE,
2435 .create = tipc_sk_create
2438 static struct proto tipc_proto = {
2440 .owner = THIS_MODULE,
2441 .obj_size = sizeof(struct tipc_sock),
2442 .sysctl_rmem = sysctl_tipc_rmem
2445 static struct proto tipc_proto_kern = {
2447 .obj_size = sizeof(struct tipc_sock),
2448 .sysctl_rmem = sysctl_tipc_rmem
2452 * tipc_socket_init - initialize TIPC socket interface
2454 * Returns 0 on success, errno otherwise
2456 int tipc_socket_init(void)
2460 res = proto_register(&tipc_proto, 1);
2462 pr_err("Failed to register TIPC protocol type\n");
2466 res = sock_register(&tipc_family_ops);
2468 pr_err("Failed to register TIPC socket type\n");
2469 proto_unregister(&tipc_proto);
2477 * tipc_socket_stop - stop TIPC socket interface
2479 void tipc_socket_stop(void)
2481 sock_unregister(tipc_family_ops.family);
2482 proto_unregister(&tipc_proto);