2 * net/tipc/socket.c: TIPC socket API
4 * Copyright (c) 2001-2007, Ericsson AB
5 * Copyright (c) 2004-2007, 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 */
68 #define tipc_sk(sk) ((struct tipc_sock *)(sk))
69 #define tipc_sk_port(sk) ((struct tipc_port *)(tipc_sk(sk)->p))
71 static int backlog_rcv(struct sock *sk, struct sk_buff *skb);
72 static u32 dispatch(struct tipc_port *tport, struct sk_buff *buf);
73 static void wakeupdispatch(struct tipc_port *tport);
75 static const struct proto_ops packet_ops;
76 static const struct proto_ops stream_ops;
77 static const struct proto_ops msg_ops;
79 static struct proto tipc_proto;
81 static int sockets_enabled = 0;
83 static atomic_t tipc_queue_size = ATOMIC_INIT(0);
86 * Revised TIPC socket locking policy:
88 * Most socket operations take the standard socket lock when they start
89 * and hold it until they finish (or until they need to sleep). Acquiring
90 * this lock grants the owner exclusive access to the fields of the socket
91 * data structures, with the exception of the backlog queue. A few socket
92 * operations can be done without taking the socket lock because they only
93 * read socket information that never changes during the life of the socket.
95 * Socket operations may acquire the lock for the associated TIPC port if they
96 * need to perform an operation on the port. If any routine needs to acquire
97 * both the socket lock and the port lock it must take the socket lock first
98 * to avoid the risk of deadlock.
100 * The dispatcher handling incoming messages cannot grab the socket lock in
101 * the standard fashion, since invoked it runs at the BH level and cannot block.
102 * Instead, it checks to see if the socket lock is currently owned by someone,
103 * and either handles the message itself or adds it to the socket's backlog
104 * queue; in the latter case the queued message is processed once the process
105 * owning the socket lock releases it.
107 * NOTE: Releasing the socket lock while an operation is sleeping overcomes
108 * the problem of a blocked socket operation preventing any other operations
109 * from occurring. However, applications must be careful if they have
110 * multiple threads trying to send (or receive) on the same socket, as these
111 * operations might interfere with each other. For example, doing a connect
112 * and a receive at the same time might allow the receive to consume the
113 * ACK message meant for the connect. While additional work could be done
114 * to try and overcome this, it doesn't seem to be worthwhile at the present.
116 * NOTE: Releasing the socket lock while an operation is sleeping also ensures
117 * that another operation that must be performed in a non-blocking manner is
118 * not delayed for very long because the lock has already been taken.
120 * NOTE: This code assumes that certain fields of a port/socket pair are
121 * constant over its lifetime; such fields can be examined without taking
122 * the socket lock and/or port lock, and do not need to be re-read even
123 * after resuming processing after waiting. These fields include:
125 * - pointer to socket sk structure (aka tipc_sock structure)
126 * - pointer to port structure
131 * advance_rx_queue - discard first buffer in socket receive queue
133 * Caller must hold socket lock
136 static void advance_rx_queue(struct sock *sk)
138 buf_discard(__skb_dequeue(&sk->sk_receive_queue));
139 atomic_dec(&tipc_queue_size);
143 * discard_rx_queue - discard all buffers in socket receive queue
145 * Caller must hold socket lock
148 static void discard_rx_queue(struct sock *sk)
152 while ((buf = __skb_dequeue(&sk->sk_receive_queue))) {
153 atomic_dec(&tipc_queue_size);
159 * reject_rx_queue - reject all buffers in socket receive queue
161 * Caller must hold socket lock
164 static void reject_rx_queue(struct sock *sk)
168 while ((buf = __skb_dequeue(&sk->sk_receive_queue))) {
169 tipc_reject_msg(buf, TIPC_ERR_NO_PORT);
170 atomic_dec(&tipc_queue_size);
175 * tipc_create - create a TIPC socket
176 * @net: network namespace (must be default network)
177 * @sock: pre-allocated socket structure
178 * @protocol: protocol indicator (must be 0)
180 * This routine creates additional data structures used by the TIPC socket,
181 * initializes them, and links them together.
183 * Returns 0 on success, errno otherwise
186 static int tipc_create(struct net *net, struct socket *sock, int protocol)
188 const struct proto_ops *ops;
191 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 portref = tipc_createport_raw(sk, &dispatch, &wakeupdispatch,
229 TIPC_LOW_IMPORTANCE, &tp_ptr);
230 if (unlikely(portref == 0)) {
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 = tipc_get_port(portref);
245 spin_unlock_bh(tp_ptr->lock);
247 if (sock->state == SS_READY) {
248 tipc_set_portunreturnable(portref, 1);
249 if (sock->type == SOCK_DGRAM)
250 tipc_set_portunreliable(portref, 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 to obtain socket name, 1 to obtain peer socket name
383 * Returns 0 on success, errno otherwise
385 * NOTE: This routine doesn't need to take the socket lock since it doesn't
386 * access any non-constant socket information.
389 static int get_name(struct socket *sock, struct sockaddr *uaddr,
390 int *uaddr_len, int peer)
392 struct sockaddr_tipc *addr = (struct sockaddr_tipc *)uaddr;
393 u32 portref = tipc_sk_port(sock->sk)->ref;
397 res = tipc_peer(portref, &addr->addr.id);
401 tipc_ownidentity(portref, &addr->addr.id);
404 *uaddr_len = sizeof(*addr);
405 addr->addrtype = TIPC_ADDR_ID;
406 addr->family = AF_TIPC;
408 addr->addr.name.domain = 0;
414 * poll - read and possibly block on pollmask
415 * @file: file structure associated with the socket
416 * @sock: socket for which to calculate the poll bits
419 * Returns pollmask value
422 * It appears that the usual socket locking mechanisms are not useful here
423 * since the pollmask info is potentially out-of-date the moment this routine
424 * exits. TCP and other protocols seem to rely on higher level poll routines
425 * to handle any preventable race conditions, so TIPC will do the same ...
427 * TIPC sets the returned events as follows:
428 * a) POLLRDNORM and POLLIN are set if the socket's receive queue is non-empty
429 * or if a connection-oriented socket is does not have an active connection
430 * (i.e. a read operation will not block).
431 * b) POLLOUT is set except when a socket's connection has been terminated
432 * (i.e. a write operation will not block).
433 * c) POLLHUP is set when a socket's connection has been terminated.
435 * IMPORTANT: The fact that a read or write operation will not block does NOT
436 * imply that the operation will succeed!
439 static unsigned int poll(struct file *file, struct socket *sock,
442 struct sock *sk = sock->sk;
445 poll_wait(file, sk->sk_sleep, wait);
447 if (!skb_queue_empty(&sk->sk_receive_queue) ||
448 (sock->state == SS_UNCONNECTED) ||
449 (sock->state == SS_DISCONNECTING))
450 mask = (POLLRDNORM | POLLIN);
454 if (sock->state == SS_DISCONNECTING)
463 * dest_name_check - verify user is permitted to send to specified port name
464 * @dest: destination address
465 * @m: descriptor for message to be sent
467 * Prevents restricted configuration commands from being issued by
468 * unauthorized users.
470 * Returns 0 if permission is granted, otherwise errno
473 static int dest_name_check(struct sockaddr_tipc *dest, struct msghdr *m)
475 struct tipc_cfg_msg_hdr hdr;
477 if (likely(dest->addr.name.name.type >= TIPC_RESERVED_TYPES))
479 if (likely(dest->addr.name.name.type == TIPC_TOP_SRV))
481 if (likely(dest->addr.name.name.type != TIPC_CFG_SRV))
484 if (copy_from_user(&hdr, m->msg_iov[0].iov_base, sizeof(hdr)))
486 if ((ntohs(hdr.tcm_type) & 0xC000) && (!capable(CAP_NET_ADMIN)))
493 * send_msg - send message in connectionless manner
494 * @iocb: if NULL, indicates that socket lock is already held
495 * @sock: socket structure
496 * @m: message to send
497 * @total_len: length of message
499 * Message must have an destination specified explicitly.
500 * Used for SOCK_RDM and SOCK_DGRAM messages,
501 * and for 'SYN' messages on SOCK_SEQPACKET and SOCK_STREAM connections.
502 * (Note: 'SYN+' is prohibited on SOCK_STREAM.)
504 * Returns the number of bytes sent on success, or errno otherwise
507 static int send_msg(struct kiocb *iocb, struct socket *sock,
508 struct msghdr *m, size_t total_len)
510 struct sock *sk = sock->sk;
511 struct tipc_port *tport = tipc_sk_port(sk);
512 struct sockaddr_tipc *dest = (struct sockaddr_tipc *)m->msg_name;
517 return -EDESTADDRREQ;
518 if (unlikely((m->msg_namelen < sizeof(*dest)) ||
519 (dest->family != AF_TIPC)))
525 needs_conn = (sock->state != SS_READY);
526 if (unlikely(needs_conn)) {
527 if (sock->state == SS_LISTENING) {
531 if (sock->state != SS_UNCONNECTED) {
535 if ((tport->published) ||
536 ((sock->type == SOCK_STREAM) && (total_len != 0))) {
540 if (dest->addrtype == TIPC_ADDR_NAME) {
541 tport->conn_type = dest->addr.name.name.type;
542 tport->conn_instance = dest->addr.name.name.instance;
545 /* Abort any pending connection attempts (very unlikely) */
551 if (dest->addrtype == TIPC_ADDR_NAME) {
552 if ((res = dest_name_check(dest, m)))
554 res = tipc_send2name(tport->ref,
555 &dest->addr.name.name,
556 dest->addr.name.domain,
560 else if (dest->addrtype == TIPC_ADDR_ID) {
561 res = tipc_send2port(tport->ref,
566 else if (dest->addrtype == TIPC_ADDR_MCAST) {
571 if ((res = dest_name_check(dest, m)))
573 res = tipc_multicast(tport->ref,
579 if (likely(res != -ELINKCONG)) {
580 if (needs_conn && (res >= 0)) {
581 sock->state = SS_CONNECTING;
585 if (m->msg_flags & MSG_DONTWAIT) {
590 res = wait_event_interruptible(*sk->sk_sleep,
604 * send_packet - send a connection-oriented message
605 * @iocb: if NULL, indicates that socket lock is already held
606 * @sock: socket structure
607 * @m: message to send
608 * @total_len: length of message
610 * Used for SOCK_SEQPACKET messages and SOCK_STREAM data.
612 * Returns the number of bytes sent on success, or errno otherwise
615 static int send_packet(struct kiocb *iocb, struct socket *sock,
616 struct msghdr *m, size_t total_len)
618 struct sock *sk = sock->sk;
619 struct tipc_port *tport = tipc_sk_port(sk);
620 struct sockaddr_tipc *dest = (struct sockaddr_tipc *)m->msg_name;
623 /* Handle implied connection establishment */
626 return send_msg(iocb, sock, m, total_len);
632 if (unlikely(sock->state != SS_CONNECTED)) {
633 if (sock->state == SS_DISCONNECTING)
640 res = tipc_send(tport->ref, m->msg_iovlen, m->msg_iov);
641 if (likely(res != -ELINKCONG)) {
644 if (m->msg_flags & MSG_DONTWAIT) {
649 res = wait_event_interruptible(*sk->sk_sleep,
650 (!tport->congested || !tport->connected));
662 * send_stream - send stream-oriented data
664 * @sock: socket structure
666 * @total_len: total length of data to be sent
668 * Used for SOCK_STREAM data.
670 * Returns the number of bytes sent on success (or partial success),
671 * or errno if no data sent
674 static int send_stream(struct kiocb *iocb, struct socket *sock,
675 struct msghdr *m, size_t total_len)
677 struct sock *sk = sock->sk;
678 struct tipc_port *tport = tipc_sk_port(sk);
679 struct msghdr my_msg;
681 struct iovec *curr_iov;
683 char __user *curr_start;
692 /* Handle special cases where there is no connection */
694 if (unlikely(sock->state != SS_CONNECTED)) {
695 if (sock->state == SS_UNCONNECTED) {
696 res = send_packet(NULL, sock, m, total_len);
698 } else if (sock->state == SS_DISCONNECTING) {
707 if (unlikely(m->msg_name)) {
713 * Send each iovec entry using one or more messages
715 * Note: This algorithm is good for the most likely case
716 * (i.e. one large iovec entry), but could be improved to pass sets
717 * of small iovec entries into send_packet().
720 curr_iov = m->msg_iov;
721 curr_iovlen = m->msg_iovlen;
722 my_msg.msg_iov = &my_iov;
723 my_msg.msg_iovlen = 1;
724 my_msg.msg_flags = m->msg_flags;
725 my_msg.msg_name = NULL;
728 hdr_size = msg_hdr_sz(&tport->phdr);
730 while (curr_iovlen--) {
731 curr_start = curr_iov->iov_base;
732 curr_left = curr_iov->iov_len;
735 bytes_to_send = tport->max_pkt - hdr_size;
736 if (bytes_to_send > TIPC_MAX_USER_MSG_SIZE)
737 bytes_to_send = TIPC_MAX_USER_MSG_SIZE;
738 if (curr_left < bytes_to_send)
739 bytes_to_send = curr_left;
740 my_iov.iov_base = curr_start;
741 my_iov.iov_len = bytes_to_send;
742 if ((res = send_packet(NULL, sock, &my_msg, 0)) < 0) {
747 curr_left -= bytes_to_send;
748 curr_start += bytes_to_send;
749 bytes_sent += bytes_to_send;
761 * auto_connect - complete connection setup to a remote port
762 * @sock: socket structure
763 * @msg: peer's response message
765 * Returns 0 on success, errno otherwise
768 static int auto_connect(struct socket *sock, struct tipc_msg *msg)
770 struct tipc_port *tport = tipc_sk_port(sock->sk);
771 struct tipc_portid peer;
773 if (msg_errcode(msg)) {
774 sock->state = SS_DISCONNECTING;
775 return -ECONNREFUSED;
778 peer.ref = msg_origport(msg);
779 peer.node = msg_orignode(msg);
780 tipc_connect2port(tport->ref, &peer);
781 tipc_set_portimportance(tport->ref, msg_importance(msg));
782 sock->state = SS_CONNECTED;
787 * set_orig_addr - capture sender's address for received message
788 * @m: descriptor for message info
789 * @msg: received message header
791 * Note: Address is not captured if not requested by receiver.
794 static void set_orig_addr(struct msghdr *m, struct tipc_msg *msg)
796 struct sockaddr_tipc *addr = (struct sockaddr_tipc *)m->msg_name;
799 addr->family = AF_TIPC;
800 addr->addrtype = TIPC_ADDR_ID;
801 addr->addr.id.ref = msg_origport(msg);
802 addr->addr.id.node = msg_orignode(msg);
803 addr->addr.name.domain = 0; /* could leave uninitialized */
804 addr->scope = 0; /* could leave uninitialized */
805 m->msg_namelen = sizeof(struct sockaddr_tipc);
810 * anc_data_recv - optionally capture ancillary data for received message
811 * @m: descriptor for message info
812 * @msg: received message header
813 * @tport: TIPC port associated with message
815 * Note: Ancillary data is not captured if not requested by receiver.
817 * Returns 0 if successful, otherwise errno
820 static int anc_data_recv(struct msghdr *m, struct tipc_msg *msg,
821 struct tipc_port *tport)
829 if (likely(m->msg_controllen == 0))
832 /* Optionally capture errored message object(s) */
834 err = msg ? msg_errcode(msg) : 0;
837 anc_data[1] = msg_data_sz(msg);
838 if ((res = put_cmsg(m, SOL_TIPC, TIPC_ERRINFO, 8, anc_data)))
841 (res = put_cmsg(m, SOL_TIPC, TIPC_RETDATA, anc_data[1],
846 /* Optionally capture message destination object */
848 dest_type = msg ? msg_type(msg) : TIPC_DIRECT_MSG;
852 anc_data[0] = msg_nametype(msg);
853 anc_data[1] = msg_namelower(msg);
854 anc_data[2] = msg_namelower(msg);
858 anc_data[0] = msg_nametype(msg);
859 anc_data[1] = msg_namelower(msg);
860 anc_data[2] = msg_nameupper(msg);
863 has_name = (tport->conn_type != 0);
864 anc_data[0] = tport->conn_type;
865 anc_data[1] = tport->conn_instance;
866 anc_data[2] = tport->conn_instance;
872 (res = put_cmsg(m, SOL_TIPC, TIPC_DESTNAME, 12, anc_data)))
879 * recv_msg - receive packet-oriented message
881 * @m: descriptor for message info
882 * @buf_len: total size of user buffer area
883 * @flags: receive flags
885 * Used for SOCK_DGRAM, SOCK_RDM, and SOCK_SEQPACKET messages.
886 * If the complete message doesn't fit in user area, truncate it.
888 * Returns size of returned message data, errno otherwise
891 static int recv_msg(struct kiocb *iocb, struct socket *sock,
892 struct msghdr *m, size_t buf_len, int flags)
894 struct sock *sk = sock->sk;
895 struct tipc_port *tport = tipc_sk_port(sk);
897 struct tipc_msg *msg;
902 /* Catch invalid receive requests */
904 if (m->msg_iovlen != 1)
905 return -EOPNOTSUPP; /* Don't do multiple iovec entries yet */
907 if (unlikely(!buf_len))
912 if (unlikely(sock->state == SS_UNCONNECTED)) {
919 /* Look for a message in receive queue; wait if necessary */
921 while (skb_queue_empty(&sk->sk_receive_queue)) {
922 if (sock->state == SS_DISCONNECTING) {
926 if (flags & MSG_DONTWAIT) {
931 res = wait_event_interruptible(*sk->sk_sleep,
932 (!skb_queue_empty(&sk->sk_receive_queue) ||
933 (sock->state == SS_DISCONNECTING)));
939 /* Look at first message in receive queue */
941 buf = skb_peek(&sk->sk_receive_queue);
943 sz = msg_data_sz(msg);
944 err = msg_errcode(msg);
946 /* Complete connection setup for an implied connect */
948 if (unlikely(sock->state == SS_CONNECTING)) {
949 res = auto_connect(sock, msg);
954 /* Discard an empty non-errored message & try again */
956 if ((!sz) && (!err)) {
957 advance_rx_queue(sk);
961 /* Capture sender's address (optional) */
963 set_orig_addr(m, msg);
965 /* Capture ancillary data (optional) */
967 res = anc_data_recv(m, msg, tport);
971 /* Capture message data (if valid) & compute return value (always) */
974 if (unlikely(buf_len < sz)) {
976 m->msg_flags |= MSG_TRUNC;
978 if (unlikely(copy_to_user(m->msg_iov->iov_base, msg_data(msg),
985 if ((sock->state == SS_READY) ||
986 ((err == TIPC_CONN_SHUTDOWN) || m->msg_control))
992 /* Consume received message (optional) */
994 if (likely(!(flags & MSG_PEEK))) {
995 if ((sock->state != SS_READY) &&
996 (++tport->conn_unacked >= TIPC_FLOW_CONTROL_WIN))
997 tipc_acknowledge(tport->ref, tport->conn_unacked);
998 advance_rx_queue(sk);
1006 * recv_stream - receive stream-oriented data
1008 * @m: descriptor for message info
1009 * @buf_len: total size of user buffer area
1010 * @flags: receive flags
1012 * Used for SOCK_STREAM messages only. If not enough data is available
1013 * will optionally wait for more; never truncates data.
1015 * Returns size of returned message data, errno otherwise
1018 static int recv_stream(struct kiocb *iocb, struct socket *sock,
1019 struct msghdr *m, size_t buf_len, int flags)
1021 struct sock *sk = sock->sk;
1022 struct tipc_port *tport = tipc_sk_port(sk);
1023 struct sk_buff *buf;
1024 struct tipc_msg *msg;
1029 char __user *crs = m->msg_iov->iov_base;
1030 unsigned char *buf_crs;
1034 /* Catch invalid receive attempts */
1036 if (m->msg_iovlen != 1)
1037 return -EOPNOTSUPP; /* Don't do multiple iovec entries yet */
1039 if (unlikely(!buf_len))
1044 if (unlikely((sock->state == SS_UNCONNECTED) ||
1045 (sock->state == SS_CONNECTING))) {
1052 /* Look for a message in receive queue; wait if necessary */
1054 while (skb_queue_empty(&sk->sk_receive_queue)) {
1055 if (sock->state == SS_DISCONNECTING) {
1059 if (flags & MSG_DONTWAIT) {
1064 res = wait_event_interruptible(*sk->sk_sleep,
1065 (!skb_queue_empty(&sk->sk_receive_queue) ||
1066 (sock->state == SS_DISCONNECTING)));
1072 /* Look at first message in receive queue */
1074 buf = skb_peek(&sk->sk_receive_queue);
1076 sz = msg_data_sz(msg);
1077 err = msg_errcode(msg);
1079 /* Discard an empty non-errored message & try again */
1081 if ((!sz) && (!err)) {
1082 advance_rx_queue(sk);
1086 /* Optionally capture sender's address & ancillary data of first msg */
1088 if (sz_copied == 0) {
1089 set_orig_addr(m, msg);
1090 res = anc_data_recv(m, msg, tport);
1095 /* Capture message data (if valid) & compute return value (always) */
1098 buf_crs = (unsigned char *)(TIPC_SKB_CB(buf)->handle);
1099 sz = (unsigned char *)msg + msg_size(msg) - buf_crs;
1101 needed = (buf_len - sz_copied);
1102 sz_to_copy = (sz <= needed) ? sz : needed;
1103 if (unlikely(copy_to_user(crs, buf_crs, sz_to_copy))) {
1107 sz_copied += sz_to_copy;
1109 if (sz_to_copy < sz) {
1110 if (!(flags & MSG_PEEK))
1111 TIPC_SKB_CB(buf)->handle = buf_crs + sz_to_copy;
1118 goto exit; /* can't add error msg to valid data */
1120 if ((err == TIPC_CONN_SHUTDOWN) || m->msg_control)
1126 /* Consume received message (optional) */
1128 if (likely(!(flags & MSG_PEEK))) {
1129 if (unlikely(++tport->conn_unacked >= TIPC_FLOW_CONTROL_WIN))
1130 tipc_acknowledge(tport->ref, tport->conn_unacked);
1131 advance_rx_queue(sk);
1134 /* Loop around if more data is required */
1136 if ((sz_copied < buf_len) /* didn't get all requested data */
1137 && (!skb_queue_empty(&sock->sk->sk_receive_queue) ||
1138 (flags & MSG_WAITALL))
1139 /* ... and more is ready or required */
1140 && (!(flags & MSG_PEEK)) /* ... and aren't just peeking at data */
1141 && (!err) /* ... and haven't reached a FIN */
1147 return sz_copied ? sz_copied : res;
1151 * rx_queue_full - determine if receive queue can accept another message
1152 * @msg: message to be added to queue
1153 * @queue_size: current size of queue
1154 * @base: nominal maximum size of queue
1156 * Returns 1 if queue is unable to accept message, 0 otherwise
1159 static int rx_queue_full(struct tipc_msg *msg, u32 queue_size, u32 base)
1162 u32 imp = msg_importance(msg);
1164 if (imp == TIPC_LOW_IMPORTANCE)
1166 else if (imp == TIPC_MEDIUM_IMPORTANCE)
1167 threshold = base * 2;
1168 else if (imp == TIPC_HIGH_IMPORTANCE)
1169 threshold = base * 100;
1173 if (msg_connected(msg))
1176 return (queue_size >= threshold);
1180 * filter_rcv - validate incoming message
1184 * Enqueues message on receive queue if acceptable; optionally handles
1185 * disconnect indication for a connected socket.
1187 * Called with socket lock already taken; port lock may also be taken.
1189 * Returns TIPC error status code (TIPC_OK if message is not to be rejected)
1192 static u32 filter_rcv(struct sock *sk, struct sk_buff *buf)
1194 struct socket *sock = sk->sk_socket;
1195 struct tipc_msg *msg = buf_msg(buf);
1198 /* Reject message if it is wrong sort of message for socket */
1201 * WOULD IT BE BETTER TO JUST DISCARD THESE MESSAGES INSTEAD?
1202 * "NO PORT" ISN'T REALLY THE RIGHT ERROR CODE, AND THERE MAY
1203 * BE SECURITY IMPLICATIONS INHERENT IN REJECTING INVALID TRAFFIC
1206 if (sock->state == SS_READY) {
1207 if (msg_connected(msg)) {
1208 msg_dbg(msg, "dispatch filter 1\n");
1209 return TIPC_ERR_NO_PORT;
1212 if (msg_mcast(msg)) {
1213 msg_dbg(msg, "dispatch filter 2\n");
1214 return TIPC_ERR_NO_PORT;
1216 if (sock->state == SS_CONNECTED) {
1217 if (!msg_connected(msg)) {
1218 msg_dbg(msg, "dispatch filter 3\n");
1219 return TIPC_ERR_NO_PORT;
1222 else if (sock->state == SS_CONNECTING) {
1223 if (!msg_connected(msg) && (msg_errcode(msg) == 0)) {
1224 msg_dbg(msg, "dispatch filter 4\n");
1225 return TIPC_ERR_NO_PORT;
1228 else if (sock->state == SS_LISTENING) {
1229 if (msg_connected(msg) || msg_errcode(msg)) {
1230 msg_dbg(msg, "dispatch filter 5\n");
1231 return TIPC_ERR_NO_PORT;
1234 else if (sock->state == SS_DISCONNECTING) {
1235 msg_dbg(msg, "dispatch filter 6\n");
1236 return TIPC_ERR_NO_PORT;
1238 else /* (sock->state == SS_UNCONNECTED) */ {
1239 if (msg_connected(msg) || msg_errcode(msg)) {
1240 msg_dbg(msg, "dispatch filter 7\n");
1241 return TIPC_ERR_NO_PORT;
1246 /* Reject message if there isn't room to queue it */
1248 recv_q_len = (u32)atomic_read(&tipc_queue_size);
1249 if (unlikely(recv_q_len >= OVERLOAD_LIMIT_BASE)) {
1250 if (rx_queue_full(msg, recv_q_len, OVERLOAD_LIMIT_BASE))
1251 return TIPC_ERR_OVERLOAD;
1253 recv_q_len = skb_queue_len(&sk->sk_receive_queue);
1254 if (unlikely(recv_q_len >= (OVERLOAD_LIMIT_BASE / 2))) {
1255 if (rx_queue_full(msg, recv_q_len, OVERLOAD_LIMIT_BASE / 2))
1256 return TIPC_ERR_OVERLOAD;
1259 /* Enqueue message (finally!) */
1261 msg_dbg(msg, "<DISP<: ");
1262 TIPC_SKB_CB(buf)->handle = msg_data(msg);
1263 atomic_inc(&tipc_queue_size);
1264 __skb_queue_tail(&sk->sk_receive_queue, buf);
1266 /* Initiate connection termination for an incoming 'FIN' */
1268 if (unlikely(msg_errcode(msg) && (sock->state == SS_CONNECTED))) {
1269 sock->state = SS_DISCONNECTING;
1270 tipc_disconnect_port(tipc_sk_port(sk));
1273 if (waitqueue_active(sk->sk_sleep))
1274 wake_up_interruptible(sk->sk_sleep);
1279 * backlog_rcv - handle incoming message from backlog queue
1283 * Caller must hold socket lock, but not port lock.
1288 static int backlog_rcv(struct sock *sk, struct sk_buff *buf)
1292 res = filter_rcv(sk, buf);
1294 tipc_reject_msg(buf, res);
1299 * dispatch - handle incoming message
1300 * @tport: TIPC port that received message
1303 * Called with port lock already taken.
1305 * Returns TIPC error status code (TIPC_OK if message is not to be rejected)
1308 static u32 dispatch(struct tipc_port *tport, struct sk_buff *buf)
1310 struct sock *sk = (struct sock *)tport->usr_handle;
1314 * Process message if socket is unlocked; otherwise add to backlog queue
1316 * This code is based on sk_receive_skb(), but must be distinct from it
1317 * since a TIPC-specific filter/reject mechanism is utilized
1321 if (!sock_owned_by_user(sk)) {
1322 res = filter_rcv(sk, buf);
1324 sk_add_backlog(sk, buf);
1333 * wakeupdispatch - wake up port after congestion
1334 * @tport: port to wakeup
1336 * Called with port lock already taken.
1339 static void wakeupdispatch(struct tipc_port *tport)
1341 struct sock *sk = (struct sock *)tport->usr_handle;
1343 if (waitqueue_active(sk->sk_sleep))
1344 wake_up_interruptible(sk->sk_sleep);
1348 * connect - establish a connection to another TIPC port
1349 * @sock: socket structure
1350 * @dest: socket address for destination port
1351 * @destlen: size of socket address data structure
1352 * @flags: file-related flags associated with socket
1354 * Returns 0 on success, errno otherwise
1357 static int connect(struct socket *sock, struct sockaddr *dest, int destlen,
1360 struct sock *sk = sock->sk;
1361 struct sockaddr_tipc *dst = (struct sockaddr_tipc *)dest;
1362 struct msghdr m = {NULL,};
1363 struct sk_buff *buf;
1364 struct tipc_msg *msg;
1369 /* For now, TIPC does not allow use of connect() with DGRAM/RDM types */
1371 if (sock->state == SS_READY) {
1376 /* For now, TIPC does not support the non-blocking form of connect() */
1378 if (flags & O_NONBLOCK) {
1383 /* Issue Posix-compliant error code if socket is in the wrong state */
1385 if (sock->state == SS_LISTENING) {
1389 if (sock->state == SS_CONNECTING) {
1393 if (sock->state != SS_UNCONNECTED) {
1399 * Reject connection attempt using multicast address
1401 * Note: send_msg() validates the rest of the address fields,
1402 * so there's no need to do it here
1405 if (dst->addrtype == TIPC_ADDR_MCAST) {
1410 /* Reject any messages already in receive queue (very unlikely) */
1412 reject_rx_queue(sk);
1414 /* Send a 'SYN-' to destination */
1417 m.msg_namelen = destlen;
1418 res = send_msg(NULL, sock, &m, 0);
1423 /* Wait until an 'ACK' or 'RST' arrives, or a timeout occurs */
1426 res = wait_event_interruptible_timeout(*sk->sk_sleep,
1427 (!skb_queue_empty(&sk->sk_receive_queue) ||
1428 (sock->state != SS_CONNECTING)),
1433 buf = skb_peek(&sk->sk_receive_queue);
1436 res = auto_connect(sock, msg);
1438 if (!msg_data_sz(msg))
1439 advance_rx_queue(sk);
1442 if (sock->state == SS_CONNECTED) {
1445 res = -ECONNREFUSED;
1452 ; /* leave "res" unchanged */
1453 sock->state = SS_DISCONNECTING;
1462 * listen - allow socket to listen for incoming connections
1463 * @sock: socket structure
1466 * Returns 0 on success, errno otherwise
1469 static int listen(struct socket *sock, int len)
1471 struct sock *sk = sock->sk;
1476 if (sock->state == SS_READY)
1478 else if (sock->state != SS_UNCONNECTED)
1481 sock->state = SS_LISTENING;
1490 * accept - wait for connection request
1491 * @sock: listening socket
1492 * @newsock: new socket that is to be connected
1493 * @flags: file-related flags associated with socket
1495 * Returns 0 on success, errno otherwise
1498 static int accept(struct socket *sock, struct socket *new_sock, int flags)
1500 struct sock *sk = sock->sk;
1501 struct sk_buff *buf;
1506 if (sock->state == SS_READY) {
1510 if (sock->state != SS_LISTENING) {
1515 while (skb_queue_empty(&sk->sk_receive_queue)) {
1516 if (flags & O_NONBLOCK) {
1521 res = wait_event_interruptible(*sk->sk_sleep,
1522 (!skb_queue_empty(&sk->sk_receive_queue)));
1528 buf = skb_peek(&sk->sk_receive_queue);
1530 res = tipc_create(sock_net(sock->sk), new_sock, 0);
1532 struct sock *new_sk = new_sock->sk;
1533 struct tipc_port *new_tport = tipc_sk_port(new_sk);
1534 u32 new_ref = new_tport->ref;
1535 struct tipc_portid id;
1536 struct tipc_msg *msg = buf_msg(buf);
1541 * Reject any stray messages received by new socket
1542 * before the socket lock was taken (very, very unlikely)
1545 reject_rx_queue(new_sk);
1547 /* Connect new socket to it's peer */
1549 id.ref = msg_origport(msg);
1550 id.node = msg_orignode(msg);
1551 tipc_connect2port(new_ref, &id);
1552 new_sock->state = SS_CONNECTED;
1554 tipc_set_portimportance(new_ref, msg_importance(msg));
1555 if (msg_named(msg)) {
1556 new_tport->conn_type = msg_nametype(msg);
1557 new_tport->conn_instance = msg_nameinst(msg);
1561 * Respond to 'SYN-' by discarding it & returning 'ACK'-.
1562 * Respond to 'SYN+' by queuing it on new socket.
1565 msg_dbg(msg,"<ACC<: ");
1566 if (!msg_data_sz(msg)) {
1567 struct msghdr m = {NULL,};
1569 advance_rx_queue(sk);
1570 send_packet(NULL, new_sock, &m, 0);
1572 __skb_dequeue(&sk->sk_receive_queue);
1573 __skb_queue_head(&new_sk->sk_receive_queue, buf);
1575 release_sock(new_sk);
1583 * shutdown - shutdown socket connection
1584 * @sock: socket structure
1585 * @how: direction to close (must be SHUT_RDWR)
1587 * Terminates connection (if necessary), then purges socket's receive queue.
1589 * Returns 0 on success, errno otherwise
1592 static int shutdown(struct socket *sock, int how)
1594 struct sock *sk = sock->sk;
1595 struct tipc_port *tport = tipc_sk_port(sk);
1596 struct sk_buff *buf;
1599 if (how != SHUT_RDWR)
1604 switch (sock->state) {
1608 /* Disconnect and send a 'FIN+' or 'FIN-' message to peer */
1610 buf = __skb_dequeue(&sk->sk_receive_queue);
1612 atomic_dec(&tipc_queue_size);
1613 if (TIPC_SKB_CB(buf)->handle != msg_data(buf_msg(buf))) {
1617 tipc_disconnect(tport->ref);
1618 tipc_reject_msg(buf, TIPC_CONN_SHUTDOWN);
1620 tipc_shutdown(tport->ref);
1623 sock->state = SS_DISCONNECTING;
1627 case SS_DISCONNECTING:
1629 /* Discard any unreceived messages; wake up sleeping tasks */
1631 discard_rx_queue(sk);
1632 if (waitqueue_active(sk->sk_sleep))
1633 wake_up_interruptible(sk->sk_sleep);
1646 * setsockopt - set socket option
1647 * @sock: socket structure
1648 * @lvl: option level
1649 * @opt: option identifier
1650 * @ov: pointer to new option value
1651 * @ol: length of option value
1653 * For stream sockets only, accepts and ignores all IPPROTO_TCP options
1654 * (to ease compatibility).
1656 * Returns 0 on success, errno otherwise
1659 static int setsockopt(struct socket *sock,
1660 int lvl, int opt, char __user *ov, int ol)
1662 struct sock *sk = sock->sk;
1663 struct tipc_port *tport = tipc_sk_port(sk);
1667 if ((lvl == IPPROTO_TCP) && (sock->type == SOCK_STREAM))
1669 if (lvl != SOL_TIPC)
1670 return -ENOPROTOOPT;
1671 if (ol < sizeof(value))
1673 if ((res = get_user(value, (u32 __user *)ov)))
1679 case TIPC_IMPORTANCE:
1680 res = tipc_set_portimportance(tport->ref, value);
1682 case TIPC_SRC_DROPPABLE:
1683 if (sock->type != SOCK_STREAM)
1684 res = tipc_set_portunreliable(tport->ref, value);
1688 case TIPC_DEST_DROPPABLE:
1689 res = tipc_set_portunreturnable(tport->ref, value);
1691 case TIPC_CONN_TIMEOUT:
1692 sk->sk_rcvtimeo = msecs_to_jiffies(value);
1693 /* no need to set "res", since already 0 at this point */
1705 * getsockopt - get socket option
1706 * @sock: socket structure
1707 * @lvl: option level
1708 * @opt: option identifier
1709 * @ov: receptacle for option value
1710 * @ol: receptacle for length of option value
1712 * For stream sockets only, returns 0 length result for all IPPROTO_TCP options
1713 * (to ease compatibility).
1715 * Returns 0 on success, errno otherwise
1718 static int getsockopt(struct socket *sock,
1719 int lvl, int opt, char __user *ov, int __user *ol)
1721 struct sock *sk = sock->sk;
1722 struct tipc_port *tport = tipc_sk_port(sk);
1727 if ((lvl == IPPROTO_TCP) && (sock->type == SOCK_STREAM))
1728 return put_user(0, ol);
1729 if (lvl != SOL_TIPC)
1730 return -ENOPROTOOPT;
1731 if ((res = get_user(len, ol)))
1737 case TIPC_IMPORTANCE:
1738 res = tipc_portimportance(tport->ref, &value);
1740 case TIPC_SRC_DROPPABLE:
1741 res = tipc_portunreliable(tport->ref, &value);
1743 case TIPC_DEST_DROPPABLE:
1744 res = tipc_portunreturnable(tport->ref, &value);
1746 case TIPC_CONN_TIMEOUT:
1747 value = jiffies_to_msecs(sk->sk_rcvtimeo);
1748 /* no need to set "res", since already 0 at this point */
1759 else if (len < sizeof(value)) {
1762 else if (copy_to_user(ov, &value, sizeof(value))) {
1766 res = put_user(sizeof(value), ol);
1773 * Protocol switches for the various types of TIPC sockets
1776 static const struct proto_ops msg_ops = {
1777 .owner = THIS_MODULE,
1782 .socketpair = sock_no_socketpair,
1784 .getname = get_name,
1786 .ioctl = sock_no_ioctl,
1788 .shutdown = shutdown,
1789 .setsockopt = setsockopt,
1790 .getsockopt = getsockopt,
1791 .sendmsg = send_msg,
1792 .recvmsg = recv_msg,
1793 .mmap = sock_no_mmap,
1794 .sendpage = sock_no_sendpage
1797 static const struct proto_ops packet_ops = {
1798 .owner = THIS_MODULE,
1803 .socketpair = sock_no_socketpair,
1805 .getname = get_name,
1807 .ioctl = sock_no_ioctl,
1809 .shutdown = shutdown,
1810 .setsockopt = setsockopt,
1811 .getsockopt = getsockopt,
1812 .sendmsg = send_packet,
1813 .recvmsg = recv_msg,
1814 .mmap = sock_no_mmap,
1815 .sendpage = sock_no_sendpage
1818 static const struct proto_ops stream_ops = {
1819 .owner = THIS_MODULE,
1824 .socketpair = sock_no_socketpair,
1826 .getname = get_name,
1828 .ioctl = sock_no_ioctl,
1830 .shutdown = shutdown,
1831 .setsockopt = setsockopt,
1832 .getsockopt = getsockopt,
1833 .sendmsg = send_stream,
1834 .recvmsg = recv_stream,
1835 .mmap = sock_no_mmap,
1836 .sendpage = sock_no_sendpage
1839 static const struct net_proto_family tipc_family_ops = {
1840 .owner = THIS_MODULE,
1842 .create = tipc_create
1845 static struct proto tipc_proto = {
1847 .owner = THIS_MODULE,
1848 .obj_size = sizeof(struct tipc_sock)
1852 * tipc_socket_init - initialize TIPC socket interface
1854 * Returns 0 on success, errno otherwise
1856 int tipc_socket_init(void)
1860 res = proto_register(&tipc_proto, 1);
1862 err("Failed to register TIPC protocol type\n");
1866 res = sock_register(&tipc_family_ops);
1868 err("Failed to register TIPC socket type\n");
1869 proto_unregister(&tipc_proto);
1873 sockets_enabled = 1;
1879 * tipc_socket_stop - stop TIPC socket interface
1882 void tipc_socket_stop(void)
1884 if (!sockets_enabled)
1887 sockets_enabled = 0;
1888 sock_unregister(tipc_family_ops.family);
1889 proto_unregister(&tipc_proto);