2 * net/tipc/socket.c: TIPC socket API
4 * Copyright (c) 2001-2007, 2012 Ericsson AB
5 * Copyright (c) 2004-2008, 2010-2012, 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 <linux/export.h>
43 #define SS_LISTENING -1 /* socket is listening */
44 #define SS_READY -2 /* socket is connectionless */
46 #define CONN_TIMEOUT_DEFAULT 8000 /* default connect timeout = 8s */
51 struct tipc_portid peer_name;
52 unsigned int conn_timeout;
55 #define tipc_sk(sk) ((struct tipc_sock *)(sk))
56 #define tipc_sk_port(sk) (tipc_sk(sk)->p)
58 #define tipc_rx_ready(sock) (!skb_queue_empty(&sock->sk->sk_receive_queue) || \
59 (sock->state == SS_DISCONNECTING))
61 static int backlog_rcv(struct sock *sk, struct sk_buff *skb);
62 static u32 dispatch(struct tipc_port *tport, struct sk_buff *buf);
63 static void wakeupdispatch(struct tipc_port *tport);
64 static void tipc_data_ready(struct sock *sk, int len);
65 static void tipc_write_space(struct sock *sk);
67 static const struct proto_ops packet_ops;
68 static const struct proto_ops stream_ops;
69 static const struct proto_ops msg_ops;
71 static struct proto tipc_proto;
73 static int sockets_enabled;
76 * Revised TIPC socket locking policy:
78 * Most socket operations take the standard socket lock when they start
79 * and hold it until they finish (or until they need to sleep). Acquiring
80 * this lock grants the owner exclusive access to the fields of the socket
81 * data structures, with the exception of the backlog queue. A few socket
82 * operations can be done without taking the socket lock because they only
83 * read socket information that never changes during the life of the socket.
85 * Socket operations may acquire the lock for the associated TIPC port if they
86 * need to perform an operation on the port. If any routine needs to acquire
87 * both the socket lock and the port lock it must take the socket lock first
88 * to avoid the risk of deadlock.
90 * The dispatcher handling incoming messages cannot grab the socket lock in
91 * the standard fashion, since invoked it runs at the BH level and cannot block.
92 * Instead, it checks to see if the socket lock is currently owned by someone,
93 * and either handles the message itself or adds it to the socket's backlog
94 * queue; in the latter case the queued message is processed once the process
95 * owning the socket lock releases it.
97 * NOTE: Releasing the socket lock while an operation is sleeping overcomes
98 * the problem of a blocked socket operation preventing any other operations
99 * from occurring. However, applications must be careful if they have
100 * multiple threads trying to send (or receive) on the same socket, as these
101 * operations might interfere with each other. For example, doing a connect
102 * and a receive at the same time might allow the receive to consume the
103 * ACK message meant for the connect. While additional work could be done
104 * to try and overcome this, it doesn't seem to be worthwhile at the present.
106 * NOTE: Releasing the socket lock while an operation is sleeping also ensures
107 * that another operation that must be performed in a non-blocking manner is
108 * not delayed for very long because the lock has already been taken.
110 * NOTE: This code assumes that certain fields of a port/socket pair are
111 * constant over its lifetime; such fields can be examined without taking
112 * the socket lock and/or port lock, and do not need to be re-read even
113 * after resuming processing after waiting. These fields include:
115 * - pointer to socket sk structure (aka tipc_sock structure)
116 * - pointer to port structure
121 * advance_rx_queue - discard first buffer in socket receive queue
123 * Caller must hold socket lock
125 static void advance_rx_queue(struct sock *sk)
127 kfree_skb(__skb_dequeue(&sk->sk_receive_queue));
131 * reject_rx_queue - reject all buffers in socket receive queue
133 * Caller must hold socket lock
135 static void reject_rx_queue(struct sock *sk)
139 while ((buf = __skb_dequeue(&sk->sk_receive_queue)))
140 tipc_reject_msg(buf, TIPC_ERR_NO_PORT);
144 * tipc_create - create a TIPC socket
145 * @net: network namespace (must be default network)
146 * @sock: pre-allocated socket structure
147 * @protocol: protocol indicator (must be 0)
148 * @kern: caused by kernel or by userspace?
150 * This routine creates additional data structures used by the TIPC socket,
151 * initializes them, and links them together.
153 * Returns 0 on success, errno otherwise
155 static int tipc_create(struct net *net, struct socket *sock, int protocol,
158 const struct proto_ops *ops;
161 struct tipc_port *tp_ptr;
163 /* Validate arguments */
164 if (unlikely(protocol != 0))
165 return -EPROTONOSUPPORT;
167 switch (sock->type) {
170 state = SS_UNCONNECTED;
174 state = SS_UNCONNECTED;
185 /* Allocate socket's protocol area */
186 sk = sk_alloc(net, AF_TIPC, GFP_KERNEL, &tipc_proto);
190 /* Allocate TIPC port for socket to use */
191 tp_ptr = tipc_createport_raw(sk, &dispatch, &wakeupdispatch,
192 TIPC_LOW_IMPORTANCE);
193 if (unlikely(!tp_ptr)) {
198 /* Finish initializing socket data structures */
202 sock_init_data(sock, sk);
203 sk->sk_backlog_rcv = backlog_rcv;
204 sk->sk_rcvbuf = sysctl_tipc_rmem[1];
205 sk->sk_data_ready = tipc_data_ready;
206 sk->sk_write_space = tipc_write_space;
207 tipc_sk(sk)->p = tp_ptr;
208 tipc_sk(sk)->conn_timeout = CONN_TIMEOUT_DEFAULT;
210 spin_unlock_bh(tp_ptr->lock);
212 if (sock->state == SS_READY) {
213 tipc_set_portunreturnable(tp_ptr->ref, 1);
214 if (sock->type == SOCK_DGRAM)
215 tipc_set_portunreliable(tp_ptr->ref, 1);
222 * release - destroy a TIPC socket
223 * @sock: socket to destroy
225 * This routine cleans up any messages that are still queued on the socket.
226 * For DGRAM and RDM socket types, all queued messages are rejected.
227 * For SEQPACKET and STREAM socket types, the first message is rejected
228 * and any others are discarded. (If the first message on a STREAM socket
229 * is partially-read, it is discarded and the next one is rejected instead.)
231 * NOTE: Rejected messages are not necessarily returned to the sender! They
232 * are returned or discarded according to the "destination droppable" setting
233 * specified for the message by the sender.
235 * Returns 0 on success, errno otherwise
237 static int release(struct socket *sock)
239 struct sock *sk = sock->sk;
240 struct tipc_port *tport;
245 * Exit if socket isn't fully initialized (occurs when a failed accept()
246 * releases a pre-allocated child socket that was never used)
251 tport = tipc_sk_port(sk);
255 * Reject all unreceived messages, except on an active connection
256 * (which disconnects locally & sends a 'FIN+' to peer)
258 while (sock->state != SS_DISCONNECTING) {
259 buf = __skb_dequeue(&sk->sk_receive_queue);
262 if (TIPC_SKB_CB(buf)->handle != 0)
265 if ((sock->state == SS_CONNECTING) ||
266 (sock->state == SS_CONNECTED)) {
267 sock->state = SS_DISCONNECTING;
268 tipc_disconnect(tport->ref);
270 tipc_reject_msg(buf, TIPC_ERR_NO_PORT);
275 * Delete TIPC port; this ensures no more messages are queued
276 * (also disconnects an active connection & sends a 'FIN-' to peer)
278 res = tipc_deleteport(tport->ref);
280 /* Discard any remaining (connection-based) messages in receive queue */
281 __skb_queue_purge(&sk->sk_receive_queue);
283 /* Reject any messages that accumulated in backlog queue */
284 sock->state = SS_DISCONNECTING;
294 * bind - associate or disassocate TIPC name(s) with a socket
295 * @sock: socket structure
296 * @uaddr: socket address describing name(s) and desired operation
297 * @uaddr_len: size of socket address data structure
299 * Name and name sequence binding is indicated using a positive scope value;
300 * a negative scope value unbinds the specified name. Specifying no name
301 * (i.e. a socket address length of 0) unbinds all names from the socket.
303 * Returns 0 on success, errno otherwise
305 * NOTE: This routine doesn't need to take the socket lock since it doesn't
306 * access any non-constant socket information.
308 static int bind(struct socket *sock, struct sockaddr *uaddr, int uaddr_len)
310 struct sockaddr_tipc *addr = (struct sockaddr_tipc *)uaddr;
311 u32 portref = tipc_sk_port(sock->sk)->ref;
313 if (unlikely(!uaddr_len))
314 return tipc_withdraw(portref, 0, NULL);
316 if (uaddr_len < sizeof(struct sockaddr_tipc))
318 if (addr->family != AF_TIPC)
319 return -EAFNOSUPPORT;
321 if (addr->addrtype == TIPC_ADDR_NAME)
322 addr->addr.nameseq.upper = addr->addr.nameseq.lower;
323 else if (addr->addrtype != TIPC_ADDR_NAMESEQ)
324 return -EAFNOSUPPORT;
326 if (addr->addr.nameseq.type < TIPC_RESERVED_TYPES)
329 return (addr->scope > 0) ?
330 tipc_publish(portref, addr->scope, &addr->addr.nameseq) :
331 tipc_withdraw(portref, -addr->scope, &addr->addr.nameseq);
335 * get_name - get port ID of socket or peer socket
336 * @sock: socket structure
337 * @uaddr: area for returned socket address
338 * @uaddr_len: area for returned length of socket address
339 * @peer: 0 = own ID, 1 = current peer ID, 2 = current/former peer ID
341 * Returns 0 on success, errno otherwise
343 * NOTE: This routine doesn't need to take the socket lock since it only
344 * accesses socket information that is unchanging (or which changes in
345 * a completely predictable manner).
347 static int get_name(struct socket *sock, struct sockaddr *uaddr,
348 int *uaddr_len, int peer)
350 struct sockaddr_tipc *addr = (struct sockaddr_tipc *)uaddr;
351 struct tipc_sock *tsock = tipc_sk(sock->sk);
353 memset(addr, 0, sizeof(*addr));
355 if ((sock->state != SS_CONNECTED) &&
356 ((peer != 2) || (sock->state != SS_DISCONNECTING)))
358 addr->addr.id.ref = tsock->peer_name.ref;
359 addr->addr.id.node = tsock->peer_name.node;
361 addr->addr.id.ref = tsock->p->ref;
362 addr->addr.id.node = tipc_own_addr;
365 *uaddr_len = sizeof(*addr);
366 addr->addrtype = TIPC_ADDR_ID;
367 addr->family = AF_TIPC;
369 addr->addr.name.domain = 0;
375 * poll - read and possibly block on pollmask
376 * @file: file structure associated with the socket
377 * @sock: socket for which to calculate the poll bits
380 * Returns pollmask value
383 * It appears that the usual socket locking mechanisms are not useful here
384 * since the pollmask info is potentially out-of-date the moment this routine
385 * exits. TCP and other protocols seem to rely on higher level poll routines
386 * to handle any preventable race conditions, so TIPC will do the same ...
388 * TIPC sets the returned events as follows:
390 * socket state flags set
391 * ------------ ---------
392 * unconnected no read flags
393 * POLLOUT if port is not congested
395 * connecting POLLIN/POLLRDNORM if ACK/NACK in rx queue
398 * connected POLLIN/POLLRDNORM if data in rx queue
399 * POLLOUT if port is not congested
401 * disconnecting POLLIN/POLLRDNORM/POLLHUP
404 * listening POLLIN if SYN in rx queue
407 * ready POLLIN/POLLRDNORM if data in rx queue
408 * [connectionless] POLLOUT (since port cannot be congested)
410 * IMPORTANT: The fact that a read or write operation is indicated does NOT
411 * imply that the operation will succeed, merely that it should be performed
412 * and will not block.
414 static unsigned int poll(struct file *file, struct socket *sock,
417 struct sock *sk = sock->sk;
420 sock_poll_wait(file, sk_sleep(sk), wait);
422 switch ((int)sock->state) {
424 if (!tipc_sk_port(sk)->congested)
429 if (!tipc_sk_port(sk)->congested)
434 if (!skb_queue_empty(&sk->sk_receive_queue))
435 mask |= (POLLIN | POLLRDNORM);
437 case SS_DISCONNECTING:
438 mask = (POLLIN | POLLRDNORM | POLLHUP);
446 * dest_name_check - verify user is permitted to send to specified port name
447 * @dest: destination address
448 * @m: descriptor for message to be sent
450 * Prevents restricted configuration commands from being issued by
451 * unauthorized users.
453 * Returns 0 if permission is granted, otherwise errno
455 static int dest_name_check(struct sockaddr_tipc *dest, struct msghdr *m)
457 struct tipc_cfg_msg_hdr hdr;
459 if (likely(dest->addr.name.name.type >= TIPC_RESERVED_TYPES))
461 if (likely(dest->addr.name.name.type == TIPC_TOP_SRV))
463 if (likely(dest->addr.name.name.type != TIPC_CFG_SRV))
466 if (!m->msg_iovlen || (m->msg_iov[0].iov_len < sizeof(hdr)))
468 if (copy_from_user(&hdr, m->msg_iov[0].iov_base, sizeof(hdr)))
470 if ((ntohs(hdr.tcm_type) & 0xC000) && (!capable(CAP_NET_ADMIN)))
477 * send_msg - send message in connectionless manner
478 * @iocb: if NULL, indicates that socket lock is already held
479 * @sock: socket structure
480 * @m: message to send
481 * @total_len: length of message
483 * Message must have an destination specified explicitly.
484 * Used for SOCK_RDM and SOCK_DGRAM messages,
485 * and for 'SYN' messages on SOCK_SEQPACKET and SOCK_STREAM connections.
486 * (Note: 'SYN+' is prohibited on SOCK_STREAM.)
488 * Returns the number of bytes sent on success, or errno otherwise
490 static int send_msg(struct kiocb *iocb, struct socket *sock,
491 struct msghdr *m, size_t total_len)
493 struct sock *sk = sock->sk;
494 struct tipc_port *tport = tipc_sk_port(sk);
495 struct sockaddr_tipc *dest = (struct sockaddr_tipc *)m->msg_name;
501 return -EDESTADDRREQ;
502 if (unlikely((m->msg_namelen < sizeof(*dest)) ||
503 (dest->family != AF_TIPC)))
505 if (total_len > TIPC_MAX_USER_MSG_SIZE)
511 needs_conn = (sock->state != SS_READY);
512 if (unlikely(needs_conn)) {
513 if (sock->state == SS_LISTENING) {
517 if (sock->state != SS_UNCONNECTED) {
521 if ((tport->published) ||
522 ((sock->type == SOCK_STREAM) && (total_len != 0))) {
526 if (dest->addrtype == TIPC_ADDR_NAME) {
527 tport->conn_type = dest->addr.name.name.type;
528 tport->conn_instance = dest->addr.name.name.instance;
531 /* Abort any pending connection attempts (very unlikely) */
535 timeout_val = sock_sndtimeo(sk, m->msg_flags & MSG_DONTWAIT);
538 if (dest->addrtype == TIPC_ADDR_NAME) {
539 res = dest_name_check(dest, m);
542 res = tipc_send2name(tport->ref,
543 &dest->addr.name.name,
544 dest->addr.name.domain,
548 } else if (dest->addrtype == TIPC_ADDR_ID) {
549 res = tipc_send2port(tport->ref,
554 } else if (dest->addrtype == TIPC_ADDR_MCAST) {
559 res = dest_name_check(dest, m);
562 res = tipc_multicast(tport->ref,
568 if (likely(res != -ELINKCONG)) {
569 if (needs_conn && (res >= 0))
570 sock->state = SS_CONNECTING;
573 if (timeout_val <= 0L) {
574 res = timeout_val ? timeout_val : -EWOULDBLOCK;
578 timeout_val = wait_event_interruptible_timeout(*sk_sleep(sk),
579 !tport->congested, timeout_val);
590 * send_packet - send a connection-oriented message
591 * @iocb: if NULL, indicates that socket lock is already held
592 * @sock: socket structure
593 * @m: message to send
594 * @total_len: length of message
596 * Used for SOCK_SEQPACKET messages and SOCK_STREAM data.
598 * Returns the number of bytes sent on success, or errno otherwise
600 static int send_packet(struct kiocb *iocb, struct socket *sock,
601 struct msghdr *m, size_t total_len)
603 struct sock *sk = sock->sk;
604 struct tipc_port *tport = tipc_sk_port(sk);
605 struct sockaddr_tipc *dest = (struct sockaddr_tipc *)m->msg_name;
609 /* Handle implied connection establishment */
611 return send_msg(iocb, sock, m, total_len);
613 if (total_len > TIPC_MAX_USER_MSG_SIZE)
619 timeout_val = sock_sndtimeo(sk, m->msg_flags & MSG_DONTWAIT);
622 if (unlikely(sock->state != SS_CONNECTED)) {
623 if (sock->state == SS_DISCONNECTING)
630 res = tipc_send(tport->ref, m->msg_iovlen, m->msg_iov,
632 if (likely(res != -ELINKCONG))
634 if (timeout_val <= 0L) {
635 res = timeout_val ? timeout_val : -EWOULDBLOCK;
639 timeout_val = wait_event_interruptible_timeout(*sk_sleep(sk),
640 (!tport->congested || !tport->connected), timeout_val);
650 * send_stream - send stream-oriented data
652 * @sock: socket structure
654 * @total_len: total length of data to be sent
656 * Used for SOCK_STREAM data.
658 * Returns the number of bytes sent on success (or partial success),
659 * or errno if no data sent
661 static int send_stream(struct kiocb *iocb, struct socket *sock,
662 struct msghdr *m, size_t total_len)
664 struct sock *sk = sock->sk;
665 struct tipc_port *tport = tipc_sk_port(sk);
666 struct msghdr my_msg;
668 struct iovec *curr_iov;
670 char __user *curr_start;
679 /* Handle special cases where there is no connection */
680 if (unlikely(sock->state != SS_CONNECTED)) {
681 if (sock->state == SS_UNCONNECTED) {
682 res = send_packet(NULL, sock, m, total_len);
684 } else if (sock->state == SS_DISCONNECTING) {
693 if (unlikely(m->msg_name)) {
698 if (total_len > (unsigned int)INT_MAX) {
704 * Send each iovec entry using one or more messages
706 * Note: This algorithm is good for the most likely case
707 * (i.e. one large iovec entry), but could be improved to pass sets
708 * of small iovec entries into send_packet().
710 curr_iov = m->msg_iov;
711 curr_iovlen = m->msg_iovlen;
712 my_msg.msg_iov = &my_iov;
713 my_msg.msg_iovlen = 1;
714 my_msg.msg_flags = m->msg_flags;
715 my_msg.msg_name = NULL;
718 hdr_size = msg_hdr_sz(&tport->phdr);
720 while (curr_iovlen--) {
721 curr_start = curr_iov->iov_base;
722 curr_left = curr_iov->iov_len;
725 bytes_to_send = tport->max_pkt - hdr_size;
726 if (bytes_to_send > TIPC_MAX_USER_MSG_SIZE)
727 bytes_to_send = TIPC_MAX_USER_MSG_SIZE;
728 if (curr_left < bytes_to_send)
729 bytes_to_send = curr_left;
730 my_iov.iov_base = curr_start;
731 my_iov.iov_len = bytes_to_send;
732 res = send_packet(NULL, sock, &my_msg, bytes_to_send);
738 curr_left -= bytes_to_send;
739 curr_start += bytes_to_send;
740 bytes_sent += bytes_to_send;
752 * auto_connect - complete connection setup to a remote port
753 * @sock: socket structure
754 * @msg: peer's response message
756 * Returns 0 on success, errno otherwise
758 static int auto_connect(struct socket *sock, struct tipc_msg *msg)
760 struct tipc_sock *tsock = tipc_sk(sock->sk);
761 struct tipc_port *p_ptr;
763 tsock->peer_name.ref = msg_origport(msg);
764 tsock->peer_name.node = msg_orignode(msg);
765 p_ptr = tipc_port_deref(tsock->p->ref);
769 __tipc_connect(tsock->p->ref, p_ptr, &tsock->peer_name);
771 if (msg_importance(msg) > TIPC_CRITICAL_IMPORTANCE)
773 msg_set_importance(&p_ptr->phdr, (u32)msg_importance(msg));
774 sock->state = SS_CONNECTED;
779 * set_orig_addr - capture sender's address for received message
780 * @m: descriptor for message info
781 * @msg: received message header
783 * Note: Address is not captured if not requested by receiver.
785 static void set_orig_addr(struct msghdr *m, struct tipc_msg *msg)
787 struct sockaddr_tipc *addr = (struct sockaddr_tipc *)m->msg_name;
790 addr->family = AF_TIPC;
791 addr->addrtype = TIPC_ADDR_ID;
792 memset(&addr->addr, 0, sizeof(addr->addr));
793 addr->addr.id.ref = msg_origport(msg);
794 addr->addr.id.node = msg_orignode(msg);
795 addr->addr.name.domain = 0; /* could leave uninitialized */
796 addr->scope = 0; /* could leave uninitialized */
797 m->msg_namelen = sizeof(struct sockaddr_tipc);
802 * anc_data_recv - optionally capture ancillary data for received message
803 * @m: descriptor for message info
804 * @msg: received message header
805 * @tport: TIPC port associated with message
807 * Note: Ancillary data is not captured if not requested by receiver.
809 * Returns 0 if successful, otherwise errno
811 static int anc_data_recv(struct msghdr *m, struct tipc_msg *msg,
812 struct tipc_port *tport)
820 if (likely(m->msg_controllen == 0))
823 /* Optionally capture errored message object(s) */
824 err = msg ? msg_errcode(msg) : 0;
827 anc_data[1] = msg_data_sz(msg);
828 res = put_cmsg(m, SOL_TIPC, TIPC_ERRINFO, 8, anc_data);
832 res = put_cmsg(m, SOL_TIPC, TIPC_RETDATA, anc_data[1],
839 /* Optionally capture message destination object */
840 dest_type = msg ? msg_type(msg) : TIPC_DIRECT_MSG;
844 anc_data[0] = msg_nametype(msg);
845 anc_data[1] = msg_namelower(msg);
846 anc_data[2] = msg_namelower(msg);
850 anc_data[0] = msg_nametype(msg);
851 anc_data[1] = msg_namelower(msg);
852 anc_data[2] = msg_nameupper(msg);
855 has_name = (tport->conn_type != 0);
856 anc_data[0] = tport->conn_type;
857 anc_data[1] = tport->conn_instance;
858 anc_data[2] = tport->conn_instance;
864 res = put_cmsg(m, SOL_TIPC, TIPC_DESTNAME, 12, anc_data);
873 * recv_msg - receive packet-oriented message
875 * @m: descriptor for message info
876 * @buf_len: total size of user buffer area
877 * @flags: receive flags
879 * Used for SOCK_DGRAM, SOCK_RDM, and SOCK_SEQPACKET messages.
880 * If the complete message doesn't fit in user area, truncate it.
882 * Returns size of returned message data, errno otherwise
884 static int recv_msg(struct kiocb *iocb, struct socket *sock,
885 struct msghdr *m, size_t buf_len, int flags)
887 struct sock *sk = sock->sk;
888 struct tipc_port *tport = tipc_sk_port(sk);
890 struct tipc_msg *msg;
896 /* Catch invalid receive requests */
897 if (unlikely(!buf_len))
902 if (unlikely(sock->state == SS_UNCONNECTED)) {
907 /* will be updated in set_orig_addr() if needed */
910 timeout = sock_rcvtimeo(sk, flags & MSG_DONTWAIT);
913 /* Look for a message in receive queue; wait if necessary */
914 while (skb_queue_empty(&sk->sk_receive_queue)) {
915 if (sock->state == SS_DISCONNECTING) {
920 res = timeout ? timeout : -EWOULDBLOCK;
924 timeout = wait_event_interruptible_timeout(*sk_sleep(sk),
930 /* Look at first message in receive queue */
931 buf = skb_peek(&sk->sk_receive_queue);
933 sz = msg_data_sz(msg);
934 err = msg_errcode(msg);
936 /* Discard an empty non-errored message & try again */
937 if ((!sz) && (!err)) {
938 advance_rx_queue(sk);
942 /* Capture sender's address (optional) */
943 set_orig_addr(m, msg);
945 /* Capture ancillary data (optional) */
946 res = anc_data_recv(m, msg, tport);
950 /* Capture message data (if valid) & compute return value (always) */
952 if (unlikely(buf_len < sz)) {
954 m->msg_flags |= MSG_TRUNC;
956 res = skb_copy_datagram_iovec(buf, msg_hdr_sz(msg),
962 if ((sock->state == SS_READY) ||
963 ((err == TIPC_CONN_SHUTDOWN) || m->msg_control))
969 /* Consume received message (optional) */
970 if (likely(!(flags & MSG_PEEK))) {
971 if ((sock->state != SS_READY) &&
972 (++tport->conn_unacked >= TIPC_FLOW_CONTROL_WIN))
973 tipc_acknowledge(tport->ref, tport->conn_unacked);
974 advance_rx_queue(sk);
982 * recv_stream - receive stream-oriented data
984 * @m: descriptor for message info
985 * @buf_len: total size of user buffer area
986 * @flags: receive flags
988 * Used for SOCK_STREAM messages only. If not enough data is available
989 * will optionally wait for more; never truncates data.
991 * Returns size of returned message data, errno otherwise
993 static int recv_stream(struct kiocb *iocb, struct socket *sock,
994 struct msghdr *m, size_t buf_len, int flags)
996 struct sock *sk = sock->sk;
997 struct tipc_port *tport = tipc_sk_port(sk);
999 struct tipc_msg *msg;
1002 int sz_to_copy, target, needed;
1007 /* Catch invalid receive attempts */
1008 if (unlikely(!buf_len))
1013 if (unlikely((sock->state == SS_UNCONNECTED) ||
1014 (sock->state == SS_CONNECTING))) {
1019 /* will be updated in set_orig_addr() if needed */
1022 target = sock_rcvlowat(sk, flags & MSG_WAITALL, buf_len);
1023 timeout = sock_rcvtimeo(sk, flags & MSG_DONTWAIT);
1026 /* Look for a message in receive queue; wait if necessary */
1027 while (skb_queue_empty(&sk->sk_receive_queue)) {
1028 if (sock->state == SS_DISCONNECTING) {
1032 if (timeout <= 0L) {
1033 res = timeout ? timeout : -EWOULDBLOCK;
1037 timeout = wait_event_interruptible_timeout(*sk_sleep(sk),
1038 tipc_rx_ready(sock),
1043 /* Look at first message in receive queue */
1044 buf = skb_peek(&sk->sk_receive_queue);
1046 sz = msg_data_sz(msg);
1047 err = msg_errcode(msg);
1049 /* Discard an empty non-errored message & try again */
1050 if ((!sz) && (!err)) {
1051 advance_rx_queue(sk);
1055 /* Optionally capture sender's address & ancillary data of first msg */
1056 if (sz_copied == 0) {
1057 set_orig_addr(m, msg);
1058 res = anc_data_recv(m, msg, tport);
1063 /* Capture message data (if valid) & compute return value (always) */
1065 u32 offset = (u32)(unsigned long)(TIPC_SKB_CB(buf)->handle);
1068 needed = (buf_len - sz_copied);
1069 sz_to_copy = (sz <= needed) ? sz : needed;
1071 res = skb_copy_datagram_iovec(buf, msg_hdr_sz(msg) + offset,
1072 m->msg_iov, sz_to_copy);
1076 sz_copied += sz_to_copy;
1078 if (sz_to_copy < sz) {
1079 if (!(flags & MSG_PEEK))
1080 TIPC_SKB_CB(buf)->handle =
1081 (void *)(unsigned long)(offset + sz_to_copy);
1086 goto exit; /* can't add error msg to valid data */
1088 if ((err == TIPC_CONN_SHUTDOWN) || m->msg_control)
1094 /* Consume received message (optional) */
1095 if (likely(!(flags & MSG_PEEK))) {
1096 if (unlikely(++tport->conn_unacked >= TIPC_FLOW_CONTROL_WIN))
1097 tipc_acknowledge(tport->ref, tport->conn_unacked);
1098 advance_rx_queue(sk);
1101 /* Loop around if more data is required */
1102 if ((sz_copied < buf_len) && /* didn't get all requested data */
1103 (!skb_queue_empty(&sk->sk_receive_queue) ||
1104 (sz_copied < target)) && /* and more is ready or required */
1105 (!(flags & MSG_PEEK)) && /* and aren't just peeking at data */
1106 (!err)) /* and haven't reached a FIN */
1111 return sz_copied ? sz_copied : res;
1115 * tipc_write_space - wake up thread if port congestion is released
1118 static void tipc_write_space(struct sock *sk)
1120 struct socket_wq *wq;
1123 wq = rcu_dereference(sk->sk_wq);
1124 if (wq_has_sleeper(wq))
1125 wake_up_interruptible_sync_poll(&wq->wait, POLLOUT |
1126 POLLWRNORM | POLLWRBAND);
1131 * tipc_data_ready - wake up threads to indicate messages have been received
1133 * @len: the length of messages
1135 static void tipc_data_ready(struct sock *sk, int len)
1137 struct socket_wq *wq;
1140 wq = rcu_dereference(sk->sk_wq);
1141 if (wq_has_sleeper(wq))
1142 wake_up_interruptible_sync_poll(&wq->wait, POLLIN |
1143 POLLRDNORM | POLLRDBAND);
1148 * filter_connect - Handle all incoming messages for a connection-based socket
1149 * @tsock: TIPC socket
1152 * Returns TIPC error status code and socket error status code
1153 * once it encounters some errors
1155 static u32 filter_connect(struct tipc_sock *tsock, struct sk_buff **buf)
1157 struct socket *sock = tsock->sk.sk_socket;
1158 struct tipc_msg *msg = buf_msg(*buf);
1159 struct sock *sk = &tsock->sk;
1160 u32 retval = TIPC_ERR_NO_PORT;
1166 switch ((int)sock->state) {
1168 /* Accept only connection-based messages sent by peer */
1169 if (msg_connected(msg) && tipc_port_peer_msg(tsock->p, msg)) {
1170 if (unlikely(msg_errcode(msg))) {
1171 sock->state = SS_DISCONNECTING;
1172 __tipc_disconnect(tsock->p);
1178 /* Accept only ACK or NACK message */
1179 if (unlikely(msg_errcode(msg))) {
1180 sock->state = SS_DISCONNECTING;
1181 sk->sk_err = -ECONNREFUSED;
1186 if (unlikely(!msg_connected(msg)))
1189 res = auto_connect(sock, msg);
1191 sock->state = SS_DISCONNECTING;
1197 /* If an incoming message is an 'ACK-', it should be
1198 * discarded here because it doesn't contain useful
1199 * data. In addition, we should try to wake up
1200 * connect() routine if sleeping.
1202 if (msg_data_sz(msg) == 0) {
1205 if (waitqueue_active(sk_sleep(sk)))
1206 wake_up_interruptible(sk_sleep(sk));
1211 case SS_UNCONNECTED:
1212 /* Accept only SYN message */
1213 if (!msg_connected(msg) && !(msg_errcode(msg)))
1216 case SS_DISCONNECTING:
1219 pr_err("Unknown socket state %u\n", sock->state);
1225 * rcvbuf_limit - get proper overload limit of socket receive queue
1229 * For all connection oriented messages, irrespective of importance,
1230 * the default overload value (i.e. 67MB) is set as limit.
1232 * For all connectionless messages, by default new queue limits are
1235 * TIPC_LOW_IMPORTANCE (4 MB)
1236 * TIPC_MEDIUM_IMPORTANCE (8 MB)
1237 * TIPC_HIGH_IMPORTANCE (16 MB)
1238 * TIPC_CRITICAL_IMPORTANCE (32 MB)
1240 * Returns overload limit according to corresponding message importance
1242 static unsigned int rcvbuf_limit(struct sock *sk, struct sk_buff *buf)
1244 struct tipc_msg *msg = buf_msg(buf);
1247 if (msg_connected(msg))
1248 limit = sysctl_tipc_rmem[2];
1250 limit = sk->sk_rcvbuf >> TIPC_CRITICAL_IMPORTANCE <<
1251 msg_importance(msg);
1256 * filter_rcv - validate incoming message
1260 * Enqueues message on receive queue if acceptable; optionally handles
1261 * disconnect indication for a connected socket.
1263 * Called with socket lock already taken; port lock may also be taken.
1265 * Returns TIPC error status code (TIPC_OK if message is not to be rejected)
1267 static u32 filter_rcv(struct sock *sk, struct sk_buff *buf)
1269 struct socket *sock = sk->sk_socket;
1270 struct tipc_msg *msg = buf_msg(buf);
1271 unsigned int limit = rcvbuf_limit(sk, buf);
1274 /* Reject message if it is wrong sort of message for socket */
1275 if (msg_type(msg) > TIPC_DIRECT_MSG)
1276 return TIPC_ERR_NO_PORT;
1278 if (sock->state == SS_READY) {
1279 if (msg_connected(msg))
1280 return TIPC_ERR_NO_PORT;
1282 res = filter_connect(tipc_sk(sk), &buf);
1283 if (res != TIPC_OK || buf == NULL)
1287 /* Reject message if there isn't room to queue it */
1288 if (sk_rmem_alloc_get(sk) + buf->truesize >= limit)
1289 return TIPC_ERR_OVERLOAD;
1291 /* Enqueue message */
1292 TIPC_SKB_CB(buf)->handle = 0;
1293 __skb_queue_tail(&sk->sk_receive_queue, buf);
1294 skb_set_owner_r(buf, sk);
1296 sk->sk_data_ready(sk, 0);
1301 * backlog_rcv - handle incoming message from backlog queue
1305 * Caller must hold socket lock, but not port lock.
1309 static int backlog_rcv(struct sock *sk, struct sk_buff *buf)
1313 res = filter_rcv(sk, buf);
1315 tipc_reject_msg(buf, res);
1320 * dispatch - handle incoming message
1321 * @tport: TIPC port that received message
1324 * Called with port lock already taken.
1326 * Returns TIPC error status code (TIPC_OK if message is not to be rejected)
1328 static u32 dispatch(struct tipc_port *tport, struct sk_buff *buf)
1330 struct sock *sk = (struct sock *)tport->usr_handle;
1334 * Process message if socket is unlocked; otherwise add to backlog queue
1336 * This code is based on sk_receive_skb(), but must be distinct from it
1337 * since a TIPC-specific filter/reject mechanism is utilized
1340 if (!sock_owned_by_user(sk)) {
1341 res = filter_rcv(sk, buf);
1343 if (sk_add_backlog(sk, buf, rcvbuf_limit(sk, buf)))
1344 res = TIPC_ERR_OVERLOAD;
1354 * wakeupdispatch - wake up port after congestion
1355 * @tport: port to wakeup
1357 * Called with port lock already taken.
1359 static void wakeupdispatch(struct tipc_port *tport)
1361 struct sock *sk = (struct sock *)tport->usr_handle;
1363 sk->sk_write_space(sk);
1367 * connect - establish a connection to another TIPC port
1368 * @sock: socket structure
1369 * @dest: socket address for destination port
1370 * @destlen: size of socket address data structure
1371 * @flags: file-related flags associated with socket
1373 * Returns 0 on success, errno otherwise
1375 static int connect(struct socket *sock, struct sockaddr *dest, int destlen,
1378 struct sock *sk = sock->sk;
1379 struct sockaddr_tipc *dst = (struct sockaddr_tipc *)dest;
1380 struct msghdr m = {NULL,};
1381 unsigned int timeout;
1386 /* For now, TIPC does not allow use of connect() with DGRAM/RDM types */
1387 if (sock->state == SS_READY) {
1393 * Reject connection attempt using multicast address
1395 * Note: send_msg() validates the rest of the address fields,
1396 * so there's no need to do it here
1398 if (dst->addrtype == TIPC_ADDR_MCAST) {
1403 timeout = (flags & O_NONBLOCK) ? 0 : tipc_sk(sk)->conn_timeout;
1405 switch (sock->state) {
1406 case SS_UNCONNECTED:
1407 /* Send a 'SYN-' to destination */
1409 m.msg_namelen = destlen;
1411 /* If connect is in non-blocking case, set MSG_DONTWAIT to
1412 * indicate send_msg() is never blocked.
1415 m.msg_flags = MSG_DONTWAIT;
1417 res = send_msg(NULL, sock, &m, 0);
1418 if ((res < 0) && (res != -EWOULDBLOCK))
1421 /* Just entered SS_CONNECTING state; the only
1422 * difference is that return value in non-blocking
1423 * case is EINPROGRESS, rather than EALREADY.
1438 if (sock->state == SS_CONNECTING) {
1442 /* Wait until an 'ACK' or 'RST' arrives, or a timeout occurs */
1444 res = wait_event_interruptible_timeout(*sk_sleep(sk),
1445 sock->state != SS_CONNECTING,
1446 timeout ? (long)msecs_to_jiffies(timeout)
1447 : MAX_SCHEDULE_TIMEOUT);
1453 ; /* leave "res" unchanged */
1458 if (unlikely(sock->state == SS_DISCONNECTING))
1459 res = sock_error(sk);
1469 * listen - allow socket to listen for incoming connections
1470 * @sock: socket structure
1473 * Returns 0 on success, errno otherwise
1475 static int listen(struct socket *sock, int len)
1477 struct sock *sk = sock->sk;
1482 if (sock->state != SS_UNCONNECTED)
1485 sock->state = SS_LISTENING;
1494 * accept - wait for connection request
1495 * @sock: listening socket
1496 * @newsock: new socket that is to be connected
1497 * @flags: file-related flags associated with socket
1499 * Returns 0 on success, errno otherwise
1501 static int accept(struct socket *sock, struct socket *new_sock, int flags)
1503 struct sock *new_sk, *sk = sock->sk;
1504 struct sk_buff *buf;
1505 struct tipc_sock *new_tsock;
1506 struct tipc_port *new_tport;
1507 struct tipc_msg *msg;
1514 if (sock->state != SS_LISTENING) {
1519 while (skb_queue_empty(&sk->sk_receive_queue)) {
1520 if (flags & O_NONBLOCK) {
1525 res = wait_event_interruptible(*sk_sleep(sk),
1526 (!skb_queue_empty(&sk->sk_receive_queue)));
1532 buf = skb_peek(&sk->sk_receive_queue);
1534 res = tipc_create(sock_net(sock->sk), new_sock, 0, 0);
1538 new_sk = new_sock->sk;
1539 new_tsock = tipc_sk(new_sk);
1540 new_tport = new_tsock->p;
1541 new_ref = new_tport->ref;
1544 /* we lock on new_sk; but lockdep sees the lock on sk */
1545 lock_sock_nested(new_sk, SINGLE_DEPTH_NESTING);
1548 * Reject any stray messages received by new socket
1549 * before the socket lock was taken (very, very unlikely)
1551 reject_rx_queue(new_sk);
1553 /* Connect new socket to it's peer */
1554 new_tsock->peer_name.ref = msg_origport(msg);
1555 new_tsock->peer_name.node = msg_orignode(msg);
1556 tipc_connect(new_ref, &new_tsock->peer_name);
1557 new_sock->state = SS_CONNECTED;
1559 tipc_set_portimportance(new_ref, msg_importance(msg));
1560 if (msg_named(msg)) {
1561 new_tport->conn_type = msg_nametype(msg);
1562 new_tport->conn_instance = msg_nameinst(msg);
1566 * Respond to 'SYN-' by discarding it & returning 'ACK'-.
1567 * Respond to 'SYN+' by queuing it on new socket.
1569 if (!msg_data_sz(msg)) {
1570 struct msghdr m = {NULL,};
1572 advance_rx_queue(sk);
1573 send_packet(NULL, new_sock, &m, 0);
1575 __skb_dequeue(&sk->sk_receive_queue);
1576 __skb_queue_head(&new_sk->sk_receive_queue, buf);
1577 skb_set_owner_r(buf, new_sk);
1579 release_sock(new_sk);
1587 * shutdown - shutdown socket connection
1588 * @sock: socket structure
1589 * @how: direction to close (must be SHUT_RDWR)
1591 * Terminates connection (if necessary), then purges socket's receive queue.
1593 * Returns 0 on success, errno otherwise
1595 static int shutdown(struct socket *sock, int how)
1597 struct sock *sk = sock->sk;
1598 struct tipc_port *tport = tipc_sk_port(sk);
1599 struct sk_buff *buf;
1602 if (how != SHUT_RDWR)
1607 switch (sock->state) {
1612 /* Disconnect and send a 'FIN+' or 'FIN-' message to peer */
1613 buf = __skb_dequeue(&sk->sk_receive_queue);
1615 if (TIPC_SKB_CB(buf)->handle != 0) {
1619 tipc_disconnect(tport->ref);
1620 tipc_reject_msg(buf, TIPC_CONN_SHUTDOWN);
1622 tipc_shutdown(tport->ref);
1625 sock->state = SS_DISCONNECTING;
1629 case SS_DISCONNECTING:
1631 /* Discard any unreceived messages */
1632 __skb_queue_purge(&sk->sk_receive_queue);
1634 /* Wake up anyone sleeping in poll */
1635 sk->sk_state_change(sk);
1648 * setsockopt - set socket option
1649 * @sock: socket structure
1650 * @lvl: option level
1651 * @opt: option identifier
1652 * @ov: pointer to new option value
1653 * @ol: length of option value
1655 * For stream sockets only, accepts and ignores all IPPROTO_TCP options
1656 * (to ease compatibility).
1658 * Returns 0 on success, errno otherwise
1660 static int setsockopt(struct socket *sock,
1661 int lvl, int opt, char __user *ov, unsigned int ol)
1663 struct sock *sk = sock->sk;
1664 struct tipc_port *tport = tipc_sk_port(sk);
1668 if ((lvl == IPPROTO_TCP) && (sock->type == SOCK_STREAM))
1670 if (lvl != SOL_TIPC)
1671 return -ENOPROTOOPT;
1672 if (ol < sizeof(value))
1674 res = get_user(value, (u32 __user *)ov);
1681 case TIPC_IMPORTANCE:
1682 res = tipc_set_portimportance(tport->ref, value);
1684 case TIPC_SRC_DROPPABLE:
1685 if (sock->type != SOCK_STREAM)
1686 res = tipc_set_portunreliable(tport->ref, value);
1690 case TIPC_DEST_DROPPABLE:
1691 res = tipc_set_portunreturnable(tport->ref, value);
1693 case TIPC_CONN_TIMEOUT:
1694 tipc_sk(sk)->conn_timeout = value;
1695 /* no need to set "res", since already 0 at this point */
1707 * getsockopt - get socket option
1708 * @sock: socket structure
1709 * @lvl: option level
1710 * @opt: option identifier
1711 * @ov: receptacle for option value
1712 * @ol: receptacle for length of option value
1714 * For stream sockets only, returns 0 length result for all IPPROTO_TCP options
1715 * (to ease compatibility).
1717 * Returns 0 on success, errno otherwise
1719 static int getsockopt(struct socket *sock,
1720 int lvl, int opt, char __user *ov, int __user *ol)
1722 struct sock *sk = sock->sk;
1723 struct tipc_port *tport = tipc_sk_port(sk);
1728 if ((lvl == IPPROTO_TCP) && (sock->type == SOCK_STREAM))
1729 return put_user(0, ol);
1730 if (lvl != SOL_TIPC)
1731 return -ENOPROTOOPT;
1732 res = get_user(len, ol);
1739 case TIPC_IMPORTANCE:
1740 res = tipc_portimportance(tport->ref, &value);
1742 case TIPC_SRC_DROPPABLE:
1743 res = tipc_portunreliable(tport->ref, &value);
1745 case TIPC_DEST_DROPPABLE:
1746 res = tipc_portunreturnable(tport->ref, &value);
1748 case TIPC_CONN_TIMEOUT:
1749 value = tipc_sk(sk)->conn_timeout;
1750 /* no need to set "res", since already 0 at this point */
1752 case TIPC_NODE_RECVQ_DEPTH:
1753 value = 0; /* was tipc_queue_size, now obsolete */
1755 case TIPC_SOCK_RECVQ_DEPTH:
1756 value = skb_queue_len(&sk->sk_receive_queue);
1765 return res; /* "get" failed */
1767 if (len < sizeof(value))
1770 if (copy_to_user(ov, &value, sizeof(value)))
1773 return put_user(sizeof(value), ol);
1776 /* Protocol switches for the various types of TIPC sockets */
1778 static const struct proto_ops msg_ops = {
1779 .owner = THIS_MODULE,
1784 .socketpair = sock_no_socketpair,
1785 .accept = sock_no_accept,
1786 .getname = get_name,
1788 .ioctl = sock_no_ioctl,
1789 .listen = sock_no_listen,
1790 .shutdown = shutdown,
1791 .setsockopt = setsockopt,
1792 .getsockopt = getsockopt,
1793 .sendmsg = send_msg,
1794 .recvmsg = recv_msg,
1795 .mmap = sock_no_mmap,
1796 .sendpage = sock_no_sendpage
1799 static const struct proto_ops packet_ops = {
1800 .owner = THIS_MODULE,
1805 .socketpair = sock_no_socketpair,
1807 .getname = get_name,
1809 .ioctl = sock_no_ioctl,
1811 .shutdown = shutdown,
1812 .setsockopt = setsockopt,
1813 .getsockopt = getsockopt,
1814 .sendmsg = send_packet,
1815 .recvmsg = recv_msg,
1816 .mmap = sock_no_mmap,
1817 .sendpage = sock_no_sendpage
1820 static const struct proto_ops stream_ops = {
1821 .owner = THIS_MODULE,
1826 .socketpair = sock_no_socketpair,
1828 .getname = get_name,
1830 .ioctl = sock_no_ioctl,
1832 .shutdown = shutdown,
1833 .setsockopt = setsockopt,
1834 .getsockopt = getsockopt,
1835 .sendmsg = send_stream,
1836 .recvmsg = recv_stream,
1837 .mmap = sock_no_mmap,
1838 .sendpage = sock_no_sendpage
1841 static const struct net_proto_family tipc_family_ops = {
1842 .owner = THIS_MODULE,
1844 .create = tipc_create
1847 static struct proto tipc_proto = {
1849 .owner = THIS_MODULE,
1850 .obj_size = sizeof(struct tipc_sock),
1851 .sysctl_rmem = sysctl_tipc_rmem
1855 * tipc_socket_init - initialize TIPC socket interface
1857 * Returns 0 on success, errno otherwise
1859 int tipc_socket_init(void)
1863 res = proto_register(&tipc_proto, 1);
1865 pr_err("Failed to register TIPC protocol type\n");
1869 res = sock_register(&tipc_family_ops);
1871 pr_err("Failed to register TIPC socket type\n");
1872 proto_unregister(&tipc_proto);
1876 sockets_enabled = 1;
1882 * tipc_socket_stop - stop TIPC socket interface
1884 void tipc_socket_stop(void)
1886 if (!sockets_enabled)
1889 sockets_enabled = 0;
1890 sock_unregister(tipc_family_ops.family);
1891 proto_unregister(&tipc_proto);