2 * net/tipc/socket.c: TIPC socket API
4 * Copyright (c) 2001-2007, Ericsson AB
5 * Copyright (c) 2004-2008, 2010-2011, 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 OVERLOAD_LIMIT_BASE 5000
47 #define CONN_TIMEOUT_DEFAULT 8000 /* default connect timeout = 8s */
52 struct tipc_portid peer_name;
53 unsigned int conn_timeout;
56 #define tipc_sk(sk) ((struct tipc_sock *)(sk))
57 #define tipc_sk_port(sk) (tipc_sk(sk)->p)
59 #define tipc_rx_ready(sock) (!skb_queue_empty(&sock->sk->sk_receive_queue) || \
60 (sock->state == SS_DISCONNECTING))
62 static int backlog_rcv(struct sock *sk, struct sk_buff *skb);
63 static u32 dispatch(struct tipc_port *tport, struct sk_buff *buf);
64 static void wakeupdispatch(struct tipc_port *tport);
65 static void tipc_data_ready(struct sock *sk, int len);
66 static void tipc_write_space(struct sock *sk);
68 static const struct proto_ops packet_ops;
69 static const struct proto_ops stream_ops;
70 static const struct proto_ops msg_ops;
72 static struct proto tipc_proto;
74 static int sockets_enabled;
76 static atomic_t tipc_queue_size = ATOMIC_INIT(0);
79 * Revised TIPC socket locking policy:
81 * Most socket operations take the standard socket lock when they start
82 * and hold it until they finish (or until they need to sleep). Acquiring
83 * this lock grants the owner exclusive access to the fields of the socket
84 * data structures, with the exception of the backlog queue. A few socket
85 * operations can be done without taking the socket lock because they only
86 * read socket information that never changes during the life of the socket.
88 * Socket operations may acquire the lock for the associated TIPC port if they
89 * need to perform an operation on the port. If any routine needs to acquire
90 * both the socket lock and the port lock it must take the socket lock first
91 * to avoid the risk of deadlock.
93 * The dispatcher handling incoming messages cannot grab the socket lock in
94 * the standard fashion, since invoked it runs at the BH level and cannot block.
95 * Instead, it checks to see if the socket lock is currently owned by someone,
96 * and either handles the message itself or adds it to the socket's backlog
97 * queue; in the latter case the queued message is processed once the process
98 * owning the socket lock releases it.
100 * NOTE: Releasing the socket lock while an operation is sleeping overcomes
101 * the problem of a blocked socket operation preventing any other operations
102 * from occurring. However, applications must be careful if they have
103 * multiple threads trying to send (or receive) on the same socket, as these
104 * operations might interfere with each other. For example, doing a connect
105 * and a receive at the same time might allow the receive to consume the
106 * ACK message meant for the connect. While additional work could be done
107 * to try and overcome this, it doesn't seem to be worthwhile at the present.
109 * NOTE: Releasing the socket lock while an operation is sleeping also ensures
110 * that another operation that must be performed in a non-blocking manner is
111 * not delayed for very long because the lock has already been taken.
113 * NOTE: This code assumes that certain fields of a port/socket pair are
114 * constant over its lifetime; such fields can be examined without taking
115 * the socket lock and/or port lock, and do not need to be re-read even
116 * after resuming processing after waiting. These fields include:
118 * - pointer to socket sk structure (aka tipc_sock structure)
119 * - pointer to port structure
124 * advance_rx_queue - discard first buffer in socket receive queue
126 * Caller must hold socket lock
128 static void advance_rx_queue(struct sock *sk)
130 kfree_skb(__skb_dequeue(&sk->sk_receive_queue));
131 atomic_dec(&tipc_queue_size);
135 * discard_rx_queue - discard all buffers in socket receive queue
137 * Caller must hold socket lock
139 static void discard_rx_queue(struct sock *sk)
143 while ((buf = __skb_dequeue(&sk->sk_receive_queue))) {
144 atomic_dec(&tipc_queue_size);
150 * reject_rx_queue - reject all buffers in socket receive queue
152 * Caller must hold socket lock
154 static void reject_rx_queue(struct sock *sk)
158 while ((buf = __skb_dequeue(&sk->sk_receive_queue))) {
159 tipc_reject_msg(buf, TIPC_ERR_NO_PORT);
160 atomic_dec(&tipc_queue_size);
165 * tipc_create - create a TIPC socket
166 * @net: network namespace (must be default network)
167 * @sock: pre-allocated socket structure
168 * @protocol: protocol indicator (must be 0)
169 * @kern: caused by kernel or by userspace?
171 * This routine creates additional data structures used by the TIPC socket,
172 * initializes them, and links them together.
174 * Returns 0 on success, errno otherwise
176 static int tipc_create(struct net *net, struct socket *sock, int protocol,
179 const struct proto_ops *ops;
182 struct tipc_port *tp_ptr;
184 /* Validate arguments */
185 if (unlikely(protocol != 0))
186 return -EPROTONOSUPPORT;
188 switch (sock->type) {
191 state = SS_UNCONNECTED;
195 state = SS_UNCONNECTED;
206 /* Allocate socket's protocol area */
207 sk = sk_alloc(net, AF_TIPC, GFP_KERNEL, &tipc_proto);
211 /* Allocate TIPC port for socket to use */
212 tp_ptr = tipc_createport_raw(sk, &dispatch, &wakeupdispatch,
213 TIPC_LOW_IMPORTANCE);
214 if (unlikely(!tp_ptr)) {
219 /* Finish initializing socket data structures */
223 sock_init_data(sock, sk);
224 sk->sk_backlog_rcv = backlog_rcv;
225 sk->sk_rcvbuf = TIPC_FLOW_CONTROL_WIN * 2 * TIPC_MAX_USER_MSG_SIZE * 2;
226 sk->sk_data_ready = tipc_data_ready;
227 sk->sk_write_space = tipc_write_space;
228 tipc_sk(sk)->p = tp_ptr;
229 tipc_sk(sk)->conn_timeout = CONN_TIMEOUT_DEFAULT;
231 spin_unlock_bh(tp_ptr->lock);
233 if (sock->state == SS_READY) {
234 tipc_set_portunreturnable(tp_ptr->ref, 1);
235 if (sock->type == SOCK_DGRAM)
236 tipc_set_portunreliable(tp_ptr->ref, 1);
243 * release - destroy a TIPC socket
244 * @sock: socket to destroy
246 * This routine cleans up any messages that are still queued on the socket.
247 * For DGRAM and RDM socket types, all queued messages are rejected.
248 * For SEQPACKET and STREAM socket types, the first message is rejected
249 * and any others are discarded. (If the first message on a STREAM socket
250 * is partially-read, it is discarded and the next one is rejected instead.)
252 * NOTE: Rejected messages are not necessarily returned to the sender! They
253 * are returned or discarded according to the "destination droppable" setting
254 * specified for the message by the sender.
256 * Returns 0 on success, errno otherwise
258 static int release(struct socket *sock)
260 struct sock *sk = sock->sk;
261 struct tipc_port *tport;
266 * Exit if socket isn't fully initialized (occurs when a failed accept()
267 * releases a pre-allocated child socket that was never used)
272 tport = tipc_sk_port(sk);
276 * Reject all unreceived messages, except on an active connection
277 * (which disconnects locally & sends a 'FIN+' to peer)
279 while (sock->state != SS_DISCONNECTING) {
280 buf = __skb_dequeue(&sk->sk_receive_queue);
283 atomic_dec(&tipc_queue_size);
284 if (TIPC_SKB_CB(buf)->handle != 0)
287 if ((sock->state == SS_CONNECTING) ||
288 (sock->state == SS_CONNECTED)) {
289 sock->state = SS_DISCONNECTING;
290 tipc_disconnect(tport->ref);
292 tipc_reject_msg(buf, TIPC_ERR_NO_PORT);
297 * Delete TIPC port; this ensures no more messages are queued
298 * (also disconnects an active connection & sends a 'FIN-' to peer)
300 res = tipc_deleteport(tport->ref);
302 /* Discard any remaining (connection-based) messages in receive queue */
303 discard_rx_queue(sk);
305 /* Reject any messages that accumulated in backlog queue */
306 sock->state = SS_DISCONNECTING;
316 * bind - associate or disassocate TIPC name(s) with a socket
317 * @sock: socket structure
318 * @uaddr: socket address describing name(s) and desired operation
319 * @uaddr_len: size of socket address data structure
321 * Name and name sequence binding is indicated using a positive scope value;
322 * a negative scope value unbinds the specified name. Specifying no name
323 * (i.e. a socket address length of 0) unbinds all names from the socket.
325 * Returns 0 on success, errno otherwise
327 * NOTE: This routine doesn't need to take the socket lock since it doesn't
328 * access any non-constant socket information.
330 static int bind(struct socket *sock, struct sockaddr *uaddr, int uaddr_len)
332 struct sockaddr_tipc *addr = (struct sockaddr_tipc *)uaddr;
333 u32 portref = tipc_sk_port(sock->sk)->ref;
335 if (unlikely(!uaddr_len))
336 return tipc_withdraw(portref, 0, NULL);
338 if (uaddr_len < sizeof(struct sockaddr_tipc))
340 if (addr->family != AF_TIPC)
341 return -EAFNOSUPPORT;
343 if (addr->addrtype == TIPC_ADDR_NAME)
344 addr->addr.nameseq.upper = addr->addr.nameseq.lower;
345 else if (addr->addrtype != TIPC_ADDR_NAMESEQ)
346 return -EAFNOSUPPORT;
348 if (addr->addr.nameseq.type < TIPC_RESERVED_TYPES)
351 return (addr->scope > 0) ?
352 tipc_publish(portref, addr->scope, &addr->addr.nameseq) :
353 tipc_withdraw(portref, -addr->scope, &addr->addr.nameseq);
357 * get_name - get port ID of socket or peer socket
358 * @sock: socket structure
359 * @uaddr: area for returned socket address
360 * @uaddr_len: area for returned length of socket address
361 * @peer: 0 = own ID, 1 = current peer ID, 2 = current/former peer ID
363 * Returns 0 on success, errno otherwise
365 * NOTE: This routine doesn't need to take the socket lock since it only
366 * accesses socket information that is unchanging (or which changes in
367 * a completely predictable manner).
369 static int get_name(struct socket *sock, struct sockaddr *uaddr,
370 int *uaddr_len, int peer)
372 struct sockaddr_tipc *addr = (struct sockaddr_tipc *)uaddr;
373 struct tipc_sock *tsock = tipc_sk(sock->sk);
375 memset(addr, 0, sizeof(*addr));
377 if ((sock->state != SS_CONNECTED) &&
378 ((peer != 2) || (sock->state != SS_DISCONNECTING)))
380 addr->addr.id.ref = tsock->peer_name.ref;
381 addr->addr.id.node = tsock->peer_name.node;
383 addr->addr.id.ref = tsock->p->ref;
384 addr->addr.id.node = tipc_own_addr;
387 *uaddr_len = sizeof(*addr);
388 addr->addrtype = TIPC_ADDR_ID;
389 addr->family = AF_TIPC;
391 addr->addr.name.domain = 0;
397 * poll - read and possibly block on pollmask
398 * @file: file structure associated with the socket
399 * @sock: socket for which to calculate the poll bits
402 * Returns pollmask value
405 * It appears that the usual socket locking mechanisms are not useful here
406 * since the pollmask info is potentially out-of-date the moment this routine
407 * exits. TCP and other protocols seem to rely on higher level poll routines
408 * to handle any preventable race conditions, so TIPC will do the same ...
410 * TIPC sets the returned events as follows:
412 * socket state flags set
413 * ------------ ---------
414 * unconnected no read flags
415 * POLLOUT if port is not congested
417 * connecting POLLIN/POLLRDNORM if ACK/NACK in rx queue
420 * connected POLLIN/POLLRDNORM if data in rx queue
421 * POLLOUT if port is not congested
423 * disconnecting POLLIN/POLLRDNORM/POLLHUP
426 * listening POLLIN if SYN in rx queue
429 * ready POLLIN/POLLRDNORM if data in rx queue
430 * [connectionless] POLLOUT (since port cannot be congested)
432 * IMPORTANT: The fact that a read or write operation is indicated does NOT
433 * imply that the operation will succeed, merely that it should be performed
434 * and will not block.
436 static unsigned int poll(struct file *file, struct socket *sock,
439 struct sock *sk = sock->sk;
442 sock_poll_wait(file, sk_sleep(sk), wait);
444 switch ((int)sock->state) {
446 if (!tipc_sk_port(sk)->congested)
451 if (!tipc_sk_port(sk)->congested)
456 if (!skb_queue_empty(&sk->sk_receive_queue))
457 mask |= (POLLIN | POLLRDNORM);
459 case SS_DISCONNECTING:
460 mask = (POLLIN | POLLRDNORM | POLLHUP);
468 * dest_name_check - verify user is permitted to send to specified port name
469 * @dest: destination address
470 * @m: descriptor for message to be sent
472 * Prevents restricted configuration commands from being issued by
473 * unauthorized users.
475 * Returns 0 if permission is granted, otherwise errno
477 static int dest_name_check(struct sockaddr_tipc *dest, struct msghdr *m)
479 struct tipc_cfg_msg_hdr hdr;
481 if (likely(dest->addr.name.name.type >= TIPC_RESERVED_TYPES))
483 if (likely(dest->addr.name.name.type == TIPC_TOP_SRV))
485 if (likely(dest->addr.name.name.type != TIPC_CFG_SRV))
488 if (!m->msg_iovlen || (m->msg_iov[0].iov_len < sizeof(hdr)))
490 if (copy_from_user(&hdr, m->msg_iov[0].iov_base, sizeof(hdr)))
492 if ((ntohs(hdr.tcm_type) & 0xC000) && (!capable(CAP_NET_ADMIN)))
499 * send_msg - send message in connectionless manner
500 * @iocb: if NULL, indicates that socket lock is already held
501 * @sock: socket structure
502 * @m: message to send
503 * @total_len: length of message
505 * Message must have an destination specified explicitly.
506 * Used for SOCK_RDM and SOCK_DGRAM messages,
507 * and for 'SYN' messages on SOCK_SEQPACKET and SOCK_STREAM connections.
508 * (Note: 'SYN+' is prohibited on SOCK_STREAM.)
510 * Returns the number of bytes sent on success, or errno otherwise
512 static int send_msg(struct kiocb *iocb, struct socket *sock,
513 struct msghdr *m, size_t total_len)
515 struct sock *sk = sock->sk;
516 struct tipc_port *tport = tipc_sk_port(sk);
517 struct sockaddr_tipc *dest = (struct sockaddr_tipc *)m->msg_name;
523 return -EDESTADDRREQ;
524 if (unlikely((m->msg_namelen < sizeof(*dest)) ||
525 (dest->family != AF_TIPC)))
527 if ((total_len > TIPC_MAX_USER_MSG_SIZE) ||
528 (m->msg_iovlen > (unsigned int)INT_MAX))
534 needs_conn = (sock->state != SS_READY);
535 if (unlikely(needs_conn)) {
536 if (sock->state == SS_LISTENING) {
540 if (sock->state != SS_UNCONNECTED) {
544 if ((tport->published) ||
545 ((sock->type == SOCK_STREAM) && (total_len != 0))) {
549 if (dest->addrtype == TIPC_ADDR_NAME) {
550 tport->conn_type = dest->addr.name.name.type;
551 tport->conn_instance = dest->addr.name.name.instance;
554 /* Abort any pending connection attempts (very unlikely) */
558 timeout_val = sock_sndtimeo(sk, m->msg_flags & MSG_DONTWAIT);
561 if (dest->addrtype == TIPC_ADDR_NAME) {
562 res = dest_name_check(dest, m);
565 res = tipc_send2name(tport->ref,
566 &dest->addr.name.name,
567 dest->addr.name.domain,
571 } else if (dest->addrtype == TIPC_ADDR_ID) {
572 res = tipc_send2port(tport->ref,
577 } else if (dest->addrtype == TIPC_ADDR_MCAST) {
582 res = dest_name_check(dest, m);
585 res = tipc_multicast(tport->ref,
591 if (likely(res != -ELINKCONG)) {
592 if (needs_conn && (res >= 0))
593 sock->state = SS_CONNECTING;
596 if (timeout_val <= 0L) {
597 res = timeout_val ? timeout_val : -EWOULDBLOCK;
601 timeout_val = wait_event_interruptible_timeout(*sk_sleep(sk),
602 !tport->congested, timeout_val);
613 * send_packet - send a connection-oriented message
614 * @iocb: if NULL, indicates that socket lock is already held
615 * @sock: socket structure
616 * @m: message to send
617 * @total_len: length of message
619 * Used for SOCK_SEQPACKET messages and SOCK_STREAM data.
621 * Returns the number of bytes sent on success, or errno otherwise
623 static int send_packet(struct kiocb *iocb, struct socket *sock,
624 struct msghdr *m, size_t total_len)
626 struct sock *sk = sock->sk;
627 struct tipc_port *tport = tipc_sk_port(sk);
628 struct sockaddr_tipc *dest = (struct sockaddr_tipc *)m->msg_name;
632 /* Handle implied connection establishment */
634 return send_msg(iocb, sock, m, total_len);
636 if ((total_len > TIPC_MAX_USER_MSG_SIZE) ||
637 (m->msg_iovlen > (unsigned int)INT_MAX))
643 timeout_val = sock_sndtimeo(sk, m->msg_flags & MSG_DONTWAIT);
646 if (unlikely(sock->state != SS_CONNECTED)) {
647 if (sock->state == SS_DISCONNECTING)
654 res = tipc_send(tport->ref, m->msg_iovlen, m->msg_iov,
656 if (likely(res != -ELINKCONG))
658 if (timeout_val <= 0L) {
659 res = timeout_val ? timeout_val : -EWOULDBLOCK;
663 timeout_val = wait_event_interruptible_timeout(*sk_sleep(sk),
664 (!tport->congested || !tport->connected), timeout_val);
674 * send_stream - send stream-oriented data
676 * @sock: socket structure
678 * @total_len: total length of data to be sent
680 * Used for SOCK_STREAM data.
682 * Returns the number of bytes sent on success (or partial success),
683 * or errno if no data sent
685 static int send_stream(struct kiocb *iocb, struct socket *sock,
686 struct msghdr *m, size_t total_len)
688 struct sock *sk = sock->sk;
689 struct tipc_port *tport = tipc_sk_port(sk);
690 struct msghdr my_msg;
692 struct iovec *curr_iov;
694 char __user *curr_start;
703 /* Handle special cases where there is no connection */
704 if (unlikely(sock->state != SS_CONNECTED)) {
705 if (sock->state == SS_UNCONNECTED) {
706 res = send_packet(NULL, sock, m, total_len);
708 } else if (sock->state == SS_DISCONNECTING) {
717 if (unlikely(m->msg_name)) {
722 if ((total_len > (unsigned int)INT_MAX) ||
723 (m->msg_iovlen > (unsigned int)INT_MAX)) {
729 * Send each iovec entry using one or more messages
731 * Note: This algorithm is good for the most likely case
732 * (i.e. one large iovec entry), but could be improved to pass sets
733 * of small iovec entries into send_packet().
735 curr_iov = m->msg_iov;
736 curr_iovlen = m->msg_iovlen;
737 my_msg.msg_iov = &my_iov;
738 my_msg.msg_iovlen = 1;
739 my_msg.msg_flags = m->msg_flags;
740 my_msg.msg_name = NULL;
743 hdr_size = msg_hdr_sz(&tport->phdr);
745 while (curr_iovlen--) {
746 curr_start = curr_iov->iov_base;
747 curr_left = curr_iov->iov_len;
750 bytes_to_send = tport->max_pkt - hdr_size;
751 if (bytes_to_send > TIPC_MAX_USER_MSG_SIZE)
752 bytes_to_send = TIPC_MAX_USER_MSG_SIZE;
753 if (curr_left < bytes_to_send)
754 bytes_to_send = curr_left;
755 my_iov.iov_base = curr_start;
756 my_iov.iov_len = bytes_to_send;
757 res = send_packet(NULL, sock, &my_msg, bytes_to_send);
763 curr_left -= bytes_to_send;
764 curr_start += bytes_to_send;
765 bytes_sent += bytes_to_send;
777 * auto_connect - complete connection setup to a remote port
778 * @sock: socket structure
779 * @msg: peer's response message
781 * Returns 0 on success, errno otherwise
783 static int auto_connect(struct socket *sock, struct tipc_msg *msg)
785 struct tipc_sock *tsock = tipc_sk(sock->sk);
787 if (msg_errcode(msg)) {
788 sock->state = SS_DISCONNECTING;
789 return -ECONNREFUSED;
792 tsock->peer_name.ref = msg_origport(msg);
793 tsock->peer_name.node = msg_orignode(msg);
794 tipc_connect2port(tsock->p->ref, &tsock->peer_name);
795 tipc_set_portimportance(tsock->p->ref, msg_importance(msg));
796 sock->state = SS_CONNECTED;
801 * set_orig_addr - capture sender's address for received message
802 * @m: descriptor for message info
803 * @msg: received message header
805 * Note: Address is not captured if not requested by receiver.
807 static void set_orig_addr(struct msghdr *m, struct tipc_msg *msg)
809 struct sockaddr_tipc *addr = (struct sockaddr_tipc *)m->msg_name;
812 addr->family = AF_TIPC;
813 addr->addrtype = TIPC_ADDR_ID;
814 addr->addr.id.ref = msg_origport(msg);
815 addr->addr.id.node = msg_orignode(msg);
816 addr->addr.name.domain = 0; /* could leave uninitialized */
817 addr->scope = 0; /* could leave uninitialized */
818 m->msg_namelen = sizeof(struct sockaddr_tipc);
823 * anc_data_recv - optionally capture ancillary data for received message
824 * @m: descriptor for message info
825 * @msg: received message header
826 * @tport: TIPC port associated with message
828 * Note: Ancillary data is not captured if not requested by receiver.
830 * Returns 0 if successful, otherwise errno
832 static int anc_data_recv(struct msghdr *m, struct tipc_msg *msg,
833 struct tipc_port *tport)
841 if (likely(m->msg_controllen == 0))
844 /* Optionally capture errored message object(s) */
845 err = msg ? msg_errcode(msg) : 0;
848 anc_data[1] = msg_data_sz(msg);
849 res = put_cmsg(m, SOL_TIPC, TIPC_ERRINFO, 8, anc_data);
853 res = put_cmsg(m, SOL_TIPC, TIPC_RETDATA, anc_data[1],
860 /* Optionally capture message destination object */
861 dest_type = msg ? msg_type(msg) : TIPC_DIRECT_MSG;
865 anc_data[0] = msg_nametype(msg);
866 anc_data[1] = msg_namelower(msg);
867 anc_data[2] = msg_namelower(msg);
871 anc_data[0] = msg_nametype(msg);
872 anc_data[1] = msg_namelower(msg);
873 anc_data[2] = msg_nameupper(msg);
876 has_name = (tport->conn_type != 0);
877 anc_data[0] = tport->conn_type;
878 anc_data[1] = tport->conn_instance;
879 anc_data[2] = tport->conn_instance;
885 res = put_cmsg(m, SOL_TIPC, TIPC_DESTNAME, 12, anc_data);
894 * recv_msg - receive packet-oriented message
896 * @m: descriptor for message info
897 * @buf_len: total size of user buffer area
898 * @flags: receive flags
900 * Used for SOCK_DGRAM, SOCK_RDM, and SOCK_SEQPACKET messages.
901 * If the complete message doesn't fit in user area, truncate it.
903 * Returns size of returned message data, errno otherwise
905 static int recv_msg(struct kiocb *iocb, struct socket *sock,
906 struct msghdr *m, size_t buf_len, int flags)
908 struct sock *sk = sock->sk;
909 struct tipc_port *tport = tipc_sk_port(sk);
911 struct tipc_msg *msg;
917 /* Catch invalid receive requests */
918 if (unlikely(!buf_len))
923 if (unlikely(sock->state == SS_UNCONNECTED)) {
928 timeout = sock_rcvtimeo(sk, flags & MSG_DONTWAIT);
931 /* Look for a message in receive queue; wait if necessary */
932 while (skb_queue_empty(&sk->sk_receive_queue)) {
933 if (sock->state == SS_DISCONNECTING) {
938 res = timeout ? timeout : -EWOULDBLOCK;
942 timeout = wait_event_interruptible_timeout(*sk_sleep(sk),
948 /* Look at first message in receive queue */
949 buf = skb_peek(&sk->sk_receive_queue);
951 sz = msg_data_sz(msg);
952 err = msg_errcode(msg);
954 /* Complete connection setup for an implied connect */
955 if (unlikely(sock->state == SS_CONNECTING)) {
956 res = auto_connect(sock, msg);
961 /* Discard an empty non-errored message & try again */
962 if ((!sz) && (!err)) {
963 advance_rx_queue(sk);
967 /* Capture sender's address (optional) */
968 set_orig_addr(m, msg);
970 /* Capture ancillary data (optional) */
971 res = anc_data_recv(m, msg, tport);
975 /* Capture message data (if valid) & compute return value (always) */
977 if (unlikely(buf_len < sz)) {
979 m->msg_flags |= MSG_TRUNC;
981 res = skb_copy_datagram_iovec(buf, msg_hdr_sz(msg),
987 if ((sock->state == SS_READY) ||
988 ((err == TIPC_CONN_SHUTDOWN) || m->msg_control))
994 /* 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
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;
1027 int sz_to_copy, target, needed;
1032 /* Catch invalid receive attempts */
1033 if (unlikely(!buf_len))
1038 if (unlikely((sock->state == SS_UNCONNECTED) ||
1039 (sock->state == SS_CONNECTING))) {
1044 target = sock_rcvlowat(sk, flags & MSG_WAITALL, buf_len);
1045 timeout = sock_rcvtimeo(sk, flags & MSG_DONTWAIT);
1048 /* Look for a message in receive queue; wait if necessary */
1049 while (skb_queue_empty(&sk->sk_receive_queue)) {
1050 if (sock->state == SS_DISCONNECTING) {
1054 if (timeout <= 0L) {
1055 res = timeout ? timeout : -EWOULDBLOCK;
1059 timeout = wait_event_interruptible_timeout(*sk_sleep(sk),
1060 tipc_rx_ready(sock),
1065 /* Look at first message in receive queue */
1066 buf = skb_peek(&sk->sk_receive_queue);
1068 sz = msg_data_sz(msg);
1069 err = msg_errcode(msg);
1071 /* Discard an empty non-errored message & try again */
1072 if ((!sz) && (!err)) {
1073 advance_rx_queue(sk);
1077 /* Optionally capture sender's address & ancillary data of first msg */
1078 if (sz_copied == 0) {
1079 set_orig_addr(m, msg);
1080 res = anc_data_recv(m, msg, tport);
1085 /* Capture message data (if valid) & compute return value (always) */
1087 u32 offset = (u32)(unsigned long)(TIPC_SKB_CB(buf)->handle);
1090 needed = (buf_len - sz_copied);
1091 sz_to_copy = (sz <= needed) ? sz : needed;
1093 res = skb_copy_datagram_iovec(buf, msg_hdr_sz(msg) + offset,
1094 m->msg_iov, sz_to_copy);
1098 sz_copied += sz_to_copy;
1100 if (sz_to_copy < sz) {
1101 if (!(flags & MSG_PEEK))
1102 TIPC_SKB_CB(buf)->handle =
1103 (void *)(unsigned long)(offset + sz_to_copy);
1108 goto exit; /* can't add error msg to valid data */
1110 if ((err == TIPC_CONN_SHUTDOWN) || m->msg_control)
1116 /* Consume received message (optional) */
1117 if (likely(!(flags & MSG_PEEK))) {
1118 if (unlikely(++tport->conn_unacked >= TIPC_FLOW_CONTROL_WIN))
1119 tipc_acknowledge(tport->ref, tport->conn_unacked);
1120 advance_rx_queue(sk);
1123 /* Loop around if more data is required */
1124 if ((sz_copied < buf_len) && /* didn't get all requested data */
1125 (!skb_queue_empty(&sk->sk_receive_queue) ||
1126 (sz_copied < target)) && /* and more is ready or required */
1127 (!(flags & MSG_PEEK)) && /* and aren't just peeking at data */
1128 (!err)) /* and haven't reached a FIN */
1133 return sz_copied ? sz_copied : res;
1137 * tipc_write_space - wake up thread if port congestion is released
1140 static void tipc_write_space(struct sock *sk)
1142 struct socket_wq *wq;
1145 wq = rcu_dereference(sk->sk_wq);
1146 if (wq_has_sleeper(wq))
1147 wake_up_interruptible_sync_poll(&wq->wait, POLLOUT |
1148 POLLWRNORM | POLLWRBAND);
1153 * tipc_data_ready - wake up threads to indicate messages have been received
1155 * @len: the length of messages
1157 static void tipc_data_ready(struct sock *sk, int len)
1159 struct socket_wq *wq;
1162 wq = rcu_dereference(sk->sk_wq);
1163 if (wq_has_sleeper(wq))
1164 wake_up_interruptible_sync_poll(&wq->wait, POLLIN |
1165 POLLRDNORM | POLLRDBAND);
1170 * rx_queue_full - determine if receive queue can accept another message
1171 * @msg: message to be added to queue
1172 * @queue_size: current size of queue
1173 * @base: nominal maximum size of queue
1175 * Returns 1 if queue is unable to accept message, 0 otherwise
1177 static int rx_queue_full(struct tipc_msg *msg, u32 queue_size, u32 base)
1180 u32 imp = msg_importance(msg);
1182 if (imp == TIPC_LOW_IMPORTANCE)
1184 else if (imp == TIPC_MEDIUM_IMPORTANCE)
1185 threshold = base * 2;
1186 else if (imp == TIPC_HIGH_IMPORTANCE)
1187 threshold = base * 100;
1191 if (msg_connected(msg))
1194 return queue_size >= threshold;
1198 * filter_rcv - validate incoming message
1202 * Enqueues message on receive queue if acceptable; optionally handles
1203 * disconnect indication for a connected socket.
1205 * Called with socket lock already taken; port lock may also be taken.
1207 * Returns TIPC error status code (TIPC_OK if message is not to be rejected)
1209 static u32 filter_rcv(struct sock *sk, struct sk_buff *buf)
1211 struct socket *sock = sk->sk_socket;
1212 struct tipc_msg *msg = buf_msg(buf);
1215 /* Reject message if it is wrong sort of message for socket */
1216 if (msg_type(msg) > TIPC_DIRECT_MSG)
1217 return TIPC_ERR_NO_PORT;
1219 if (sock->state == SS_READY) {
1220 if (msg_connected(msg))
1221 return TIPC_ERR_NO_PORT;
1224 return TIPC_ERR_NO_PORT;
1225 if (sock->state == SS_CONNECTED) {
1226 if (!msg_connected(msg) ||
1227 !tipc_port_peer_msg(tipc_sk_port(sk), msg))
1228 return TIPC_ERR_NO_PORT;
1229 } else if (sock->state == SS_CONNECTING) {
1230 if (!msg_connected(msg) && (msg_errcode(msg) == 0))
1231 return TIPC_ERR_NO_PORT;
1232 } else if (sock->state == SS_LISTENING) {
1233 if (msg_connected(msg) || msg_errcode(msg))
1234 return TIPC_ERR_NO_PORT;
1235 } else if (sock->state == SS_DISCONNECTING) {
1236 return TIPC_ERR_NO_PORT;
1237 } else /* (sock->state == SS_UNCONNECTED) */ {
1238 if (msg_connected(msg) || msg_errcode(msg))
1239 return TIPC_ERR_NO_PORT;
1243 /* Reject message if there isn't room to queue it */
1244 recv_q_len = (u32)atomic_read(&tipc_queue_size);
1245 if (unlikely(recv_q_len >= OVERLOAD_LIMIT_BASE)) {
1246 if (rx_queue_full(msg, recv_q_len, OVERLOAD_LIMIT_BASE))
1247 return TIPC_ERR_OVERLOAD;
1249 recv_q_len = skb_queue_len(&sk->sk_receive_queue);
1250 if (unlikely(recv_q_len >= (OVERLOAD_LIMIT_BASE / 2))) {
1251 if (rx_queue_full(msg, recv_q_len, OVERLOAD_LIMIT_BASE / 2))
1252 return TIPC_ERR_OVERLOAD;
1255 /* Enqueue message (finally!) */
1256 TIPC_SKB_CB(buf)->handle = 0;
1257 atomic_inc(&tipc_queue_size);
1258 __skb_queue_tail(&sk->sk_receive_queue, buf);
1260 /* Initiate connection termination for an incoming 'FIN' */
1261 if (unlikely(msg_errcode(msg) && (sock->state == SS_CONNECTED))) {
1262 sock->state = SS_DISCONNECTING;
1263 tipc_disconnect_port(tipc_sk_port(sk));
1266 sk->sk_data_ready(sk, 0);
1271 * backlog_rcv - handle incoming message from backlog queue
1275 * Caller must hold socket lock, but not port lock.
1279 static int backlog_rcv(struct sock *sk, struct sk_buff *buf)
1283 res = filter_rcv(sk, buf);
1285 tipc_reject_msg(buf, res);
1290 * dispatch - handle incoming message
1291 * @tport: TIPC port that received message
1294 * Called with port lock already taken.
1296 * Returns TIPC error status code (TIPC_OK if message is not to be rejected)
1298 static u32 dispatch(struct tipc_port *tport, struct sk_buff *buf)
1300 struct sock *sk = (struct sock *)tport->usr_handle;
1304 * Process message if socket is unlocked; otherwise add to backlog queue
1306 * This code is based on sk_receive_skb(), but must be distinct from it
1307 * since a TIPC-specific filter/reject mechanism is utilized
1310 if (!sock_owned_by_user(sk)) {
1311 res = filter_rcv(sk, buf);
1313 if (sk_add_backlog(sk, buf, sk->sk_rcvbuf))
1314 res = TIPC_ERR_OVERLOAD;
1324 * wakeupdispatch - wake up port after congestion
1325 * @tport: port to wakeup
1327 * Called with port lock already taken.
1329 static void wakeupdispatch(struct tipc_port *tport)
1331 struct sock *sk = (struct sock *)tport->usr_handle;
1333 sk->sk_write_space(sk);
1337 * connect - establish a connection to another TIPC port
1338 * @sock: socket structure
1339 * @dest: socket address for destination port
1340 * @destlen: size of socket address data structure
1341 * @flags: file-related flags associated with socket
1343 * Returns 0 on success, errno otherwise
1345 static int connect(struct socket *sock, struct sockaddr *dest, int destlen,
1348 struct sock *sk = sock->sk;
1349 struct sockaddr_tipc *dst = (struct sockaddr_tipc *)dest;
1350 struct msghdr m = {NULL,};
1351 struct sk_buff *buf;
1352 struct tipc_msg *msg;
1353 unsigned int timeout;
1358 /* For now, TIPC does not allow use of connect() with DGRAM/RDM types */
1359 if (sock->state == SS_READY) {
1364 /* For now, TIPC does not support the non-blocking form of connect() */
1365 if (flags & O_NONBLOCK) {
1370 /* Issue Posix-compliant error code if socket is in the wrong state */
1371 if (sock->state == SS_LISTENING) {
1375 if (sock->state == SS_CONNECTING) {
1379 if (sock->state != SS_UNCONNECTED) {
1385 * Reject connection attempt using multicast address
1387 * Note: send_msg() validates the rest of the address fields,
1388 * so there's no need to do it here
1390 if (dst->addrtype == TIPC_ADDR_MCAST) {
1395 /* Reject any messages already in receive queue (very unlikely) */
1396 reject_rx_queue(sk);
1398 /* Send a 'SYN-' to destination */
1400 m.msg_namelen = destlen;
1401 res = send_msg(NULL, sock, &m, 0);
1405 /* Wait until an 'ACK' or 'RST' arrives, or a timeout occurs */
1406 timeout = tipc_sk(sk)->conn_timeout;
1408 res = wait_event_interruptible_timeout(*sk_sleep(sk),
1409 (!skb_queue_empty(&sk->sk_receive_queue) ||
1410 (sock->state != SS_CONNECTING)),
1411 timeout ? (long)msecs_to_jiffies(timeout)
1412 : MAX_SCHEDULE_TIMEOUT);
1416 buf = skb_peek(&sk->sk_receive_queue);
1419 res = auto_connect(sock, msg);
1421 if (!msg_data_sz(msg))
1422 advance_rx_queue(sk);
1425 if (sock->state == SS_CONNECTED)
1428 res = -ECONNREFUSED;
1434 ; /* leave "res" unchanged */
1435 sock->state = SS_DISCONNECTING;
1444 * listen - allow socket to listen for incoming connections
1445 * @sock: socket structure
1448 * Returns 0 on success, errno otherwise
1450 static int listen(struct socket *sock, int len)
1452 struct sock *sk = sock->sk;
1457 if (sock->state != SS_UNCONNECTED)
1460 sock->state = SS_LISTENING;
1469 * accept - wait for connection request
1470 * @sock: listening socket
1471 * @newsock: new socket that is to be connected
1472 * @flags: file-related flags associated with socket
1474 * Returns 0 on success, errno otherwise
1476 static int accept(struct socket *sock, struct socket *new_sock, int flags)
1478 struct sock *sk = sock->sk;
1479 struct sk_buff *buf;
1484 if (sock->state != SS_LISTENING) {
1489 while (skb_queue_empty(&sk->sk_receive_queue)) {
1490 if (flags & O_NONBLOCK) {
1495 res = wait_event_interruptible(*sk_sleep(sk),
1496 (!skb_queue_empty(&sk->sk_receive_queue)));
1502 buf = skb_peek(&sk->sk_receive_queue);
1504 res = tipc_create(sock_net(sock->sk), new_sock, 0, 0);
1506 struct sock *new_sk = new_sock->sk;
1507 struct tipc_sock *new_tsock = tipc_sk(new_sk);
1508 struct tipc_port *new_tport = new_tsock->p;
1509 u32 new_ref = new_tport->ref;
1510 struct tipc_msg *msg = buf_msg(buf);
1515 * Reject any stray messages received by new socket
1516 * before the socket lock was taken (very, very unlikely)
1518 reject_rx_queue(new_sk);
1520 /* Connect new socket to it's peer */
1521 new_tsock->peer_name.ref = msg_origport(msg);
1522 new_tsock->peer_name.node = msg_orignode(msg);
1523 tipc_connect2port(new_ref, &new_tsock->peer_name);
1524 new_sock->state = SS_CONNECTED;
1526 tipc_set_portimportance(new_ref, msg_importance(msg));
1527 if (msg_named(msg)) {
1528 new_tport->conn_type = msg_nametype(msg);
1529 new_tport->conn_instance = msg_nameinst(msg);
1533 * Respond to 'SYN-' by discarding it & returning 'ACK'-.
1534 * Respond to 'SYN+' by queuing it on new socket.
1536 if (!msg_data_sz(msg)) {
1537 struct msghdr m = {NULL,};
1539 advance_rx_queue(sk);
1540 send_packet(NULL, new_sock, &m, 0);
1542 __skb_dequeue(&sk->sk_receive_queue);
1543 __skb_queue_head(&new_sk->sk_receive_queue, buf);
1545 release_sock(new_sk);
1553 * shutdown - shutdown socket connection
1554 * @sock: socket structure
1555 * @how: direction to close (must be SHUT_RDWR)
1557 * Terminates connection (if necessary), then purges socket's receive queue.
1559 * Returns 0 on success, errno otherwise
1561 static int shutdown(struct socket *sock, int how)
1563 struct sock *sk = sock->sk;
1564 struct tipc_port *tport = tipc_sk_port(sk);
1565 struct sk_buff *buf;
1568 if (how != SHUT_RDWR)
1573 switch (sock->state) {
1578 /* Disconnect and send a 'FIN+' or 'FIN-' message to peer */
1579 buf = __skb_dequeue(&sk->sk_receive_queue);
1581 atomic_dec(&tipc_queue_size);
1582 if (TIPC_SKB_CB(buf)->handle != 0) {
1586 tipc_disconnect(tport->ref);
1587 tipc_reject_msg(buf, TIPC_CONN_SHUTDOWN);
1589 tipc_shutdown(tport->ref);
1592 sock->state = SS_DISCONNECTING;
1596 case SS_DISCONNECTING:
1598 /* Discard any unreceived messages; wake up sleeping tasks */
1599 discard_rx_queue(sk);
1600 if (waitqueue_active(sk_sleep(sk)))
1601 wake_up_interruptible(sk_sleep(sk));
1614 * setsockopt - set socket option
1615 * @sock: socket structure
1616 * @lvl: option level
1617 * @opt: option identifier
1618 * @ov: pointer to new option value
1619 * @ol: length of option value
1621 * For stream sockets only, accepts and ignores all IPPROTO_TCP options
1622 * (to ease compatibility).
1624 * Returns 0 on success, errno otherwise
1626 static int setsockopt(struct socket *sock,
1627 int lvl, int opt, char __user *ov, unsigned int ol)
1629 struct sock *sk = sock->sk;
1630 struct tipc_port *tport = tipc_sk_port(sk);
1634 if ((lvl == IPPROTO_TCP) && (sock->type == SOCK_STREAM))
1636 if (lvl != SOL_TIPC)
1637 return -ENOPROTOOPT;
1638 if (ol < sizeof(value))
1640 res = get_user(value, (u32 __user *)ov);
1647 case TIPC_IMPORTANCE:
1648 res = tipc_set_portimportance(tport->ref, value);
1650 case TIPC_SRC_DROPPABLE:
1651 if (sock->type != SOCK_STREAM)
1652 res = tipc_set_portunreliable(tport->ref, value);
1656 case TIPC_DEST_DROPPABLE:
1657 res = tipc_set_portunreturnable(tport->ref, value);
1659 case TIPC_CONN_TIMEOUT:
1660 tipc_sk(sk)->conn_timeout = value;
1661 /* no need to set "res", since already 0 at this point */
1673 * getsockopt - get socket option
1674 * @sock: socket structure
1675 * @lvl: option level
1676 * @opt: option identifier
1677 * @ov: receptacle for option value
1678 * @ol: receptacle for length of option value
1680 * For stream sockets only, returns 0 length result for all IPPROTO_TCP options
1681 * (to ease compatibility).
1683 * Returns 0 on success, errno otherwise
1685 static int getsockopt(struct socket *sock,
1686 int lvl, int opt, char __user *ov, int __user *ol)
1688 struct sock *sk = sock->sk;
1689 struct tipc_port *tport = tipc_sk_port(sk);
1694 if ((lvl == IPPROTO_TCP) && (sock->type == SOCK_STREAM))
1695 return put_user(0, ol);
1696 if (lvl != SOL_TIPC)
1697 return -ENOPROTOOPT;
1698 res = get_user(len, ol);
1705 case TIPC_IMPORTANCE:
1706 res = tipc_portimportance(tport->ref, &value);
1708 case TIPC_SRC_DROPPABLE:
1709 res = tipc_portunreliable(tport->ref, &value);
1711 case TIPC_DEST_DROPPABLE:
1712 res = tipc_portunreturnable(tport->ref, &value);
1714 case TIPC_CONN_TIMEOUT:
1715 value = tipc_sk(sk)->conn_timeout;
1716 /* no need to set "res", since already 0 at this point */
1718 case TIPC_NODE_RECVQ_DEPTH:
1719 value = (u32)atomic_read(&tipc_queue_size);
1721 case TIPC_SOCK_RECVQ_DEPTH:
1722 value = skb_queue_len(&sk->sk_receive_queue);
1731 return res; /* "get" failed */
1733 if (len < sizeof(value))
1736 if (copy_to_user(ov, &value, sizeof(value)))
1739 return put_user(sizeof(value), ol);
1742 /* Protocol switches for the various types of TIPC sockets */
1744 static const struct proto_ops msg_ops = {
1745 .owner = THIS_MODULE,
1750 .socketpair = sock_no_socketpair,
1751 .accept = sock_no_accept,
1752 .getname = get_name,
1754 .ioctl = sock_no_ioctl,
1755 .listen = sock_no_listen,
1756 .shutdown = shutdown,
1757 .setsockopt = setsockopt,
1758 .getsockopt = getsockopt,
1759 .sendmsg = send_msg,
1760 .recvmsg = recv_msg,
1761 .mmap = sock_no_mmap,
1762 .sendpage = sock_no_sendpage
1765 static const struct proto_ops packet_ops = {
1766 .owner = THIS_MODULE,
1771 .socketpair = sock_no_socketpair,
1773 .getname = get_name,
1775 .ioctl = sock_no_ioctl,
1777 .shutdown = shutdown,
1778 .setsockopt = setsockopt,
1779 .getsockopt = getsockopt,
1780 .sendmsg = send_packet,
1781 .recvmsg = recv_msg,
1782 .mmap = sock_no_mmap,
1783 .sendpage = sock_no_sendpage
1786 static const struct proto_ops stream_ops = {
1787 .owner = THIS_MODULE,
1792 .socketpair = sock_no_socketpair,
1794 .getname = get_name,
1796 .ioctl = sock_no_ioctl,
1798 .shutdown = shutdown,
1799 .setsockopt = setsockopt,
1800 .getsockopt = getsockopt,
1801 .sendmsg = send_stream,
1802 .recvmsg = recv_stream,
1803 .mmap = sock_no_mmap,
1804 .sendpage = sock_no_sendpage
1807 static const struct net_proto_family tipc_family_ops = {
1808 .owner = THIS_MODULE,
1810 .create = tipc_create
1813 static struct proto tipc_proto = {
1815 .owner = THIS_MODULE,
1816 .obj_size = sizeof(struct tipc_sock)
1820 * tipc_socket_init - initialize TIPC socket interface
1822 * Returns 0 on success, errno otherwise
1824 int tipc_socket_init(void)
1828 res = proto_register(&tipc_proto, 1);
1830 pr_err("Failed to register TIPC protocol type\n");
1834 res = sock_register(&tipc_family_ops);
1836 pr_err("Failed to register TIPC socket type\n");
1837 proto_unregister(&tipc_proto);
1841 sockets_enabled = 1;
1847 * tipc_socket_stop - stop TIPC socket interface
1849 void tipc_socket_stop(void)
1851 if (!sockets_enabled)
1854 sockets_enabled = 0;
1855 sock_unregister(tipc_family_ops.family);
1856 proto_unregister(&tipc_proto);