2 * net/tipc/socket.c: TIPC socket API
4 * Copyright (c) 2001-2007, Ericsson AB
5 * Copyright (c) 2004-2008, 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.
37 #include <linux/module.h>
38 #include <linux/types.h>
39 #include <linux/net.h>
40 #include <linux/socket.h>
41 #include <linux/errno.h>
43 #include <linux/slab.h>
44 #include <linux/poll.h>
45 #include <linux/fcntl.h>
46 #include <asm/string.h>
47 #include <asm/atomic.h>
50 #include <linux/tipc.h>
51 #include <linux/tipc_config.h>
52 #include <net/tipc/tipc_msg.h>
53 #include <net/tipc/tipc_port.h>
57 #define SS_LISTENING -1 /* socket is listening */
58 #define SS_READY -2 /* socket is connectionless */
60 #define OVERLOAD_LIMIT_BASE 5000
61 #define CONN_TIMEOUT_DEFAULT 8000 /* default connect timeout = 8s */
66 struct tipc_portid peer_name;
69 #define tipc_sk(sk) ((struct tipc_sock *)(sk))
70 #define tipc_sk_port(sk) ((struct tipc_port *)(tipc_sk(sk)->p))
72 static int backlog_rcv(struct sock *sk, struct sk_buff *skb);
73 static u32 dispatch(struct tipc_port *tport, struct sk_buff *buf);
74 static void wakeupdispatch(struct tipc_port *tport);
76 static const struct proto_ops packet_ops;
77 static const struct proto_ops stream_ops;
78 static const struct proto_ops msg_ops;
80 static struct proto tipc_proto;
82 static int sockets_enabled = 0;
84 static atomic_t tipc_queue_size = ATOMIC_INIT(0);
87 * Revised TIPC socket locking policy:
89 * Most socket operations take the standard socket lock when they start
90 * and hold it until they finish (or until they need to sleep). Acquiring
91 * this lock grants the owner exclusive access to the fields of the socket
92 * data structures, with the exception of the backlog queue. A few socket
93 * operations can be done without taking the socket lock because they only
94 * read socket information that never changes during the life of the socket.
96 * Socket operations may acquire the lock for the associated TIPC port if they
97 * need to perform an operation on the port. If any routine needs to acquire
98 * both the socket lock and the port lock it must take the socket lock first
99 * to avoid the risk of deadlock.
101 * The dispatcher handling incoming messages cannot grab the socket lock in
102 * the standard fashion, since invoked it runs at the BH level and cannot block.
103 * Instead, it checks to see if the socket lock is currently owned by someone,
104 * and either handles the message itself or adds it to the socket's backlog
105 * queue; in the latter case the queued message is processed once the process
106 * owning the socket lock releases it.
108 * NOTE: Releasing the socket lock while an operation is sleeping overcomes
109 * the problem of a blocked socket operation preventing any other operations
110 * from occurring. However, applications must be careful if they have
111 * multiple threads trying to send (or receive) on the same socket, as these
112 * operations might interfere with each other. For example, doing a connect
113 * and a receive at the same time might allow the receive to consume the
114 * ACK message meant for the connect. While additional work could be done
115 * to try and overcome this, it doesn't seem to be worthwhile at the present.
117 * NOTE: Releasing the socket lock while an operation is sleeping also ensures
118 * that another operation that must be performed in a non-blocking manner is
119 * not delayed for very long because the lock has already been taken.
121 * NOTE: This code assumes that certain fields of a port/socket pair are
122 * constant over its lifetime; such fields can be examined without taking
123 * the socket lock and/or port lock, and do not need to be re-read even
124 * after resuming processing after waiting. These fields include:
126 * - pointer to socket sk structure (aka tipc_sock structure)
127 * - pointer to port structure
132 * advance_rx_queue - discard first buffer in socket receive queue
134 * Caller must hold socket lock
137 static void advance_rx_queue(struct sock *sk)
139 buf_discard(__skb_dequeue(&sk->sk_receive_queue));
140 atomic_dec(&tipc_queue_size);
144 * discard_rx_queue - discard all buffers in socket receive queue
146 * Caller must hold socket lock
149 static void discard_rx_queue(struct sock *sk)
153 while ((buf = __skb_dequeue(&sk->sk_receive_queue))) {
154 atomic_dec(&tipc_queue_size);
160 * reject_rx_queue - reject all buffers in socket receive queue
162 * Caller must hold socket lock
165 static void reject_rx_queue(struct sock *sk)
169 while ((buf = __skb_dequeue(&sk->sk_receive_queue))) {
170 tipc_reject_msg(buf, TIPC_ERR_NO_PORT);
171 atomic_dec(&tipc_queue_size);
176 * tipc_create - create a TIPC socket
177 * @net: network namespace (must be default network)
178 * @sock: pre-allocated socket structure
179 * @protocol: protocol indicator (must be 0)
181 * This routine creates additional data structures used by the TIPC socket,
182 * initializes them, and links them together.
184 * Returns 0 on success, errno otherwise
187 static int tipc_create(struct net *net, struct socket *sock, int protocol)
189 const struct proto_ops *ops;
192 struct tipc_port *tp_ptr;
194 /* Validate arguments */
196 if (net != &init_net)
197 return -EAFNOSUPPORT;
199 if (unlikely(protocol != 0))
200 return -EPROTONOSUPPORT;
202 switch (sock->type) {
205 state = SS_UNCONNECTED;
209 state = SS_UNCONNECTED;
220 /* Allocate socket's protocol area */
222 sk = sk_alloc(net, AF_TIPC, GFP_KERNEL, &tipc_proto);
226 /* Allocate TIPC port for socket to use */
228 tp_ptr = tipc_createport_raw(sk, &dispatch, &wakeupdispatch,
229 TIPC_LOW_IMPORTANCE);
230 if (unlikely(!tp_ptr)) {
235 /* Finish initializing socket data structures */
240 sock_init_data(sock, sk);
241 sk->sk_rcvtimeo = msecs_to_jiffies(CONN_TIMEOUT_DEFAULT);
242 sk->sk_backlog_rcv = backlog_rcv;
243 tipc_sk(sk)->p = tp_ptr;
245 spin_unlock_bh(tp_ptr->lock);
247 if (sock->state == SS_READY) {
248 tipc_set_portunreturnable(tp_ptr->ref, 1);
249 if (sock->type == SOCK_DGRAM)
250 tipc_set_portunreliable(tp_ptr->ref, 1);
253 atomic_inc(&tipc_user_count);
258 * release - destroy a TIPC socket
259 * @sock: socket to destroy
261 * This routine cleans up any messages that are still queued on the socket.
262 * For DGRAM and RDM socket types, all queued messages are rejected.
263 * For SEQPACKET and STREAM socket types, the first message is rejected
264 * and any others are discarded. (If the first message on a STREAM socket
265 * is partially-read, it is discarded and the next one is rejected instead.)
267 * NOTE: Rejected messages are not necessarily returned to the sender! They
268 * are returned or discarded according to the "destination droppable" setting
269 * specified for the message by the sender.
271 * Returns 0 on success, errno otherwise
274 static int release(struct socket *sock)
276 struct sock *sk = sock->sk;
277 struct tipc_port *tport;
282 * Exit if socket isn't fully initialized (occurs when a failed accept()
283 * releases a pre-allocated child socket that was never used)
289 tport = tipc_sk_port(sk);
293 * Reject all unreceived messages, except on an active connection
294 * (which disconnects locally & sends a 'FIN+' to peer)
297 while (sock->state != SS_DISCONNECTING) {
298 buf = __skb_dequeue(&sk->sk_receive_queue);
301 atomic_dec(&tipc_queue_size);
302 if (TIPC_SKB_CB(buf)->handle != msg_data(buf_msg(buf)))
305 if ((sock->state == SS_CONNECTING) ||
306 (sock->state == SS_CONNECTED)) {
307 sock->state = SS_DISCONNECTING;
308 tipc_disconnect(tport->ref);
310 tipc_reject_msg(buf, TIPC_ERR_NO_PORT);
315 * Delete TIPC port; this ensures no more messages are queued
316 * (also disconnects an active connection & sends a 'FIN-' to peer)
319 res = tipc_deleteport(tport->ref);
321 /* Discard any remaining (connection-based) messages in receive queue */
323 discard_rx_queue(sk);
325 /* Reject any messages that accumulated in backlog queue */
327 sock->state = SS_DISCONNECTING;
333 atomic_dec(&tipc_user_count);
338 * bind - associate or disassocate TIPC name(s) with a socket
339 * @sock: socket structure
340 * @uaddr: socket address describing name(s) and desired operation
341 * @uaddr_len: size of socket address data structure
343 * Name and name sequence binding is indicated using a positive scope value;
344 * a negative scope value unbinds the specified name. Specifying no name
345 * (i.e. a socket address length of 0) unbinds all names from the socket.
347 * Returns 0 on success, errno otherwise
349 * NOTE: This routine doesn't need to take the socket lock since it doesn't
350 * access any non-constant socket information.
353 static int bind(struct socket *sock, struct sockaddr *uaddr, int uaddr_len)
355 struct sockaddr_tipc *addr = (struct sockaddr_tipc *)uaddr;
356 u32 portref = tipc_sk_port(sock->sk)->ref;
358 if (unlikely(!uaddr_len))
359 return tipc_withdraw(portref, 0, NULL);
361 if (uaddr_len < sizeof(struct sockaddr_tipc))
363 if (addr->family != AF_TIPC)
364 return -EAFNOSUPPORT;
366 if (addr->addrtype == TIPC_ADDR_NAME)
367 addr->addr.nameseq.upper = addr->addr.nameseq.lower;
368 else if (addr->addrtype != TIPC_ADDR_NAMESEQ)
369 return -EAFNOSUPPORT;
371 return (addr->scope > 0) ?
372 tipc_publish(portref, addr->scope, &addr->addr.nameseq) :
373 tipc_withdraw(portref, -addr->scope, &addr->addr.nameseq);
377 * get_name - get port ID of socket or peer socket
378 * @sock: socket structure
379 * @uaddr: area for returned socket address
380 * @uaddr_len: area for returned length of socket address
381 * @peer: 0 = own ID, 1 = current peer ID, 2 = current/former peer ID
383 * Returns 0 on success, errno otherwise
385 * NOTE: This routine doesn't need to take the socket lock since it only
386 * accesses socket information that is unchanging (or which changes in
387 * a completely predictable manner).
390 static int get_name(struct socket *sock, struct sockaddr *uaddr,
391 int *uaddr_len, int peer)
393 struct sockaddr_tipc *addr = (struct sockaddr_tipc *)uaddr;
394 struct tipc_sock *tsock = tipc_sk(sock->sk);
397 if ((sock->state != SS_CONNECTED) &&
398 ((peer != 2) || (sock->state != SS_DISCONNECTING)))
400 addr->addr.id.ref = tsock->peer_name.ref;
401 addr->addr.id.node = tsock->peer_name.node;
403 tipc_ownidentity(tsock->p->ref, &addr->addr.id);
406 *uaddr_len = sizeof(*addr);
407 addr->addrtype = TIPC_ADDR_ID;
408 addr->family = AF_TIPC;
410 addr->addr.name.domain = 0;
416 * poll - read and possibly block on pollmask
417 * @file: file structure associated with the socket
418 * @sock: socket for which to calculate the poll bits
421 * Returns pollmask value
424 * It appears that the usual socket locking mechanisms are not useful here
425 * since the pollmask info is potentially out-of-date the moment this routine
426 * exits. TCP and other protocols seem to rely on higher level poll routines
427 * to handle any preventable race conditions, so TIPC will do the same ...
429 * TIPC sets the returned events as follows:
430 * a) POLLRDNORM and POLLIN are set if the socket's receive queue is non-empty
431 * or if a connection-oriented socket is does not have an active connection
432 * (i.e. a read operation will not block).
433 * b) POLLOUT is set except when a socket's connection has been terminated
434 * (i.e. a write operation will not block).
435 * c) POLLHUP is set when a socket's connection has been terminated.
437 * IMPORTANT: The fact that a read or write operation will not block does NOT
438 * imply that the operation will succeed!
441 static unsigned int poll(struct file *file, struct socket *sock,
444 struct sock *sk = sock->sk;
447 poll_wait(file, sk->sk_sleep, wait);
449 if (!skb_queue_empty(&sk->sk_receive_queue) ||
450 (sock->state == SS_UNCONNECTED) ||
451 (sock->state == SS_DISCONNECTING))
452 mask = (POLLRDNORM | POLLIN);
456 if (sock->state == SS_DISCONNECTING)
465 * dest_name_check - verify user is permitted to send to specified port name
466 * @dest: destination address
467 * @m: descriptor for message to be sent
469 * Prevents restricted configuration commands from being issued by
470 * unauthorized users.
472 * Returns 0 if permission is granted, otherwise errno
475 static int dest_name_check(struct sockaddr_tipc *dest, struct msghdr *m)
477 struct tipc_cfg_msg_hdr hdr;
479 if (likely(dest->addr.name.name.type >= TIPC_RESERVED_TYPES))
481 if (likely(dest->addr.name.name.type == TIPC_TOP_SRV))
483 if (likely(dest->addr.name.name.type != TIPC_CFG_SRV))
486 if (copy_from_user(&hdr, m->msg_iov[0].iov_base, sizeof(hdr)))
488 if ((ntohs(hdr.tcm_type) & 0xC000) && (!capable(CAP_NET_ADMIN)))
495 * send_msg - send message in connectionless manner
496 * @iocb: if NULL, indicates that socket lock is already held
497 * @sock: socket structure
498 * @m: message to send
499 * @total_len: length of message
501 * Message must have an destination specified explicitly.
502 * Used for SOCK_RDM and SOCK_DGRAM messages,
503 * and for 'SYN' messages on SOCK_SEQPACKET and SOCK_STREAM connections.
504 * (Note: 'SYN+' is prohibited on SOCK_STREAM.)
506 * Returns the number of bytes sent on success, or errno otherwise
509 static int send_msg(struct kiocb *iocb, struct socket *sock,
510 struct msghdr *m, size_t total_len)
512 struct sock *sk = sock->sk;
513 struct tipc_port *tport = tipc_sk_port(sk);
514 struct sockaddr_tipc *dest = (struct sockaddr_tipc *)m->msg_name;
519 return -EDESTADDRREQ;
520 if (unlikely((m->msg_namelen < sizeof(*dest)) ||
521 (dest->family != AF_TIPC)))
527 needs_conn = (sock->state != SS_READY);
528 if (unlikely(needs_conn)) {
529 if (sock->state == SS_LISTENING) {
533 if (sock->state != SS_UNCONNECTED) {
537 if ((tport->published) ||
538 ((sock->type == SOCK_STREAM) && (total_len != 0))) {
542 if (dest->addrtype == TIPC_ADDR_NAME) {
543 tport->conn_type = dest->addr.name.name.type;
544 tport->conn_instance = dest->addr.name.name.instance;
547 /* Abort any pending connection attempts (very unlikely) */
553 if (dest->addrtype == TIPC_ADDR_NAME) {
554 if ((res = dest_name_check(dest, m)))
556 res = tipc_send2name(tport->ref,
557 &dest->addr.name.name,
558 dest->addr.name.domain,
562 else if (dest->addrtype == TIPC_ADDR_ID) {
563 res = tipc_send2port(tport->ref,
568 else if (dest->addrtype == TIPC_ADDR_MCAST) {
573 if ((res = dest_name_check(dest, m)))
575 res = tipc_multicast(tport->ref,
581 if (likely(res != -ELINKCONG)) {
582 if (needs_conn && (res >= 0)) {
583 sock->state = SS_CONNECTING;
587 if (m->msg_flags & MSG_DONTWAIT) {
592 res = wait_event_interruptible(*sk->sk_sleep,
606 * send_packet - send a connection-oriented message
607 * @iocb: if NULL, indicates that socket lock is already held
608 * @sock: socket structure
609 * @m: message to send
610 * @total_len: length of message
612 * Used for SOCK_SEQPACKET messages and SOCK_STREAM data.
614 * Returns the number of bytes sent on success, or errno otherwise
617 static int send_packet(struct kiocb *iocb, struct socket *sock,
618 struct msghdr *m, size_t total_len)
620 struct sock *sk = sock->sk;
621 struct tipc_port *tport = tipc_sk_port(sk);
622 struct sockaddr_tipc *dest = (struct sockaddr_tipc *)m->msg_name;
625 /* Handle implied connection establishment */
628 return send_msg(iocb, sock, m, total_len);
634 if (unlikely(sock->state != SS_CONNECTED)) {
635 if (sock->state == SS_DISCONNECTING)
642 res = tipc_send(tport->ref, m->msg_iovlen, m->msg_iov);
643 if (likely(res != -ELINKCONG)) {
646 if (m->msg_flags & MSG_DONTWAIT) {
651 res = wait_event_interruptible(*sk->sk_sleep,
652 (!tport->congested || !tport->connected));
664 * send_stream - send stream-oriented data
666 * @sock: socket structure
668 * @total_len: total length of data to be sent
670 * Used for SOCK_STREAM data.
672 * Returns the number of bytes sent on success (or partial success),
673 * or errno if no data sent
676 static int send_stream(struct kiocb *iocb, struct socket *sock,
677 struct msghdr *m, size_t total_len)
679 struct sock *sk = sock->sk;
680 struct tipc_port *tport = tipc_sk_port(sk);
681 struct msghdr my_msg;
683 struct iovec *curr_iov;
685 char __user *curr_start;
694 /* Handle special cases where there is no connection */
696 if (unlikely(sock->state != SS_CONNECTED)) {
697 if (sock->state == SS_UNCONNECTED) {
698 res = send_packet(NULL, sock, m, total_len);
700 } else if (sock->state == SS_DISCONNECTING) {
709 if (unlikely(m->msg_name)) {
715 * Send each iovec entry using one or more messages
717 * Note: This algorithm is good for the most likely case
718 * (i.e. one large iovec entry), but could be improved to pass sets
719 * of small iovec entries into send_packet().
722 curr_iov = m->msg_iov;
723 curr_iovlen = m->msg_iovlen;
724 my_msg.msg_iov = &my_iov;
725 my_msg.msg_iovlen = 1;
726 my_msg.msg_flags = m->msg_flags;
727 my_msg.msg_name = NULL;
730 hdr_size = msg_hdr_sz(&tport->phdr);
732 while (curr_iovlen--) {
733 curr_start = curr_iov->iov_base;
734 curr_left = curr_iov->iov_len;
737 bytes_to_send = tport->max_pkt - hdr_size;
738 if (bytes_to_send > TIPC_MAX_USER_MSG_SIZE)
739 bytes_to_send = TIPC_MAX_USER_MSG_SIZE;
740 if (curr_left < bytes_to_send)
741 bytes_to_send = curr_left;
742 my_iov.iov_base = curr_start;
743 my_iov.iov_len = bytes_to_send;
744 if ((res = send_packet(NULL, sock, &my_msg, 0)) < 0) {
749 curr_left -= bytes_to_send;
750 curr_start += bytes_to_send;
751 bytes_sent += bytes_to_send;
763 * auto_connect - complete connection setup to a remote port
764 * @sock: socket structure
765 * @msg: peer's response message
767 * Returns 0 on success, errno otherwise
770 static int auto_connect(struct socket *sock, struct tipc_msg *msg)
772 struct tipc_sock *tsock = tipc_sk(sock->sk);
774 if (msg_errcode(msg)) {
775 sock->state = SS_DISCONNECTING;
776 return -ECONNREFUSED;
779 tsock->peer_name.ref = msg_origport(msg);
780 tsock->peer_name.node = msg_orignode(msg);
781 tipc_connect2port(tsock->p->ref, &tsock->peer_name);
782 tipc_set_portimportance(tsock->p->ref, msg_importance(msg));
783 sock->state = SS_CONNECTED;
788 * set_orig_addr - capture sender's address for received message
789 * @m: descriptor for message info
790 * @msg: received message header
792 * Note: Address is not captured if not requested by receiver.
795 static void set_orig_addr(struct msghdr *m, struct tipc_msg *msg)
797 struct sockaddr_tipc *addr = (struct sockaddr_tipc *)m->msg_name;
800 addr->family = AF_TIPC;
801 addr->addrtype = TIPC_ADDR_ID;
802 addr->addr.id.ref = msg_origport(msg);
803 addr->addr.id.node = msg_orignode(msg);
804 addr->addr.name.domain = 0; /* could leave uninitialized */
805 addr->scope = 0; /* could leave uninitialized */
806 m->msg_namelen = sizeof(struct sockaddr_tipc);
811 * anc_data_recv - optionally capture ancillary data for received message
812 * @m: descriptor for message info
813 * @msg: received message header
814 * @tport: TIPC port associated with message
816 * Note: Ancillary data is not captured if not requested by receiver.
818 * Returns 0 if successful, otherwise errno
821 static int anc_data_recv(struct msghdr *m, struct tipc_msg *msg,
822 struct tipc_port *tport)
830 if (likely(m->msg_controllen == 0))
833 /* Optionally capture errored message object(s) */
835 err = msg ? msg_errcode(msg) : 0;
838 anc_data[1] = msg_data_sz(msg);
839 if ((res = put_cmsg(m, SOL_TIPC, TIPC_ERRINFO, 8, anc_data)))
842 (res = put_cmsg(m, SOL_TIPC, TIPC_RETDATA, anc_data[1],
847 /* Optionally capture message destination object */
849 dest_type = msg ? msg_type(msg) : TIPC_DIRECT_MSG;
853 anc_data[0] = msg_nametype(msg);
854 anc_data[1] = msg_namelower(msg);
855 anc_data[2] = msg_namelower(msg);
859 anc_data[0] = msg_nametype(msg);
860 anc_data[1] = msg_namelower(msg);
861 anc_data[2] = msg_nameupper(msg);
864 has_name = (tport->conn_type != 0);
865 anc_data[0] = tport->conn_type;
866 anc_data[1] = tport->conn_instance;
867 anc_data[2] = tport->conn_instance;
873 (res = put_cmsg(m, SOL_TIPC, TIPC_DESTNAME, 12, anc_data)))
880 * recv_msg - receive packet-oriented message
882 * @m: descriptor for message info
883 * @buf_len: total size of user buffer area
884 * @flags: receive flags
886 * Used for SOCK_DGRAM, SOCK_RDM, and SOCK_SEQPACKET messages.
887 * If the complete message doesn't fit in user area, truncate it.
889 * Returns size of returned message data, errno otherwise
892 static int recv_msg(struct kiocb *iocb, struct socket *sock,
893 struct msghdr *m, size_t buf_len, int flags)
895 struct sock *sk = sock->sk;
896 struct tipc_port *tport = tipc_sk_port(sk);
898 struct tipc_msg *msg;
903 /* Catch invalid receive requests */
905 if (m->msg_iovlen != 1)
906 return -EOPNOTSUPP; /* Don't do multiple iovec entries yet */
908 if (unlikely(!buf_len))
913 if (unlikely(sock->state == SS_UNCONNECTED)) {
920 /* Look for a message in receive queue; wait if necessary */
922 while (skb_queue_empty(&sk->sk_receive_queue)) {
923 if (sock->state == SS_DISCONNECTING) {
927 if (flags & MSG_DONTWAIT) {
932 res = wait_event_interruptible(*sk->sk_sleep,
933 (!skb_queue_empty(&sk->sk_receive_queue) ||
934 (sock->state == SS_DISCONNECTING)));
940 /* Look at first message in receive queue */
942 buf = skb_peek(&sk->sk_receive_queue);
944 sz = msg_data_sz(msg);
945 err = msg_errcode(msg);
947 /* Complete connection setup for an implied connect */
949 if (unlikely(sock->state == SS_CONNECTING)) {
950 res = auto_connect(sock, msg);
955 /* Discard an empty non-errored message & try again */
957 if ((!sz) && (!err)) {
958 advance_rx_queue(sk);
962 /* Capture sender's address (optional) */
964 set_orig_addr(m, msg);
966 /* Capture ancillary data (optional) */
968 res = anc_data_recv(m, msg, tport);
972 /* Capture message data (if valid) & compute return value (always) */
975 if (unlikely(buf_len < sz)) {
977 m->msg_flags |= MSG_TRUNC;
979 if (unlikely(copy_to_user(m->msg_iov->iov_base, msg_data(msg),
986 if ((sock->state == SS_READY) ||
987 ((err == TIPC_CONN_SHUTDOWN) || m->msg_control))
993 /* Consume received message (optional) */
995 if (likely(!(flags & MSG_PEEK))) {
996 if ((sock->state != SS_READY) &&
997 (++tport->conn_unacked >= TIPC_FLOW_CONTROL_WIN))
998 tipc_acknowledge(tport->ref, tport->conn_unacked);
999 advance_rx_queue(sk);
1007 * recv_stream - receive stream-oriented data
1009 * @m: descriptor for message info
1010 * @buf_len: total size of user buffer area
1011 * @flags: receive flags
1013 * Used for SOCK_STREAM messages only. If not enough data is available
1014 * will optionally wait for more; never truncates data.
1016 * Returns size of returned message data, errno otherwise
1019 static int recv_stream(struct kiocb *iocb, struct socket *sock,
1020 struct msghdr *m, size_t buf_len, int flags)
1022 struct sock *sk = sock->sk;
1023 struct tipc_port *tport = tipc_sk_port(sk);
1024 struct sk_buff *buf;
1025 struct tipc_msg *msg;
1030 char __user *crs = m->msg_iov->iov_base;
1031 unsigned char *buf_crs;
1035 /* Catch invalid receive attempts */
1037 if (m->msg_iovlen != 1)
1038 return -EOPNOTSUPP; /* Don't do multiple iovec entries yet */
1040 if (unlikely(!buf_len))
1045 if (unlikely((sock->state == SS_UNCONNECTED) ||
1046 (sock->state == SS_CONNECTING))) {
1053 /* Look for a message in receive queue; wait if necessary */
1055 while (skb_queue_empty(&sk->sk_receive_queue)) {
1056 if (sock->state == SS_DISCONNECTING) {
1060 if (flags & MSG_DONTWAIT) {
1065 res = wait_event_interruptible(*sk->sk_sleep,
1066 (!skb_queue_empty(&sk->sk_receive_queue) ||
1067 (sock->state == SS_DISCONNECTING)));
1073 /* Look at first message in receive queue */
1075 buf = skb_peek(&sk->sk_receive_queue);
1077 sz = msg_data_sz(msg);
1078 err = msg_errcode(msg);
1080 /* Discard an empty non-errored message & try again */
1082 if ((!sz) && (!err)) {
1083 advance_rx_queue(sk);
1087 /* Optionally capture sender's address & ancillary data of first msg */
1089 if (sz_copied == 0) {
1090 set_orig_addr(m, msg);
1091 res = anc_data_recv(m, msg, tport);
1096 /* Capture message data (if valid) & compute return value (always) */
1099 buf_crs = (unsigned char *)(TIPC_SKB_CB(buf)->handle);
1100 sz = (unsigned char *)msg + msg_size(msg) - buf_crs;
1102 needed = (buf_len - sz_copied);
1103 sz_to_copy = (sz <= needed) ? sz : needed;
1104 if (unlikely(copy_to_user(crs, buf_crs, sz_to_copy))) {
1108 sz_copied += sz_to_copy;
1110 if (sz_to_copy < sz) {
1111 if (!(flags & MSG_PEEK))
1112 TIPC_SKB_CB(buf)->handle = buf_crs + sz_to_copy;
1119 goto exit; /* can't add error msg to valid data */
1121 if ((err == TIPC_CONN_SHUTDOWN) || m->msg_control)
1127 /* Consume received message (optional) */
1129 if (likely(!(flags & MSG_PEEK))) {
1130 if (unlikely(++tport->conn_unacked >= TIPC_FLOW_CONTROL_WIN))
1131 tipc_acknowledge(tport->ref, tport->conn_unacked);
1132 advance_rx_queue(sk);
1135 /* Loop around if more data is required */
1137 if ((sz_copied < buf_len) /* didn't get all requested data */
1138 && (!skb_queue_empty(&sk->sk_receive_queue) ||
1139 (flags & MSG_WAITALL))
1140 /* ... and more is ready or required */
1141 && (!(flags & MSG_PEEK)) /* ... and aren't just peeking at data */
1142 && (!err) /* ... and haven't reached a FIN */
1148 return sz_copied ? sz_copied : res;
1152 * rx_queue_full - determine if receive queue can accept another message
1153 * @msg: message to be added to queue
1154 * @queue_size: current size of queue
1155 * @base: nominal maximum size of queue
1157 * Returns 1 if queue is unable to accept message, 0 otherwise
1160 static int rx_queue_full(struct tipc_msg *msg, u32 queue_size, u32 base)
1163 u32 imp = msg_importance(msg);
1165 if (imp == TIPC_LOW_IMPORTANCE)
1167 else if (imp == TIPC_MEDIUM_IMPORTANCE)
1168 threshold = base * 2;
1169 else if (imp == TIPC_HIGH_IMPORTANCE)
1170 threshold = base * 100;
1174 if (msg_connected(msg))
1177 return (queue_size >= threshold);
1181 * filter_rcv - validate incoming message
1185 * Enqueues message on receive queue if acceptable; optionally handles
1186 * disconnect indication for a connected socket.
1188 * Called with socket lock already taken; port lock may also be taken.
1190 * Returns TIPC error status code (TIPC_OK if message is not to be rejected)
1193 static u32 filter_rcv(struct sock *sk, struct sk_buff *buf)
1195 struct socket *sock = sk->sk_socket;
1196 struct tipc_msg *msg = buf_msg(buf);
1199 /* Reject message if it is wrong sort of message for socket */
1202 * WOULD IT BE BETTER TO JUST DISCARD THESE MESSAGES INSTEAD?
1203 * "NO PORT" ISN'T REALLY THE RIGHT ERROR CODE, AND THERE MAY
1204 * BE SECURITY IMPLICATIONS INHERENT IN REJECTING INVALID TRAFFIC
1207 if (sock->state == SS_READY) {
1208 if (msg_connected(msg)) {
1209 msg_dbg(msg, "dispatch filter 1\n");
1210 return TIPC_ERR_NO_PORT;
1213 if (msg_mcast(msg)) {
1214 msg_dbg(msg, "dispatch filter 2\n");
1215 return TIPC_ERR_NO_PORT;
1217 if (sock->state == SS_CONNECTED) {
1218 if (!msg_connected(msg)) {
1219 msg_dbg(msg, "dispatch filter 3\n");
1220 return TIPC_ERR_NO_PORT;
1223 else if (sock->state == SS_CONNECTING) {
1224 if (!msg_connected(msg) && (msg_errcode(msg) == 0)) {
1225 msg_dbg(msg, "dispatch filter 4\n");
1226 return TIPC_ERR_NO_PORT;
1229 else if (sock->state == SS_LISTENING) {
1230 if (msg_connected(msg) || msg_errcode(msg)) {
1231 msg_dbg(msg, "dispatch filter 5\n");
1232 return TIPC_ERR_NO_PORT;
1235 else if (sock->state == SS_DISCONNECTING) {
1236 msg_dbg(msg, "dispatch filter 6\n");
1237 return TIPC_ERR_NO_PORT;
1239 else /* (sock->state == SS_UNCONNECTED) */ {
1240 if (msg_connected(msg) || msg_errcode(msg)) {
1241 msg_dbg(msg, "dispatch filter 7\n");
1242 return TIPC_ERR_NO_PORT;
1247 /* Reject message if there isn't room to queue it */
1249 recv_q_len = (u32)atomic_read(&tipc_queue_size);
1250 if (unlikely(recv_q_len >= OVERLOAD_LIMIT_BASE)) {
1251 if (rx_queue_full(msg, recv_q_len, OVERLOAD_LIMIT_BASE))
1252 return TIPC_ERR_OVERLOAD;
1254 recv_q_len = skb_queue_len(&sk->sk_receive_queue);
1255 if (unlikely(recv_q_len >= (OVERLOAD_LIMIT_BASE / 2))) {
1256 if (rx_queue_full(msg, recv_q_len, OVERLOAD_LIMIT_BASE / 2))
1257 return TIPC_ERR_OVERLOAD;
1260 /* Enqueue message (finally!) */
1262 msg_dbg(msg, "<DISP<: ");
1263 TIPC_SKB_CB(buf)->handle = msg_data(msg);
1264 atomic_inc(&tipc_queue_size);
1265 __skb_queue_tail(&sk->sk_receive_queue, buf);
1267 /* Initiate connection termination for an incoming 'FIN' */
1269 if (unlikely(msg_errcode(msg) && (sock->state == SS_CONNECTED))) {
1270 sock->state = SS_DISCONNECTING;
1271 tipc_disconnect_port(tipc_sk_port(sk));
1274 if (waitqueue_active(sk->sk_sleep))
1275 wake_up_interruptible(sk->sk_sleep);
1280 * backlog_rcv - handle incoming message from backlog queue
1284 * Caller must hold socket lock, but not port lock.
1289 static int backlog_rcv(struct sock *sk, struct sk_buff *buf)
1293 res = filter_rcv(sk, buf);
1295 tipc_reject_msg(buf, res);
1300 * dispatch - handle incoming message
1301 * @tport: TIPC port that received message
1304 * Called with port lock already taken.
1306 * Returns TIPC error status code (TIPC_OK if message is not to be rejected)
1309 static u32 dispatch(struct tipc_port *tport, struct sk_buff *buf)
1311 struct sock *sk = (struct sock *)tport->usr_handle;
1315 * Process message if socket is unlocked; otherwise add to backlog queue
1317 * This code is based on sk_receive_skb(), but must be distinct from it
1318 * since a TIPC-specific filter/reject mechanism is utilized
1322 if (!sock_owned_by_user(sk)) {
1323 res = filter_rcv(sk, buf);
1325 sk_add_backlog(sk, buf);
1334 * wakeupdispatch - wake up port after congestion
1335 * @tport: port to wakeup
1337 * Called with port lock already taken.
1340 static void wakeupdispatch(struct tipc_port *tport)
1342 struct sock *sk = (struct sock *)tport->usr_handle;
1344 if (waitqueue_active(sk->sk_sleep))
1345 wake_up_interruptible(sk->sk_sleep);
1349 * connect - establish a connection to another TIPC port
1350 * @sock: socket structure
1351 * @dest: socket address for destination port
1352 * @destlen: size of socket address data structure
1353 * @flags: file-related flags associated with socket
1355 * Returns 0 on success, errno otherwise
1358 static int connect(struct socket *sock, struct sockaddr *dest, int destlen,
1361 struct sock *sk = sock->sk;
1362 struct sockaddr_tipc *dst = (struct sockaddr_tipc *)dest;
1363 struct msghdr m = {NULL,};
1364 struct sk_buff *buf;
1365 struct tipc_msg *msg;
1370 /* For now, TIPC does not allow use of connect() with DGRAM/RDM types */
1372 if (sock->state == SS_READY) {
1377 /* For now, TIPC does not support the non-blocking form of connect() */
1379 if (flags & O_NONBLOCK) {
1384 /* Issue Posix-compliant error code if socket is in the wrong state */
1386 if (sock->state == SS_LISTENING) {
1390 if (sock->state == SS_CONNECTING) {
1394 if (sock->state != SS_UNCONNECTED) {
1400 * Reject connection attempt using multicast address
1402 * Note: send_msg() validates the rest of the address fields,
1403 * so there's no need to do it here
1406 if (dst->addrtype == TIPC_ADDR_MCAST) {
1411 /* Reject any messages already in receive queue (very unlikely) */
1413 reject_rx_queue(sk);
1415 /* Send a 'SYN-' to destination */
1418 m.msg_namelen = destlen;
1419 res = send_msg(NULL, sock, &m, 0);
1424 /* Wait until an 'ACK' or 'RST' arrives, or a timeout occurs */
1427 res = wait_event_interruptible_timeout(*sk->sk_sleep,
1428 (!skb_queue_empty(&sk->sk_receive_queue) ||
1429 (sock->state != SS_CONNECTING)),
1434 buf = skb_peek(&sk->sk_receive_queue);
1437 res = auto_connect(sock, msg);
1439 if (!msg_data_sz(msg))
1440 advance_rx_queue(sk);
1443 if (sock->state == SS_CONNECTED) {
1446 res = -ECONNREFUSED;
1453 ; /* leave "res" unchanged */
1454 sock->state = SS_DISCONNECTING;
1463 * listen - allow socket to listen for incoming connections
1464 * @sock: socket structure
1467 * Returns 0 on success, errno otherwise
1470 static int listen(struct socket *sock, int len)
1472 struct sock *sk = sock->sk;
1477 if (sock->state == SS_READY)
1479 else if (sock->state != SS_UNCONNECTED)
1482 sock->state = SS_LISTENING;
1491 * accept - wait for connection request
1492 * @sock: listening socket
1493 * @newsock: new socket that is to be connected
1494 * @flags: file-related flags associated with socket
1496 * Returns 0 on success, errno otherwise
1499 static int accept(struct socket *sock, struct socket *new_sock, int flags)
1501 struct sock *sk = sock->sk;
1502 struct sk_buff *buf;
1507 if (sock->state == SS_READY) {
1511 if (sock->state != SS_LISTENING) {
1516 while (skb_queue_empty(&sk->sk_receive_queue)) {
1517 if (flags & O_NONBLOCK) {
1522 res = wait_event_interruptible(*sk->sk_sleep,
1523 (!skb_queue_empty(&sk->sk_receive_queue)));
1529 buf = skb_peek(&sk->sk_receive_queue);
1531 res = tipc_create(sock_net(sock->sk), new_sock, 0);
1533 struct sock *new_sk = new_sock->sk;
1534 struct tipc_sock *new_tsock = tipc_sk(new_sk);
1535 struct tipc_port *new_tport = new_tsock->p;
1536 u32 new_ref = new_tport->ref;
1537 struct tipc_msg *msg = buf_msg(buf);
1542 * Reject any stray messages received by new socket
1543 * before the socket lock was taken (very, very unlikely)
1546 reject_rx_queue(new_sk);
1548 /* Connect new socket to it's peer */
1550 new_tsock->peer_name.ref = msg_origport(msg);
1551 new_tsock->peer_name.node = msg_orignode(msg);
1552 tipc_connect2port(new_ref, &new_tsock->peer_name);
1553 new_sock->state = SS_CONNECTED;
1555 tipc_set_portimportance(new_ref, msg_importance(msg));
1556 if (msg_named(msg)) {
1557 new_tport->conn_type = msg_nametype(msg);
1558 new_tport->conn_instance = msg_nameinst(msg);
1562 * Respond to 'SYN-' by discarding it & returning 'ACK'-.
1563 * Respond to 'SYN+' by queuing it on new socket.
1566 msg_dbg(msg,"<ACC<: ");
1567 if (!msg_data_sz(msg)) {
1568 struct msghdr m = {NULL,};
1570 advance_rx_queue(sk);
1571 send_packet(NULL, new_sock, &m, 0);
1573 __skb_dequeue(&sk->sk_receive_queue);
1574 __skb_queue_head(&new_sk->sk_receive_queue, buf);
1576 release_sock(new_sk);
1584 * shutdown - shutdown socket connection
1585 * @sock: socket structure
1586 * @how: direction to close (must be SHUT_RDWR)
1588 * Terminates connection (if necessary), then purges socket's receive queue.
1590 * Returns 0 on success, errno otherwise
1593 static int shutdown(struct socket *sock, int how)
1595 struct sock *sk = sock->sk;
1596 struct tipc_port *tport = tipc_sk_port(sk);
1597 struct sk_buff *buf;
1600 if (how != SHUT_RDWR)
1605 switch (sock->state) {
1609 /* Disconnect and send a 'FIN+' or 'FIN-' message to peer */
1611 buf = __skb_dequeue(&sk->sk_receive_queue);
1613 atomic_dec(&tipc_queue_size);
1614 if (TIPC_SKB_CB(buf)->handle != msg_data(buf_msg(buf))) {
1618 tipc_disconnect(tport->ref);
1619 tipc_reject_msg(buf, TIPC_CONN_SHUTDOWN);
1621 tipc_shutdown(tport->ref);
1624 sock->state = SS_DISCONNECTING;
1628 case SS_DISCONNECTING:
1630 /* Discard any unreceived messages; wake up sleeping tasks */
1632 discard_rx_queue(sk);
1633 if (waitqueue_active(sk->sk_sleep))
1634 wake_up_interruptible(sk->sk_sleep);
1647 * setsockopt - set socket option
1648 * @sock: socket structure
1649 * @lvl: option level
1650 * @opt: option identifier
1651 * @ov: pointer to new option value
1652 * @ol: length of option value
1654 * For stream sockets only, accepts and ignores all IPPROTO_TCP options
1655 * (to ease compatibility).
1657 * Returns 0 on success, errno otherwise
1660 static int setsockopt(struct socket *sock,
1661 int lvl, int opt, char __user *ov, 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 if ((res = get_user(value, (u32 __user *)ov)))
1680 case TIPC_IMPORTANCE:
1681 res = tipc_set_portimportance(tport->ref, value);
1683 case TIPC_SRC_DROPPABLE:
1684 if (sock->type != SOCK_STREAM)
1685 res = tipc_set_portunreliable(tport->ref, value);
1689 case TIPC_DEST_DROPPABLE:
1690 res = tipc_set_portunreturnable(tport->ref, value);
1692 case TIPC_CONN_TIMEOUT:
1693 sk->sk_rcvtimeo = msecs_to_jiffies(value);
1694 /* no need to set "res", since already 0 at this point */
1706 * getsockopt - get socket option
1707 * @sock: socket structure
1708 * @lvl: option level
1709 * @opt: option identifier
1710 * @ov: receptacle for option value
1711 * @ol: receptacle for length of option value
1713 * For stream sockets only, returns 0 length result for all IPPROTO_TCP options
1714 * (to ease compatibility).
1716 * 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 if ((res = get_user(len, ol)))
1738 case TIPC_IMPORTANCE:
1739 res = tipc_portimportance(tport->ref, &value);
1741 case TIPC_SRC_DROPPABLE:
1742 res = tipc_portunreliable(tport->ref, &value);
1744 case TIPC_DEST_DROPPABLE:
1745 res = tipc_portunreturnable(tport->ref, &value);
1747 case TIPC_CONN_TIMEOUT:
1748 value = jiffies_to_msecs(sk->sk_rcvtimeo);
1749 /* no need to set "res", since already 0 at this point */
1760 else if (len < sizeof(value)) {
1763 else if (copy_to_user(ov, &value, sizeof(value))) {
1767 res = put_user(sizeof(value), ol);
1774 * Protocol switches for the various types of TIPC sockets
1777 static const struct proto_ops msg_ops = {
1778 .owner = THIS_MODULE,
1783 .socketpair = sock_no_socketpair,
1785 .getname = get_name,
1787 .ioctl = sock_no_ioctl,
1789 .shutdown = shutdown,
1790 .setsockopt = setsockopt,
1791 .getsockopt = getsockopt,
1792 .sendmsg = send_msg,
1793 .recvmsg = recv_msg,
1794 .mmap = sock_no_mmap,
1795 .sendpage = sock_no_sendpage
1798 static const struct proto_ops packet_ops = {
1799 .owner = THIS_MODULE,
1804 .socketpair = sock_no_socketpair,
1806 .getname = get_name,
1808 .ioctl = sock_no_ioctl,
1810 .shutdown = shutdown,
1811 .setsockopt = setsockopt,
1812 .getsockopt = getsockopt,
1813 .sendmsg = send_packet,
1814 .recvmsg = recv_msg,
1815 .mmap = sock_no_mmap,
1816 .sendpage = sock_no_sendpage
1819 static const struct proto_ops stream_ops = {
1820 .owner = THIS_MODULE,
1825 .socketpair = sock_no_socketpair,
1827 .getname = get_name,
1829 .ioctl = sock_no_ioctl,
1831 .shutdown = shutdown,
1832 .setsockopt = setsockopt,
1833 .getsockopt = getsockopt,
1834 .sendmsg = send_stream,
1835 .recvmsg = recv_stream,
1836 .mmap = sock_no_mmap,
1837 .sendpage = sock_no_sendpage
1840 static const struct net_proto_family tipc_family_ops = {
1841 .owner = THIS_MODULE,
1843 .create = tipc_create
1846 static struct proto tipc_proto = {
1848 .owner = THIS_MODULE,
1849 .obj_size = sizeof(struct tipc_sock)
1853 * tipc_socket_init - initialize TIPC socket interface
1855 * Returns 0 on success, errno otherwise
1857 int tipc_socket_init(void)
1861 res = proto_register(&tipc_proto, 1);
1863 err("Failed to register TIPC protocol type\n");
1867 res = sock_register(&tipc_family_ops);
1869 err("Failed to register TIPC socket type\n");
1870 proto_unregister(&tipc_proto);
1874 sockets_enabled = 1;
1880 * tipc_socket_stop - stop TIPC socket interface
1883 void tipc_socket_stop(void)
1885 if (!sockets_enabled)
1888 sockets_enabled = 0;
1889 sock_unregister(tipc_family_ops.family);
1890 proto_unregister(&tipc_proto);