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
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) {
447 if (!tipc_sk_port(sk)->congested)
452 if (!skb_queue_empty(&sk->sk_receive_queue))
453 mask |= (POLLIN | POLLRDNORM);
455 case SS_DISCONNECTING:
456 mask = (POLLIN | POLLRDNORM | POLLHUP);
464 * dest_name_check - verify user is permitted to send to specified port name
465 * @dest: destination address
466 * @m: descriptor for message to be sent
468 * Prevents restricted configuration commands from being issued by
469 * unauthorized users.
471 * 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 (!m->msg_iovlen || (m->msg_iov[0].iov_len < sizeof(hdr)))
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
508 static int send_msg(struct kiocb *iocb, struct socket *sock,
509 struct msghdr *m, size_t total_len)
511 struct sock *sk = sock->sk;
512 struct tipc_port *tport = tipc_sk_port(sk);
513 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)))
523 if ((total_len > TIPC_MAX_USER_MSG_SIZE) ||
524 (m->msg_iovlen > (unsigned int)INT_MAX))
530 needs_conn = (sock->state != SS_READY);
531 if (unlikely(needs_conn)) {
532 if (sock->state == SS_LISTENING) {
536 if (sock->state != SS_UNCONNECTED) {
540 if ((tport->published) ||
541 ((sock->type == SOCK_STREAM) && (total_len != 0))) {
545 if (dest->addrtype == TIPC_ADDR_NAME) {
546 tport->conn_type = dest->addr.name.name.type;
547 tport->conn_instance = dest->addr.name.name.instance;
550 /* Abort any pending connection attempts (very unlikely) */
554 timeout_val = sock_sndtimeo(sk, m->msg_flags & MSG_DONTWAIT);
557 if (dest->addrtype == TIPC_ADDR_NAME) {
558 res = dest_name_check(dest, m);
561 res = tipc_send2name(tport->ref,
562 &dest->addr.name.name,
563 dest->addr.name.domain,
567 } else if (dest->addrtype == TIPC_ADDR_ID) {
568 res = tipc_send2port(tport->ref,
573 } else if (dest->addrtype == TIPC_ADDR_MCAST) {
578 res = dest_name_check(dest, m);
581 res = tipc_multicast(tport->ref,
587 if (likely(res != -ELINKCONG)) {
588 if (needs_conn && (res >= 0))
589 sock->state = SS_CONNECTING;
592 if (timeout_val <= 0L) {
593 res = timeout_val ? timeout_val : -EWOULDBLOCK;
597 timeout_val = wait_event_interruptible_timeout(*sk_sleep(sk),
598 !tport->congested, timeout_val);
609 * send_packet - send a connection-oriented message
610 * @iocb: if NULL, indicates that socket lock is already held
611 * @sock: socket structure
612 * @m: message to send
613 * @total_len: length of message
615 * Used for SOCK_SEQPACKET messages and SOCK_STREAM data.
617 * Returns the number of bytes sent on success, or errno otherwise
619 static int send_packet(struct kiocb *iocb, struct socket *sock,
620 struct msghdr *m, size_t total_len)
622 struct sock *sk = sock->sk;
623 struct tipc_port *tport = tipc_sk_port(sk);
624 struct sockaddr_tipc *dest = (struct sockaddr_tipc *)m->msg_name;
628 /* Handle implied connection establishment */
630 return send_msg(iocb, sock, m, total_len);
632 if ((total_len > TIPC_MAX_USER_MSG_SIZE) ||
633 (m->msg_iovlen > (unsigned int)INT_MAX))
639 timeout_val = sock_sndtimeo(sk, m->msg_flags & MSG_DONTWAIT);
642 if (unlikely(sock->state != SS_CONNECTED)) {
643 if (sock->state == SS_DISCONNECTING)
650 res = tipc_send(tport->ref, m->msg_iovlen, m->msg_iov,
652 if (likely(res != -ELINKCONG))
654 if (timeout_val <= 0L) {
655 res = timeout_val ? timeout_val : -EWOULDBLOCK;
659 timeout_val = wait_event_interruptible_timeout(*sk_sleep(sk),
660 (!tport->congested || !tport->connected), timeout_val);
670 * send_stream - send stream-oriented data
672 * @sock: socket structure
674 * @total_len: total length of data to be sent
676 * Used for SOCK_STREAM data.
678 * Returns the number of bytes sent on success (or partial success),
679 * or errno if no data sent
681 static int send_stream(struct kiocb *iocb, struct socket *sock,
682 struct msghdr *m, size_t total_len)
684 struct sock *sk = sock->sk;
685 struct tipc_port *tport = tipc_sk_port(sk);
686 struct msghdr my_msg;
688 struct iovec *curr_iov;
690 char __user *curr_start;
699 /* Handle special cases where there is no connection */
700 if (unlikely(sock->state != SS_CONNECTED)) {
701 if (sock->state == SS_UNCONNECTED) {
702 res = send_packet(NULL, sock, m, total_len);
704 } else if (sock->state == SS_DISCONNECTING) {
713 if (unlikely(m->msg_name)) {
718 if ((total_len > (unsigned int)INT_MAX) ||
719 (m->msg_iovlen > (unsigned int)INT_MAX)) {
725 * Send each iovec entry using one or more messages
727 * Note: This algorithm is good for the most likely case
728 * (i.e. one large iovec entry), but could be improved to pass sets
729 * of small iovec entries into send_packet().
731 curr_iov = m->msg_iov;
732 curr_iovlen = m->msg_iovlen;
733 my_msg.msg_iov = &my_iov;
734 my_msg.msg_iovlen = 1;
735 my_msg.msg_flags = m->msg_flags;
736 my_msg.msg_name = NULL;
739 hdr_size = msg_hdr_sz(&tport->phdr);
741 while (curr_iovlen--) {
742 curr_start = curr_iov->iov_base;
743 curr_left = curr_iov->iov_len;
746 bytes_to_send = tport->max_pkt - hdr_size;
747 if (bytes_to_send > TIPC_MAX_USER_MSG_SIZE)
748 bytes_to_send = TIPC_MAX_USER_MSG_SIZE;
749 if (curr_left < bytes_to_send)
750 bytes_to_send = curr_left;
751 my_iov.iov_base = curr_start;
752 my_iov.iov_len = bytes_to_send;
753 res = send_packet(NULL, sock, &my_msg, bytes_to_send);
759 curr_left -= bytes_to_send;
760 curr_start += bytes_to_send;
761 bytes_sent += bytes_to_send;
773 * auto_connect - complete connection setup to a remote port
774 * @sock: socket structure
775 * @msg: peer's response message
777 * Returns 0 on success, errno otherwise
779 static int auto_connect(struct socket *sock, struct tipc_msg *msg)
781 struct tipc_sock *tsock = tipc_sk(sock->sk);
783 if (msg_errcode(msg)) {
784 sock->state = SS_DISCONNECTING;
785 return -ECONNREFUSED;
788 tsock->peer_name.ref = msg_origport(msg);
789 tsock->peer_name.node = msg_orignode(msg);
790 tipc_connect2port(tsock->p->ref, &tsock->peer_name);
791 tipc_set_portimportance(tsock->p->ref, msg_importance(msg));
792 sock->state = SS_CONNECTED;
797 * set_orig_addr - capture sender's address for received message
798 * @m: descriptor for message info
799 * @msg: received message header
801 * Note: Address is not captured if not requested by receiver.
803 static void set_orig_addr(struct msghdr *m, struct tipc_msg *msg)
805 struct sockaddr_tipc *addr = (struct sockaddr_tipc *)m->msg_name;
808 addr->family = AF_TIPC;
809 addr->addrtype = TIPC_ADDR_ID;
810 addr->addr.id.ref = msg_origport(msg);
811 addr->addr.id.node = msg_orignode(msg);
812 addr->addr.name.domain = 0; /* could leave uninitialized */
813 addr->scope = 0; /* could leave uninitialized */
814 m->msg_namelen = sizeof(struct sockaddr_tipc);
819 * anc_data_recv - optionally capture ancillary data for received message
820 * @m: descriptor for message info
821 * @msg: received message header
822 * @tport: TIPC port associated with message
824 * Note: Ancillary data is not captured if not requested by receiver.
826 * Returns 0 if successful, otherwise errno
828 static int anc_data_recv(struct msghdr *m, struct tipc_msg *msg,
829 struct tipc_port *tport)
837 if (likely(m->msg_controllen == 0))
840 /* Optionally capture errored message object(s) */
841 err = msg ? msg_errcode(msg) : 0;
844 anc_data[1] = msg_data_sz(msg);
845 res = put_cmsg(m, SOL_TIPC, TIPC_ERRINFO, 8, anc_data);
849 res = put_cmsg(m, SOL_TIPC, TIPC_RETDATA, anc_data[1],
856 /* Optionally capture message destination object */
857 dest_type = msg ? msg_type(msg) : TIPC_DIRECT_MSG;
861 anc_data[0] = msg_nametype(msg);
862 anc_data[1] = msg_namelower(msg);
863 anc_data[2] = msg_namelower(msg);
867 anc_data[0] = msg_nametype(msg);
868 anc_data[1] = msg_namelower(msg);
869 anc_data[2] = msg_nameupper(msg);
872 has_name = (tport->conn_type != 0);
873 anc_data[0] = tport->conn_type;
874 anc_data[1] = tport->conn_instance;
875 anc_data[2] = tport->conn_instance;
881 res = put_cmsg(m, SOL_TIPC, TIPC_DESTNAME, 12, anc_data);
890 * recv_msg - receive packet-oriented message
892 * @m: descriptor for message info
893 * @buf_len: total size of user buffer area
894 * @flags: receive flags
896 * Used for SOCK_DGRAM, SOCK_RDM, and SOCK_SEQPACKET messages.
897 * If the complete message doesn't fit in user area, truncate it.
899 * Returns size of returned message data, errno otherwise
901 static int recv_msg(struct kiocb *iocb, struct socket *sock,
902 struct msghdr *m, size_t buf_len, int flags)
904 struct sock *sk = sock->sk;
905 struct tipc_port *tport = tipc_sk_port(sk);
907 struct tipc_msg *msg;
913 /* Catch invalid receive requests */
914 if (unlikely(!buf_len))
919 if (unlikely(sock->state == SS_UNCONNECTED)) {
924 timeout = sock_rcvtimeo(sk, flags & MSG_DONTWAIT);
927 /* Look for a message in receive queue; wait if necessary */
928 while (skb_queue_empty(&sk->sk_receive_queue)) {
929 if (sock->state == SS_DISCONNECTING) {
934 res = timeout ? timeout : -EWOULDBLOCK;
938 timeout = wait_event_interruptible_timeout(*sk_sleep(sk),
944 /* Look at first message in receive queue */
945 buf = skb_peek(&sk->sk_receive_queue);
947 sz = msg_data_sz(msg);
948 err = msg_errcode(msg);
950 /* Complete connection setup for an implied connect */
951 if (unlikely(sock->state == SS_CONNECTING)) {
952 res = auto_connect(sock, msg);
957 /* Discard an empty non-errored message & try again */
958 if ((!sz) && (!err)) {
959 advance_rx_queue(sk);
963 /* Capture sender's address (optional) */
964 set_orig_addr(m, msg);
966 /* Capture ancillary data (optional) */
967 res = anc_data_recv(m, msg, tport);
971 /* Capture message data (if valid) & compute return value (always) */
973 if (unlikely(buf_len < sz)) {
975 m->msg_flags |= MSG_TRUNC;
977 res = skb_copy_datagram_iovec(buf, msg_hdr_sz(msg),
983 if ((sock->state == SS_READY) ||
984 ((err == TIPC_CONN_SHUTDOWN) || m->msg_control))
990 /* Consume received message (optional) */
991 if (likely(!(flags & MSG_PEEK))) {
992 if ((sock->state != SS_READY) &&
993 (++tport->conn_unacked >= TIPC_FLOW_CONTROL_WIN))
994 tipc_acknowledge(tport->ref, tport->conn_unacked);
995 advance_rx_queue(sk);
1003 * recv_stream - receive stream-oriented data
1005 * @m: descriptor for message info
1006 * @buf_len: total size of user buffer area
1007 * @flags: receive flags
1009 * Used for SOCK_STREAM messages only. If not enough data is available
1010 * will optionally wait for more; never truncates data.
1012 * Returns size of returned message data, errno otherwise
1014 static int recv_stream(struct kiocb *iocb, struct socket *sock,
1015 struct msghdr *m, size_t buf_len, int flags)
1017 struct sock *sk = sock->sk;
1018 struct tipc_port *tport = tipc_sk_port(sk);
1019 struct sk_buff *buf;
1020 struct tipc_msg *msg;
1023 int sz_to_copy, target, needed;
1028 /* Catch invalid receive attempts */
1029 if (unlikely(!buf_len))
1034 if (unlikely((sock->state == SS_UNCONNECTED) ||
1035 (sock->state == SS_CONNECTING))) {
1040 target = sock_rcvlowat(sk, flags & MSG_WAITALL, buf_len);
1041 timeout = sock_rcvtimeo(sk, flags & MSG_DONTWAIT);
1044 /* Look for a message in receive queue; wait if necessary */
1045 while (skb_queue_empty(&sk->sk_receive_queue)) {
1046 if (sock->state == SS_DISCONNECTING) {
1050 if (timeout <= 0L) {
1051 res = timeout ? timeout : -EWOULDBLOCK;
1055 timeout = wait_event_interruptible_timeout(*sk_sleep(sk),
1056 tipc_rx_ready(sock),
1061 /* Look at first message in receive queue */
1062 buf = skb_peek(&sk->sk_receive_queue);
1064 sz = msg_data_sz(msg);
1065 err = msg_errcode(msg);
1067 /* Discard an empty non-errored message & try again */
1068 if ((!sz) && (!err)) {
1069 advance_rx_queue(sk);
1073 /* Optionally capture sender's address & ancillary data of first msg */
1074 if (sz_copied == 0) {
1075 set_orig_addr(m, msg);
1076 res = anc_data_recv(m, msg, tport);
1081 /* Capture message data (if valid) & compute return value (always) */
1083 u32 offset = (u32)(unsigned long)(TIPC_SKB_CB(buf)->handle);
1086 needed = (buf_len - sz_copied);
1087 sz_to_copy = (sz <= needed) ? sz : needed;
1089 res = skb_copy_datagram_iovec(buf, msg_hdr_sz(msg) + offset,
1090 m->msg_iov, sz_to_copy);
1094 sz_copied += sz_to_copy;
1096 if (sz_to_copy < sz) {
1097 if (!(flags & MSG_PEEK))
1098 TIPC_SKB_CB(buf)->handle =
1099 (void *)(unsigned long)(offset + sz_to_copy);
1104 goto exit; /* can't add error msg to valid data */
1106 if ((err == TIPC_CONN_SHUTDOWN) || m->msg_control)
1112 /* Consume received message (optional) */
1113 if (likely(!(flags & MSG_PEEK))) {
1114 if (unlikely(++tport->conn_unacked >= TIPC_FLOW_CONTROL_WIN))
1115 tipc_acknowledge(tport->ref, tport->conn_unacked);
1116 advance_rx_queue(sk);
1119 /* Loop around if more data is required */
1120 if ((sz_copied < buf_len) && /* didn't get all requested data */
1121 (!skb_queue_empty(&sk->sk_receive_queue) ||
1122 (sz_copied < target)) && /* and more is ready or required */
1123 (!(flags & MSG_PEEK)) && /* and aren't just peeking at data */
1124 (!err)) /* and haven't reached a FIN */
1129 return sz_copied ? sz_copied : res;
1133 * tipc_write_space - wake up thread if port congestion is released
1136 static void tipc_write_space(struct sock *sk)
1138 struct socket_wq *wq;
1141 wq = rcu_dereference(sk->sk_wq);
1142 if (wq_has_sleeper(wq))
1143 wake_up_interruptible_sync_poll(&wq->wait, POLLOUT |
1144 POLLWRNORM | POLLWRBAND);
1149 * tipc_data_ready - wake up threads to indicate messages have been received
1151 * @len: the length of messages
1153 static void tipc_data_ready(struct sock *sk, int len)
1155 struct socket_wq *wq;
1158 wq = rcu_dereference(sk->sk_wq);
1159 if (wq_has_sleeper(wq))
1160 wake_up_interruptible_sync_poll(&wq->wait, POLLIN |
1161 POLLRDNORM | POLLRDBAND);
1166 * rx_queue_full - determine if receive queue can accept another message
1167 * @msg: message to be added to queue
1168 * @queue_size: current size of queue
1169 * @base: nominal maximum size of queue
1171 * Returns 1 if queue is unable to accept message, 0 otherwise
1173 static int rx_queue_full(struct tipc_msg *msg, u32 queue_size, u32 base)
1176 u32 imp = msg_importance(msg);
1178 if (imp == TIPC_LOW_IMPORTANCE)
1180 else if (imp == TIPC_MEDIUM_IMPORTANCE)
1181 threshold = base * 2;
1182 else if (imp == TIPC_HIGH_IMPORTANCE)
1183 threshold = base * 100;
1187 if (msg_connected(msg))
1190 return queue_size >= threshold;
1194 * filter_rcv - validate incoming message
1198 * Enqueues message on receive queue if acceptable; optionally handles
1199 * disconnect indication for a connected socket.
1201 * Called with socket lock already taken; port lock may also be taken.
1203 * Returns TIPC error status code (TIPC_OK if message is not to be rejected)
1205 static u32 filter_rcv(struct sock *sk, struct sk_buff *buf)
1207 struct socket *sock = sk->sk_socket;
1208 struct tipc_msg *msg = buf_msg(buf);
1211 /* Reject message if it is wrong sort of message for socket */
1212 if (msg_type(msg) > TIPC_DIRECT_MSG)
1213 return TIPC_ERR_NO_PORT;
1215 if (sock->state == SS_READY) {
1216 if (msg_connected(msg))
1217 return TIPC_ERR_NO_PORT;
1220 return TIPC_ERR_NO_PORT;
1221 if (sock->state == SS_CONNECTED) {
1222 if (!msg_connected(msg) ||
1223 !tipc_port_peer_msg(tipc_sk_port(sk), msg))
1224 return TIPC_ERR_NO_PORT;
1225 } else if (sock->state == SS_CONNECTING) {
1226 if (!msg_connected(msg) && (msg_errcode(msg) == 0))
1227 return TIPC_ERR_NO_PORT;
1228 } else if (sock->state == SS_LISTENING) {
1229 if (msg_connected(msg) || msg_errcode(msg))
1230 return TIPC_ERR_NO_PORT;
1231 } else if (sock->state == SS_DISCONNECTING) {
1232 return TIPC_ERR_NO_PORT;
1233 } else /* (sock->state == SS_UNCONNECTED) */ {
1234 if (msg_connected(msg) || msg_errcode(msg))
1235 return TIPC_ERR_NO_PORT;
1239 /* Reject message if there isn't room to queue it */
1240 recv_q_len = (u32)atomic_read(&tipc_queue_size);
1241 if (unlikely(recv_q_len >= OVERLOAD_LIMIT_BASE)) {
1242 if (rx_queue_full(msg, recv_q_len, OVERLOAD_LIMIT_BASE))
1243 return TIPC_ERR_OVERLOAD;
1245 recv_q_len = skb_queue_len(&sk->sk_receive_queue);
1246 if (unlikely(recv_q_len >= (OVERLOAD_LIMIT_BASE / 2))) {
1247 if (rx_queue_full(msg, recv_q_len, OVERLOAD_LIMIT_BASE / 2))
1248 return TIPC_ERR_OVERLOAD;
1251 /* Enqueue message (finally!) */
1252 TIPC_SKB_CB(buf)->handle = 0;
1253 atomic_inc(&tipc_queue_size);
1254 __skb_queue_tail(&sk->sk_receive_queue, buf);
1256 /* Initiate connection termination for an incoming 'FIN' */
1257 if (unlikely(msg_errcode(msg) && (sock->state == SS_CONNECTED))) {
1258 sock->state = SS_DISCONNECTING;
1259 tipc_disconnect_port(tipc_sk_port(sk));
1262 sk->sk_data_ready(sk, 0);
1267 * backlog_rcv - handle incoming message from backlog queue
1271 * Caller must hold socket lock, but not port lock.
1275 static int backlog_rcv(struct sock *sk, struct sk_buff *buf)
1279 res = filter_rcv(sk, buf);
1281 tipc_reject_msg(buf, res);
1286 * dispatch - handle incoming message
1287 * @tport: TIPC port that received message
1290 * Called with port lock already taken.
1292 * Returns TIPC error status code (TIPC_OK if message is not to be rejected)
1294 static u32 dispatch(struct tipc_port *tport, struct sk_buff *buf)
1296 struct sock *sk = (struct sock *)tport->usr_handle;
1300 * Process message if socket is unlocked; otherwise add to backlog queue
1302 * This code is based on sk_receive_skb(), but must be distinct from it
1303 * since a TIPC-specific filter/reject mechanism is utilized
1306 if (!sock_owned_by_user(sk)) {
1307 res = filter_rcv(sk, buf);
1309 if (sk_add_backlog(sk, buf, sk->sk_rcvbuf))
1310 res = TIPC_ERR_OVERLOAD;
1320 * wakeupdispatch - wake up port after congestion
1321 * @tport: port to wakeup
1323 * Called with port lock already taken.
1325 static void wakeupdispatch(struct tipc_port *tport)
1327 struct sock *sk = (struct sock *)tport->usr_handle;
1329 sk->sk_write_space(sk);
1333 * connect - establish a connection to another TIPC port
1334 * @sock: socket structure
1335 * @dest: socket address for destination port
1336 * @destlen: size of socket address data structure
1337 * @flags: file-related flags associated with socket
1339 * Returns 0 on success, errno otherwise
1341 static int connect(struct socket *sock, struct sockaddr *dest, int destlen,
1344 struct sock *sk = sock->sk;
1345 struct sockaddr_tipc *dst = (struct sockaddr_tipc *)dest;
1346 struct msghdr m = {NULL,};
1347 struct sk_buff *buf;
1348 struct tipc_msg *msg;
1349 unsigned int timeout;
1354 /* For now, TIPC does not allow use of connect() with DGRAM/RDM types */
1355 if (sock->state == SS_READY) {
1360 /* For now, TIPC does not support the non-blocking form of connect() */
1361 if (flags & O_NONBLOCK) {
1366 /* Issue Posix-compliant error code if socket is in the wrong state */
1367 if (sock->state == SS_LISTENING) {
1371 if (sock->state == SS_CONNECTING) {
1375 if (sock->state != SS_UNCONNECTED) {
1381 * Reject connection attempt using multicast address
1383 * Note: send_msg() validates the rest of the address fields,
1384 * so there's no need to do it here
1386 if (dst->addrtype == TIPC_ADDR_MCAST) {
1391 /* Reject any messages already in receive queue (very unlikely) */
1392 reject_rx_queue(sk);
1394 /* Send a 'SYN-' to destination */
1396 m.msg_namelen = destlen;
1397 res = send_msg(NULL, sock, &m, 0);
1401 /* Wait until an 'ACK' or 'RST' arrives, or a timeout occurs */
1402 timeout = tipc_sk(sk)->conn_timeout;
1404 res = wait_event_interruptible_timeout(*sk_sleep(sk),
1405 (!skb_queue_empty(&sk->sk_receive_queue) ||
1406 (sock->state != SS_CONNECTING)),
1407 timeout ? (long)msecs_to_jiffies(timeout)
1408 : MAX_SCHEDULE_TIMEOUT);
1412 buf = skb_peek(&sk->sk_receive_queue);
1415 res = auto_connect(sock, msg);
1417 if (!msg_data_sz(msg))
1418 advance_rx_queue(sk);
1421 if (sock->state == SS_CONNECTED)
1424 res = -ECONNREFUSED;
1430 ; /* leave "res" unchanged */
1431 sock->state = SS_DISCONNECTING;
1440 * listen - allow socket to listen for incoming connections
1441 * @sock: socket structure
1444 * Returns 0 on success, errno otherwise
1446 static int listen(struct socket *sock, int len)
1448 struct sock *sk = sock->sk;
1453 if (sock->state != SS_UNCONNECTED)
1456 sock->state = SS_LISTENING;
1465 * accept - wait for connection request
1466 * @sock: listening socket
1467 * @newsock: new socket that is to be connected
1468 * @flags: file-related flags associated with socket
1470 * Returns 0 on success, errno otherwise
1472 static int accept(struct socket *sock, struct socket *new_sock, int flags)
1474 struct sock *sk = sock->sk;
1475 struct sk_buff *buf;
1480 if (sock->state != SS_LISTENING) {
1485 while (skb_queue_empty(&sk->sk_receive_queue)) {
1486 if (flags & O_NONBLOCK) {
1491 res = wait_event_interruptible(*sk_sleep(sk),
1492 (!skb_queue_empty(&sk->sk_receive_queue)));
1498 buf = skb_peek(&sk->sk_receive_queue);
1500 res = tipc_create(sock_net(sock->sk), new_sock, 0, 0);
1502 struct sock *new_sk = new_sock->sk;
1503 struct tipc_sock *new_tsock = tipc_sk(new_sk);
1504 struct tipc_port *new_tport = new_tsock->p;
1505 u32 new_ref = new_tport->ref;
1506 struct tipc_msg *msg = buf_msg(buf);
1511 * Reject any stray messages received by new socket
1512 * before the socket lock was taken (very, very unlikely)
1514 reject_rx_queue(new_sk);
1516 /* Connect new socket to it's peer */
1517 new_tsock->peer_name.ref = msg_origport(msg);
1518 new_tsock->peer_name.node = msg_orignode(msg);
1519 tipc_connect2port(new_ref, &new_tsock->peer_name);
1520 new_sock->state = SS_CONNECTED;
1522 tipc_set_portimportance(new_ref, msg_importance(msg));
1523 if (msg_named(msg)) {
1524 new_tport->conn_type = msg_nametype(msg);
1525 new_tport->conn_instance = msg_nameinst(msg);
1529 * Respond to 'SYN-' by discarding it & returning 'ACK'-.
1530 * Respond to 'SYN+' by queuing it on new socket.
1532 if (!msg_data_sz(msg)) {
1533 struct msghdr m = {NULL,};
1535 advance_rx_queue(sk);
1536 send_packet(NULL, new_sock, &m, 0);
1538 __skb_dequeue(&sk->sk_receive_queue);
1539 __skb_queue_head(&new_sk->sk_receive_queue, buf);
1541 release_sock(new_sk);
1549 * shutdown - shutdown socket connection
1550 * @sock: socket structure
1551 * @how: direction to close (must be SHUT_RDWR)
1553 * Terminates connection (if necessary), then purges socket's receive queue.
1555 * Returns 0 on success, errno otherwise
1557 static int shutdown(struct socket *sock, int how)
1559 struct sock *sk = sock->sk;
1560 struct tipc_port *tport = tipc_sk_port(sk);
1561 struct sk_buff *buf;
1564 if (how != SHUT_RDWR)
1569 switch (sock->state) {
1574 /* Disconnect and send a 'FIN+' or 'FIN-' message to peer */
1575 buf = __skb_dequeue(&sk->sk_receive_queue);
1577 atomic_dec(&tipc_queue_size);
1578 if (TIPC_SKB_CB(buf)->handle != 0) {
1582 tipc_disconnect(tport->ref);
1583 tipc_reject_msg(buf, TIPC_CONN_SHUTDOWN);
1585 tipc_shutdown(tport->ref);
1588 sock->state = SS_DISCONNECTING;
1592 case SS_DISCONNECTING:
1594 /* Discard any unreceived messages; wake up sleeping tasks */
1595 discard_rx_queue(sk);
1596 if (waitqueue_active(sk_sleep(sk)))
1597 wake_up_interruptible(sk_sleep(sk));
1610 * setsockopt - set socket option
1611 * @sock: socket structure
1612 * @lvl: option level
1613 * @opt: option identifier
1614 * @ov: pointer to new option value
1615 * @ol: length of option value
1617 * For stream sockets only, accepts and ignores all IPPROTO_TCP options
1618 * (to ease compatibility).
1620 * Returns 0 on success, errno otherwise
1622 static int setsockopt(struct socket *sock,
1623 int lvl, int opt, char __user *ov, unsigned int ol)
1625 struct sock *sk = sock->sk;
1626 struct tipc_port *tport = tipc_sk_port(sk);
1630 if ((lvl == IPPROTO_TCP) && (sock->type == SOCK_STREAM))
1632 if (lvl != SOL_TIPC)
1633 return -ENOPROTOOPT;
1634 if (ol < sizeof(value))
1636 res = get_user(value, (u32 __user *)ov);
1643 case TIPC_IMPORTANCE:
1644 res = tipc_set_portimportance(tport->ref, value);
1646 case TIPC_SRC_DROPPABLE:
1647 if (sock->type != SOCK_STREAM)
1648 res = tipc_set_portunreliable(tport->ref, value);
1652 case TIPC_DEST_DROPPABLE:
1653 res = tipc_set_portunreturnable(tport->ref, value);
1655 case TIPC_CONN_TIMEOUT:
1656 tipc_sk(sk)->conn_timeout = value;
1657 /* no need to set "res", since already 0 at this point */
1669 * getsockopt - get socket option
1670 * @sock: socket structure
1671 * @lvl: option level
1672 * @opt: option identifier
1673 * @ov: receptacle for option value
1674 * @ol: receptacle for length of option value
1676 * For stream sockets only, returns 0 length result for all IPPROTO_TCP options
1677 * (to ease compatibility).
1679 * Returns 0 on success, errno otherwise
1681 static int getsockopt(struct socket *sock,
1682 int lvl, int opt, char __user *ov, int __user *ol)
1684 struct sock *sk = sock->sk;
1685 struct tipc_port *tport = tipc_sk_port(sk);
1690 if ((lvl == IPPROTO_TCP) && (sock->type == SOCK_STREAM))
1691 return put_user(0, ol);
1692 if (lvl != SOL_TIPC)
1693 return -ENOPROTOOPT;
1694 res = get_user(len, ol);
1701 case TIPC_IMPORTANCE:
1702 res = tipc_portimportance(tport->ref, &value);
1704 case TIPC_SRC_DROPPABLE:
1705 res = tipc_portunreliable(tport->ref, &value);
1707 case TIPC_DEST_DROPPABLE:
1708 res = tipc_portunreturnable(tport->ref, &value);
1710 case TIPC_CONN_TIMEOUT:
1711 value = tipc_sk(sk)->conn_timeout;
1712 /* no need to set "res", since already 0 at this point */
1714 case TIPC_NODE_RECVQ_DEPTH:
1715 value = (u32)atomic_read(&tipc_queue_size);
1717 case TIPC_SOCK_RECVQ_DEPTH:
1718 value = skb_queue_len(&sk->sk_receive_queue);
1727 return res; /* "get" failed */
1729 if (len < sizeof(value))
1732 if (copy_to_user(ov, &value, sizeof(value)))
1735 return put_user(sizeof(value), ol);
1738 /* Protocol switches for the various types of TIPC sockets */
1740 static const struct proto_ops msg_ops = {
1741 .owner = THIS_MODULE,
1746 .socketpair = sock_no_socketpair,
1747 .accept = sock_no_accept,
1748 .getname = get_name,
1750 .ioctl = sock_no_ioctl,
1751 .listen = sock_no_listen,
1752 .shutdown = shutdown,
1753 .setsockopt = setsockopt,
1754 .getsockopt = getsockopt,
1755 .sendmsg = send_msg,
1756 .recvmsg = recv_msg,
1757 .mmap = sock_no_mmap,
1758 .sendpage = sock_no_sendpage
1761 static const struct proto_ops packet_ops = {
1762 .owner = THIS_MODULE,
1767 .socketpair = sock_no_socketpair,
1769 .getname = get_name,
1771 .ioctl = sock_no_ioctl,
1773 .shutdown = shutdown,
1774 .setsockopt = setsockopt,
1775 .getsockopt = getsockopt,
1776 .sendmsg = send_packet,
1777 .recvmsg = recv_msg,
1778 .mmap = sock_no_mmap,
1779 .sendpage = sock_no_sendpage
1782 static const struct proto_ops stream_ops = {
1783 .owner = THIS_MODULE,
1788 .socketpair = sock_no_socketpair,
1790 .getname = get_name,
1792 .ioctl = sock_no_ioctl,
1794 .shutdown = shutdown,
1795 .setsockopt = setsockopt,
1796 .getsockopt = getsockopt,
1797 .sendmsg = send_stream,
1798 .recvmsg = recv_stream,
1799 .mmap = sock_no_mmap,
1800 .sendpage = sock_no_sendpage
1803 static const struct net_proto_family tipc_family_ops = {
1804 .owner = THIS_MODULE,
1806 .create = tipc_create
1809 static struct proto tipc_proto = {
1811 .owner = THIS_MODULE,
1812 .obj_size = sizeof(struct tipc_sock)
1816 * tipc_socket_init - initialize TIPC socket interface
1818 * Returns 0 on success, errno otherwise
1820 int tipc_socket_init(void)
1824 res = proto_register(&tipc_proto, 1);
1826 pr_err("Failed to register TIPC protocol type\n");
1830 res = sock_register(&tipc_family_ops);
1832 pr_err("Failed to register TIPC socket type\n");
1833 proto_unregister(&tipc_proto);
1837 sockets_enabled = 1;
1843 * tipc_socket_stop - stop TIPC socket interface
1845 void tipc_socket_stop(void)
1847 if (!sockets_enabled)
1850 sockets_enabled = 0;
1851 sock_unregister(tipc_family_ops.family);
1852 proto_unregister(&tipc_proto);