tipc: introduce non-blocking socket connect
[linux-2.6/btrfs-unstable.git] / net / tipc / socket.c
blobdbce2745f0a8ab52bbc037eba771054778287096
1 /*
2 * net/tipc/socket.c: TIPC socket API
4 * Copyright (c) 2001-2007, 2012 Ericsson AB
5 * Copyright (c) 2004-2008, 2010-2012, Wind River Systems
6 * All rights reserved.
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 "core.h"
38 #include "port.h"
40 #include <linux/export.h>
41 #include <net/sock.h>
43 #define SS_LISTENING -1 /* socket is listening */
44 #define SS_READY -2 /* socket is connectionless */
46 #define OVERLOAD_LIMIT_BASE 10000
47 #define CONN_TIMEOUT_DEFAULT 8000 /* default connect timeout = 8s */
49 struct tipc_sock {
50 struct sock sk;
51 struct tipc_port *p;
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;
77 * Revised TIPC socket locking policy:
79 * Most socket operations take the standard socket lock when they start
80 * and hold it until they finish (or until they need to sleep). Acquiring
81 * this lock grants the owner exclusive access to the fields of the socket
82 * data structures, with the exception of the backlog queue. A few socket
83 * operations can be done without taking the socket lock because they only
84 * read socket information that never changes during the life of the socket.
86 * Socket operations may acquire the lock for the associated TIPC port if they
87 * need to perform an operation on the port. If any routine needs to acquire
88 * both the socket lock and the port lock it must take the socket lock first
89 * to avoid the risk of deadlock.
91 * The dispatcher handling incoming messages cannot grab the socket lock in
92 * the standard fashion, since invoked it runs at the BH level and cannot block.
93 * Instead, it checks to see if the socket lock is currently owned by someone,
94 * and either handles the message itself or adds it to the socket's backlog
95 * queue; in the latter case the queued message is processed once the process
96 * owning the socket lock releases it.
98 * NOTE: Releasing the socket lock while an operation is sleeping overcomes
99 * the problem of a blocked socket operation preventing any other operations
100 * from occurring. However, applications must be careful if they have
101 * multiple threads trying to send (or receive) on the same socket, as these
102 * operations might interfere with each other. For example, doing a connect
103 * and a receive at the same time might allow the receive to consume the
104 * ACK message meant for the connect. While additional work could be done
105 * to try and overcome this, it doesn't seem to be worthwhile at the present.
107 * NOTE: Releasing the socket lock while an operation is sleeping also ensures
108 * that another operation that must be performed in a non-blocking manner is
109 * not delayed for very long because the lock has already been taken.
111 * NOTE: This code assumes that certain fields of a port/socket pair are
112 * constant over its lifetime; such fields can be examined without taking
113 * the socket lock and/or port lock, and do not need to be re-read even
114 * after resuming processing after waiting. These fields include:
115 * - socket type
116 * - pointer to socket sk structure (aka tipc_sock structure)
117 * - pointer to port structure
118 * - port reference
122 * advance_rx_queue - discard first buffer in socket receive queue
124 * Caller must hold socket lock
126 static void advance_rx_queue(struct sock *sk)
128 kfree_skb(__skb_dequeue(&sk->sk_receive_queue));
132 * discard_rx_queue - discard all buffers in socket receive queue
134 * Caller must hold socket lock
136 static void discard_rx_queue(struct sock *sk)
138 struct sk_buff *buf;
140 while ((buf = __skb_dequeue(&sk->sk_receive_queue)))
141 kfree_skb(buf);
145 * reject_rx_queue - reject all buffers in socket receive queue
147 * Caller must hold socket lock
149 static void reject_rx_queue(struct sock *sk)
151 struct sk_buff *buf;
153 while ((buf = __skb_dequeue(&sk->sk_receive_queue)))
154 tipc_reject_msg(buf, TIPC_ERR_NO_PORT);
158 * tipc_create - create a TIPC socket
159 * @net: network namespace (must be default network)
160 * @sock: pre-allocated socket structure
161 * @protocol: protocol indicator (must be 0)
162 * @kern: caused by kernel or by userspace?
164 * This routine creates additional data structures used by the TIPC socket,
165 * initializes them, and links them together.
167 * Returns 0 on success, errno otherwise
169 static int tipc_create(struct net *net, struct socket *sock, int protocol,
170 int kern)
172 const struct proto_ops *ops;
173 socket_state state;
174 struct sock *sk;
175 struct tipc_port *tp_ptr;
177 /* Validate arguments */
178 if (unlikely(protocol != 0))
179 return -EPROTONOSUPPORT;
181 switch (sock->type) {
182 case SOCK_STREAM:
183 ops = &stream_ops;
184 state = SS_UNCONNECTED;
185 break;
186 case SOCK_SEQPACKET:
187 ops = &packet_ops;
188 state = SS_UNCONNECTED;
189 break;
190 case SOCK_DGRAM:
191 case SOCK_RDM:
192 ops = &msg_ops;
193 state = SS_READY;
194 break;
195 default:
196 return -EPROTOTYPE;
199 /* Allocate socket's protocol area */
200 sk = sk_alloc(net, AF_TIPC, GFP_KERNEL, &tipc_proto);
201 if (sk == NULL)
202 return -ENOMEM;
204 /* Allocate TIPC port for socket to use */
205 tp_ptr = tipc_createport_raw(sk, &dispatch, &wakeupdispatch,
206 TIPC_LOW_IMPORTANCE);
207 if (unlikely(!tp_ptr)) {
208 sk_free(sk);
209 return -ENOMEM;
212 /* Finish initializing socket data structures */
213 sock->ops = ops;
214 sock->state = state;
216 sock_init_data(sock, sk);
217 sk->sk_backlog_rcv = backlog_rcv;
218 sk->sk_rcvbuf = TIPC_FLOW_CONTROL_WIN * 2 * TIPC_MAX_USER_MSG_SIZE * 2;
219 sk->sk_data_ready = tipc_data_ready;
220 sk->sk_write_space = tipc_write_space;
221 tipc_sk(sk)->p = tp_ptr;
222 tipc_sk(sk)->conn_timeout = CONN_TIMEOUT_DEFAULT;
224 spin_unlock_bh(tp_ptr->lock);
226 if (sock->state == SS_READY) {
227 tipc_set_portunreturnable(tp_ptr->ref, 1);
228 if (sock->type == SOCK_DGRAM)
229 tipc_set_portunreliable(tp_ptr->ref, 1);
232 return 0;
236 * release - destroy a TIPC socket
237 * @sock: socket to destroy
239 * This routine cleans up any messages that are still queued on the socket.
240 * For DGRAM and RDM socket types, all queued messages are rejected.
241 * For SEQPACKET and STREAM socket types, the first message is rejected
242 * and any others are discarded. (If the first message on a STREAM socket
243 * is partially-read, it is discarded and the next one is rejected instead.)
245 * NOTE: Rejected messages are not necessarily returned to the sender! They
246 * are returned or discarded according to the "destination droppable" setting
247 * specified for the message by the sender.
249 * Returns 0 on success, errno otherwise
251 static int release(struct socket *sock)
253 struct sock *sk = sock->sk;
254 struct tipc_port *tport;
255 struct sk_buff *buf;
256 int res;
259 * Exit if socket isn't fully initialized (occurs when a failed accept()
260 * releases a pre-allocated child socket that was never used)
262 if (sk == NULL)
263 return 0;
265 tport = tipc_sk_port(sk);
266 lock_sock(sk);
269 * Reject all unreceived messages, except on an active connection
270 * (which disconnects locally & sends a 'FIN+' to peer)
272 while (sock->state != SS_DISCONNECTING) {
273 buf = __skb_dequeue(&sk->sk_receive_queue);
274 if (buf == NULL)
275 break;
276 if (TIPC_SKB_CB(buf)->handle != 0)
277 kfree_skb(buf);
278 else {
279 if ((sock->state == SS_CONNECTING) ||
280 (sock->state == SS_CONNECTED)) {
281 sock->state = SS_DISCONNECTING;
282 tipc_disconnect(tport->ref);
284 tipc_reject_msg(buf, TIPC_ERR_NO_PORT);
289 * Delete TIPC port; this ensures no more messages are queued
290 * (also disconnects an active connection & sends a 'FIN-' to peer)
292 res = tipc_deleteport(tport->ref);
294 /* Discard any remaining (connection-based) messages in receive queue */
295 discard_rx_queue(sk);
297 /* Reject any messages that accumulated in backlog queue */
298 sock->state = SS_DISCONNECTING;
299 release_sock(sk);
301 sock_put(sk);
302 sock->sk = NULL;
304 return res;
308 * bind - associate or disassocate TIPC name(s) with a socket
309 * @sock: socket structure
310 * @uaddr: socket address describing name(s) and desired operation
311 * @uaddr_len: size of socket address data structure
313 * Name and name sequence binding is indicated using a positive scope value;
314 * a negative scope value unbinds the specified name. Specifying no name
315 * (i.e. a socket address length of 0) unbinds all names from the socket.
317 * Returns 0 on success, errno otherwise
319 * NOTE: This routine doesn't need to take the socket lock since it doesn't
320 * access any non-constant socket information.
322 static int bind(struct socket *sock, struct sockaddr *uaddr, int uaddr_len)
324 struct sockaddr_tipc *addr = (struct sockaddr_tipc *)uaddr;
325 u32 portref = tipc_sk_port(sock->sk)->ref;
327 if (unlikely(!uaddr_len))
328 return tipc_withdraw(portref, 0, NULL);
330 if (uaddr_len < sizeof(struct sockaddr_tipc))
331 return -EINVAL;
332 if (addr->family != AF_TIPC)
333 return -EAFNOSUPPORT;
335 if (addr->addrtype == TIPC_ADDR_NAME)
336 addr->addr.nameseq.upper = addr->addr.nameseq.lower;
337 else if (addr->addrtype != TIPC_ADDR_NAMESEQ)
338 return -EAFNOSUPPORT;
340 if (addr->addr.nameseq.type < TIPC_RESERVED_TYPES)
341 return -EACCES;
343 return (addr->scope > 0) ?
344 tipc_publish(portref, addr->scope, &addr->addr.nameseq) :
345 tipc_withdraw(portref, -addr->scope, &addr->addr.nameseq);
349 * get_name - get port ID of socket or peer socket
350 * @sock: socket structure
351 * @uaddr: area for returned socket address
352 * @uaddr_len: area for returned length of socket address
353 * @peer: 0 = own ID, 1 = current peer ID, 2 = current/former peer ID
355 * Returns 0 on success, errno otherwise
357 * NOTE: This routine doesn't need to take the socket lock since it only
358 * accesses socket information that is unchanging (or which changes in
359 * a completely predictable manner).
361 static int get_name(struct socket *sock, struct sockaddr *uaddr,
362 int *uaddr_len, int peer)
364 struct sockaddr_tipc *addr = (struct sockaddr_tipc *)uaddr;
365 struct tipc_sock *tsock = tipc_sk(sock->sk);
367 memset(addr, 0, sizeof(*addr));
368 if (peer) {
369 if ((sock->state != SS_CONNECTED) &&
370 ((peer != 2) || (sock->state != SS_DISCONNECTING)))
371 return -ENOTCONN;
372 addr->addr.id.ref = tsock->peer_name.ref;
373 addr->addr.id.node = tsock->peer_name.node;
374 } else {
375 addr->addr.id.ref = tsock->p->ref;
376 addr->addr.id.node = tipc_own_addr;
379 *uaddr_len = sizeof(*addr);
380 addr->addrtype = TIPC_ADDR_ID;
381 addr->family = AF_TIPC;
382 addr->scope = 0;
383 addr->addr.name.domain = 0;
385 return 0;
389 * poll - read and possibly block on pollmask
390 * @file: file structure associated with the socket
391 * @sock: socket for which to calculate the poll bits
392 * @wait: ???
394 * Returns pollmask value
396 * COMMENTARY:
397 * It appears that the usual socket locking mechanisms are not useful here
398 * since the pollmask info is potentially out-of-date the moment this routine
399 * exits. TCP and other protocols seem to rely on higher level poll routines
400 * to handle any preventable race conditions, so TIPC will do the same ...
402 * TIPC sets the returned events as follows:
404 * socket state flags set
405 * ------------ ---------
406 * unconnected no read flags
407 * POLLOUT if port is not congested
409 * connecting POLLIN/POLLRDNORM if ACK/NACK in rx queue
410 * no write flags
412 * connected POLLIN/POLLRDNORM if data in rx queue
413 * POLLOUT if port is not congested
415 * disconnecting POLLIN/POLLRDNORM/POLLHUP
416 * no write flags
418 * listening POLLIN if SYN in rx queue
419 * no write flags
421 * ready POLLIN/POLLRDNORM if data in rx queue
422 * [connectionless] POLLOUT (since port cannot be congested)
424 * IMPORTANT: The fact that a read or write operation is indicated does NOT
425 * imply that the operation will succeed, merely that it should be performed
426 * and will not block.
428 static unsigned int poll(struct file *file, struct socket *sock,
429 poll_table *wait)
431 struct sock *sk = sock->sk;
432 u32 mask = 0;
434 sock_poll_wait(file, sk_sleep(sk), wait);
436 switch ((int)sock->state) {
437 case SS_UNCONNECTED:
438 if (!tipc_sk_port(sk)->congested)
439 mask |= POLLOUT;
440 break;
441 case SS_READY:
442 case SS_CONNECTED:
443 if (!tipc_sk_port(sk)->congested)
444 mask |= POLLOUT;
445 /* fall thru' */
446 case SS_CONNECTING:
447 case SS_LISTENING:
448 if (!skb_queue_empty(&sk->sk_receive_queue))
449 mask |= (POLLIN | POLLRDNORM);
450 break;
451 case SS_DISCONNECTING:
452 mask = (POLLIN | POLLRDNORM | POLLHUP);
453 break;
456 return mask;
460 * dest_name_check - verify user is permitted to send to specified port name
461 * @dest: destination address
462 * @m: descriptor for message to be sent
464 * Prevents restricted configuration commands from being issued by
465 * unauthorized users.
467 * Returns 0 if permission is granted, otherwise errno
469 static int dest_name_check(struct sockaddr_tipc *dest, struct msghdr *m)
471 struct tipc_cfg_msg_hdr hdr;
473 if (likely(dest->addr.name.name.type >= TIPC_RESERVED_TYPES))
474 return 0;
475 if (likely(dest->addr.name.name.type == TIPC_TOP_SRV))
476 return 0;
477 if (likely(dest->addr.name.name.type != TIPC_CFG_SRV))
478 return -EACCES;
480 if (!m->msg_iovlen || (m->msg_iov[0].iov_len < sizeof(hdr)))
481 return -EMSGSIZE;
482 if (copy_from_user(&hdr, m->msg_iov[0].iov_base, sizeof(hdr)))
483 return -EFAULT;
484 if ((ntohs(hdr.tcm_type) & 0xC000) && (!capable(CAP_NET_ADMIN)))
485 return -EACCES;
487 return 0;
491 * send_msg - send message in connectionless manner
492 * @iocb: if NULL, indicates that socket lock is already held
493 * @sock: socket structure
494 * @m: message to send
495 * @total_len: length of message
497 * Message must have an destination specified explicitly.
498 * Used for SOCK_RDM and SOCK_DGRAM messages,
499 * and for 'SYN' messages on SOCK_SEQPACKET and SOCK_STREAM connections.
500 * (Note: 'SYN+' is prohibited on SOCK_STREAM.)
502 * Returns the number of bytes sent on success, or errno otherwise
504 static int send_msg(struct kiocb *iocb, struct socket *sock,
505 struct msghdr *m, size_t total_len)
507 struct sock *sk = sock->sk;
508 struct tipc_port *tport = tipc_sk_port(sk);
509 struct sockaddr_tipc *dest = (struct sockaddr_tipc *)m->msg_name;
510 int needs_conn;
511 long timeout_val;
512 int res = -EINVAL;
514 if (unlikely(!dest))
515 return -EDESTADDRREQ;
516 if (unlikely((m->msg_namelen < sizeof(*dest)) ||
517 (dest->family != AF_TIPC)))
518 return -EINVAL;
519 if ((total_len > TIPC_MAX_USER_MSG_SIZE) ||
520 (m->msg_iovlen > (unsigned int)INT_MAX))
521 return -EMSGSIZE;
523 if (iocb)
524 lock_sock(sk);
526 needs_conn = (sock->state != SS_READY);
527 if (unlikely(needs_conn)) {
528 if (sock->state == SS_LISTENING) {
529 res = -EPIPE;
530 goto exit;
532 if (sock->state != SS_UNCONNECTED) {
533 res = -EISCONN;
534 goto exit;
536 if ((tport->published) ||
537 ((sock->type == SOCK_STREAM) && (total_len != 0))) {
538 res = -EOPNOTSUPP;
539 goto exit;
541 if (dest->addrtype == TIPC_ADDR_NAME) {
542 tport->conn_type = dest->addr.name.name.type;
543 tport->conn_instance = dest->addr.name.name.instance;
546 /* Abort any pending connection attempts (very unlikely) */
547 reject_rx_queue(sk);
550 timeout_val = sock_sndtimeo(sk, m->msg_flags & MSG_DONTWAIT);
552 do {
553 if (dest->addrtype == TIPC_ADDR_NAME) {
554 res = dest_name_check(dest, m);
555 if (res)
556 break;
557 res = tipc_send2name(tport->ref,
558 &dest->addr.name.name,
559 dest->addr.name.domain,
560 m->msg_iovlen,
561 m->msg_iov,
562 total_len);
563 } else if (dest->addrtype == TIPC_ADDR_ID) {
564 res = tipc_send2port(tport->ref,
565 &dest->addr.id,
566 m->msg_iovlen,
567 m->msg_iov,
568 total_len);
569 } else if (dest->addrtype == TIPC_ADDR_MCAST) {
570 if (needs_conn) {
571 res = -EOPNOTSUPP;
572 break;
574 res = dest_name_check(dest, m);
575 if (res)
576 break;
577 res = tipc_multicast(tport->ref,
578 &dest->addr.nameseq,
579 m->msg_iovlen,
580 m->msg_iov,
581 total_len);
583 if (likely(res != -ELINKCONG)) {
584 if (needs_conn && (res >= 0))
585 sock->state = SS_CONNECTING;
586 break;
588 if (timeout_val <= 0L) {
589 res = timeout_val ? timeout_val : -EWOULDBLOCK;
590 break;
592 release_sock(sk);
593 timeout_val = wait_event_interruptible_timeout(*sk_sleep(sk),
594 !tport->congested, timeout_val);
595 lock_sock(sk);
596 } while (1);
598 exit:
599 if (iocb)
600 release_sock(sk);
601 return res;
605 * send_packet - send a connection-oriented message
606 * @iocb: if NULL, indicates that socket lock is already held
607 * @sock: socket structure
608 * @m: message to send
609 * @total_len: length of message
611 * Used for SOCK_SEQPACKET messages and SOCK_STREAM data.
613 * 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;
621 long timeout_val;
622 int res;
624 /* Handle implied connection establishment */
625 if (unlikely(dest))
626 return send_msg(iocb, sock, m, total_len);
628 if ((total_len > TIPC_MAX_USER_MSG_SIZE) ||
629 (m->msg_iovlen > (unsigned int)INT_MAX))
630 return -EMSGSIZE;
632 if (iocb)
633 lock_sock(sk);
635 timeout_val = sock_sndtimeo(sk, m->msg_flags & MSG_DONTWAIT);
637 do {
638 if (unlikely(sock->state != SS_CONNECTED)) {
639 if (sock->state == SS_DISCONNECTING)
640 res = -EPIPE;
641 else
642 res = -ENOTCONN;
643 break;
646 res = tipc_send(tport->ref, m->msg_iovlen, m->msg_iov,
647 total_len);
648 if (likely(res != -ELINKCONG))
649 break;
650 if (timeout_val <= 0L) {
651 res = timeout_val ? timeout_val : -EWOULDBLOCK;
652 break;
654 release_sock(sk);
655 timeout_val = wait_event_interruptible_timeout(*sk_sleep(sk),
656 (!tport->congested || !tport->connected), timeout_val);
657 lock_sock(sk);
658 } while (1);
660 if (iocb)
661 release_sock(sk);
662 return res;
666 * send_stream - send stream-oriented data
667 * @iocb: (unused)
668 * @sock: socket structure
669 * @m: data to send
670 * @total_len: total length of data to be sent
672 * Used for SOCK_STREAM data.
674 * Returns the number of bytes sent on success (or partial success),
675 * or errno if no data sent
677 static int send_stream(struct kiocb *iocb, struct socket *sock,
678 struct msghdr *m, size_t total_len)
680 struct sock *sk = sock->sk;
681 struct tipc_port *tport = tipc_sk_port(sk);
682 struct msghdr my_msg;
683 struct iovec my_iov;
684 struct iovec *curr_iov;
685 int curr_iovlen;
686 char __user *curr_start;
687 u32 hdr_size;
688 int curr_left;
689 int bytes_to_send;
690 int bytes_sent;
691 int res;
693 lock_sock(sk);
695 /* Handle special cases where there is no connection */
696 if (unlikely(sock->state != SS_CONNECTED)) {
697 if (sock->state == SS_UNCONNECTED) {
698 res = send_packet(NULL, sock, m, total_len);
699 goto exit;
700 } else if (sock->state == SS_DISCONNECTING) {
701 res = -EPIPE;
702 goto exit;
703 } else {
704 res = -ENOTCONN;
705 goto exit;
709 if (unlikely(m->msg_name)) {
710 res = -EISCONN;
711 goto exit;
714 if ((total_len > (unsigned int)INT_MAX) ||
715 (m->msg_iovlen > (unsigned int)INT_MAX)) {
716 res = -EMSGSIZE;
717 goto exit;
721 * Send each iovec entry using one or more messages
723 * Note: This algorithm is good for the most likely case
724 * (i.e. one large iovec entry), but could be improved to pass sets
725 * of small iovec entries into send_packet().
727 curr_iov = m->msg_iov;
728 curr_iovlen = m->msg_iovlen;
729 my_msg.msg_iov = &my_iov;
730 my_msg.msg_iovlen = 1;
731 my_msg.msg_flags = m->msg_flags;
732 my_msg.msg_name = NULL;
733 bytes_sent = 0;
735 hdr_size = msg_hdr_sz(&tport->phdr);
737 while (curr_iovlen--) {
738 curr_start = curr_iov->iov_base;
739 curr_left = curr_iov->iov_len;
741 while (curr_left) {
742 bytes_to_send = tport->max_pkt - hdr_size;
743 if (bytes_to_send > TIPC_MAX_USER_MSG_SIZE)
744 bytes_to_send = TIPC_MAX_USER_MSG_SIZE;
745 if (curr_left < bytes_to_send)
746 bytes_to_send = curr_left;
747 my_iov.iov_base = curr_start;
748 my_iov.iov_len = bytes_to_send;
749 res = send_packet(NULL, sock, &my_msg, bytes_to_send);
750 if (res < 0) {
751 if (bytes_sent)
752 res = bytes_sent;
753 goto exit;
755 curr_left -= bytes_to_send;
756 curr_start += bytes_to_send;
757 bytes_sent += bytes_to_send;
760 curr_iov++;
762 res = bytes_sent;
763 exit:
764 release_sock(sk);
765 return res;
769 * auto_connect - complete connection setup to a remote port
770 * @sock: socket structure
771 * @msg: peer's response message
773 * Returns 0 on success, errno otherwise
775 static int auto_connect(struct socket *sock, struct tipc_msg *msg)
777 struct tipc_sock *tsock = tipc_sk(sock->sk);
778 struct tipc_port *p_ptr;
780 tsock->peer_name.ref = msg_origport(msg);
781 tsock->peer_name.node = msg_orignode(msg);
782 p_ptr = tipc_port_deref(tsock->p->ref);
783 if (!p_ptr)
784 return -EINVAL;
786 __tipc_connect(tsock->p->ref, p_ptr, &tsock->peer_name);
788 if (msg_importance(msg) > TIPC_CRITICAL_IMPORTANCE)
789 return -EINVAL;
790 msg_set_importance(&p_ptr->phdr, (u32)msg_importance(msg));
791 sock->state = SS_CONNECTED;
792 return 0;
796 * set_orig_addr - capture sender's address for received message
797 * @m: descriptor for message info
798 * @msg: received message header
800 * Note: Address is not captured if not requested by receiver.
802 static void set_orig_addr(struct msghdr *m, struct tipc_msg *msg)
804 struct sockaddr_tipc *addr = (struct sockaddr_tipc *)m->msg_name;
806 if (addr) {
807 addr->family = AF_TIPC;
808 addr->addrtype = TIPC_ADDR_ID;
809 addr->addr.id.ref = msg_origport(msg);
810 addr->addr.id.node = msg_orignode(msg);
811 addr->addr.name.domain = 0; /* could leave uninitialized */
812 addr->scope = 0; /* could leave uninitialized */
813 m->msg_namelen = sizeof(struct sockaddr_tipc);
818 * anc_data_recv - optionally capture ancillary data for received message
819 * @m: descriptor for message info
820 * @msg: received message header
821 * @tport: TIPC port associated with message
823 * Note: Ancillary data is not captured if not requested by receiver.
825 * Returns 0 if successful, otherwise errno
827 static int anc_data_recv(struct msghdr *m, struct tipc_msg *msg,
828 struct tipc_port *tport)
830 u32 anc_data[3];
831 u32 err;
832 u32 dest_type;
833 int has_name;
834 int res;
836 if (likely(m->msg_controllen == 0))
837 return 0;
839 /* Optionally capture errored message object(s) */
840 err = msg ? msg_errcode(msg) : 0;
841 if (unlikely(err)) {
842 anc_data[0] = err;
843 anc_data[1] = msg_data_sz(msg);
844 res = put_cmsg(m, SOL_TIPC, TIPC_ERRINFO, 8, anc_data);
845 if (res)
846 return res;
847 if (anc_data[1]) {
848 res = put_cmsg(m, SOL_TIPC, TIPC_RETDATA, anc_data[1],
849 msg_data(msg));
850 if (res)
851 return res;
855 /* Optionally capture message destination object */
856 dest_type = msg ? msg_type(msg) : TIPC_DIRECT_MSG;
857 switch (dest_type) {
858 case TIPC_NAMED_MSG:
859 has_name = 1;
860 anc_data[0] = msg_nametype(msg);
861 anc_data[1] = msg_namelower(msg);
862 anc_data[2] = msg_namelower(msg);
863 break;
864 case TIPC_MCAST_MSG:
865 has_name = 1;
866 anc_data[0] = msg_nametype(msg);
867 anc_data[1] = msg_namelower(msg);
868 anc_data[2] = msg_nameupper(msg);
869 break;
870 case TIPC_CONN_MSG:
871 has_name = (tport->conn_type != 0);
872 anc_data[0] = tport->conn_type;
873 anc_data[1] = tport->conn_instance;
874 anc_data[2] = tport->conn_instance;
875 break;
876 default:
877 has_name = 0;
879 if (has_name) {
880 res = put_cmsg(m, SOL_TIPC, TIPC_DESTNAME, 12, anc_data);
881 if (res)
882 return res;
885 return 0;
889 * recv_msg - receive packet-oriented message
890 * @iocb: (unused)
891 * @m: descriptor for message info
892 * @buf_len: total size of user buffer area
893 * @flags: receive flags
895 * Used for SOCK_DGRAM, SOCK_RDM, and SOCK_SEQPACKET messages.
896 * If the complete message doesn't fit in user area, truncate it.
898 * Returns size of returned message data, errno otherwise
900 static int recv_msg(struct kiocb *iocb, struct socket *sock,
901 struct msghdr *m, size_t buf_len, int flags)
903 struct sock *sk = sock->sk;
904 struct tipc_port *tport = tipc_sk_port(sk);
905 struct sk_buff *buf;
906 struct tipc_msg *msg;
907 long timeout;
908 unsigned int sz;
909 u32 err;
910 int res;
912 /* Catch invalid receive requests */
913 if (unlikely(!buf_len))
914 return -EINVAL;
916 lock_sock(sk);
918 if (unlikely(sock->state == SS_UNCONNECTED)) {
919 res = -ENOTCONN;
920 goto exit;
923 timeout = sock_rcvtimeo(sk, flags & MSG_DONTWAIT);
924 restart:
926 /* Look for a message in receive queue; wait if necessary */
927 while (skb_queue_empty(&sk->sk_receive_queue)) {
928 if (sock->state == SS_DISCONNECTING) {
929 res = -ENOTCONN;
930 goto exit;
932 if (timeout <= 0L) {
933 res = timeout ? timeout : -EWOULDBLOCK;
934 goto exit;
936 release_sock(sk);
937 timeout = wait_event_interruptible_timeout(*sk_sleep(sk),
938 tipc_rx_ready(sock),
939 timeout);
940 lock_sock(sk);
943 /* Look at first message in receive queue */
944 buf = skb_peek(&sk->sk_receive_queue);
945 msg = buf_msg(buf);
946 sz = msg_data_sz(msg);
947 err = msg_errcode(msg);
949 /* Complete connection setup for an implied connect */
950 if (unlikely(sock->state == SS_CONNECTING)) {
951 res = auto_connect(sock, msg);
952 if (res)
953 goto exit;
956 /* Discard an empty non-errored message & try again */
957 if ((!sz) && (!err)) {
958 advance_rx_queue(sk);
959 goto restart;
962 /* Capture sender's address (optional) */
963 set_orig_addr(m, msg);
965 /* Capture ancillary data (optional) */
966 res = anc_data_recv(m, msg, tport);
967 if (res)
968 goto exit;
970 /* Capture message data (if valid) & compute return value (always) */
971 if (!err) {
972 if (unlikely(buf_len < sz)) {
973 sz = buf_len;
974 m->msg_flags |= MSG_TRUNC;
976 res = skb_copy_datagram_iovec(buf, msg_hdr_sz(msg),
977 m->msg_iov, sz);
978 if (res)
979 goto exit;
980 res = sz;
981 } else {
982 if ((sock->state == SS_READY) ||
983 ((err == TIPC_CONN_SHUTDOWN) || m->msg_control))
984 res = 0;
985 else
986 res = -ECONNRESET;
989 /* Consume received message (optional) */
990 if (likely(!(flags & MSG_PEEK))) {
991 if ((sock->state != SS_READY) &&
992 (++tport->conn_unacked >= TIPC_FLOW_CONTROL_WIN))
993 tipc_acknowledge(tport->ref, tport->conn_unacked);
994 advance_rx_queue(sk);
996 exit:
997 release_sock(sk);
998 return res;
1002 * recv_stream - receive stream-oriented data
1003 * @iocb: (unused)
1004 * @m: descriptor for message info
1005 * @buf_len: total size of user buffer area
1006 * @flags: receive flags
1008 * Used for SOCK_STREAM messages only. If not enough data is available
1009 * will optionally wait for more; never truncates data.
1011 * Returns size of returned message data, errno otherwise
1013 static int recv_stream(struct kiocb *iocb, struct socket *sock,
1014 struct msghdr *m, size_t buf_len, int flags)
1016 struct sock *sk = sock->sk;
1017 struct tipc_port *tport = tipc_sk_port(sk);
1018 struct sk_buff *buf;
1019 struct tipc_msg *msg;
1020 long timeout;
1021 unsigned int sz;
1022 int sz_to_copy, target, needed;
1023 int sz_copied = 0;
1024 u32 err;
1025 int res = 0;
1027 /* Catch invalid receive attempts */
1028 if (unlikely(!buf_len))
1029 return -EINVAL;
1031 lock_sock(sk);
1033 if (unlikely((sock->state == SS_UNCONNECTED) ||
1034 (sock->state == SS_CONNECTING))) {
1035 res = -ENOTCONN;
1036 goto exit;
1039 target = sock_rcvlowat(sk, flags & MSG_WAITALL, buf_len);
1040 timeout = sock_rcvtimeo(sk, flags & MSG_DONTWAIT);
1042 restart:
1043 /* Look for a message in receive queue; wait if necessary */
1044 while (skb_queue_empty(&sk->sk_receive_queue)) {
1045 if (sock->state == SS_DISCONNECTING) {
1046 res = -ENOTCONN;
1047 goto exit;
1049 if (timeout <= 0L) {
1050 res = timeout ? timeout : -EWOULDBLOCK;
1051 goto exit;
1053 release_sock(sk);
1054 timeout = wait_event_interruptible_timeout(*sk_sleep(sk),
1055 tipc_rx_ready(sock),
1056 timeout);
1057 lock_sock(sk);
1060 /* Look at first message in receive queue */
1061 buf = skb_peek(&sk->sk_receive_queue);
1062 msg = buf_msg(buf);
1063 sz = msg_data_sz(msg);
1064 err = msg_errcode(msg);
1066 /* Discard an empty non-errored message & try again */
1067 if ((!sz) && (!err)) {
1068 advance_rx_queue(sk);
1069 goto restart;
1072 /* Optionally capture sender's address & ancillary data of first msg */
1073 if (sz_copied == 0) {
1074 set_orig_addr(m, msg);
1075 res = anc_data_recv(m, msg, tport);
1076 if (res)
1077 goto exit;
1080 /* Capture message data (if valid) & compute return value (always) */
1081 if (!err) {
1082 u32 offset = (u32)(unsigned long)(TIPC_SKB_CB(buf)->handle);
1084 sz -= offset;
1085 needed = (buf_len - sz_copied);
1086 sz_to_copy = (sz <= needed) ? sz : needed;
1088 res = skb_copy_datagram_iovec(buf, msg_hdr_sz(msg) + offset,
1089 m->msg_iov, sz_to_copy);
1090 if (res)
1091 goto exit;
1093 sz_copied += sz_to_copy;
1095 if (sz_to_copy < sz) {
1096 if (!(flags & MSG_PEEK))
1097 TIPC_SKB_CB(buf)->handle =
1098 (void *)(unsigned long)(offset + sz_to_copy);
1099 goto exit;
1101 } else {
1102 if (sz_copied != 0)
1103 goto exit; /* can't add error msg to valid data */
1105 if ((err == TIPC_CONN_SHUTDOWN) || m->msg_control)
1106 res = 0;
1107 else
1108 res = -ECONNRESET;
1111 /* Consume received message (optional) */
1112 if (likely(!(flags & MSG_PEEK))) {
1113 if (unlikely(++tport->conn_unacked >= TIPC_FLOW_CONTROL_WIN))
1114 tipc_acknowledge(tport->ref, tport->conn_unacked);
1115 advance_rx_queue(sk);
1118 /* Loop around if more data is required */
1119 if ((sz_copied < buf_len) && /* didn't get all requested data */
1120 (!skb_queue_empty(&sk->sk_receive_queue) ||
1121 (sz_copied < target)) && /* and more is ready or required */
1122 (!(flags & MSG_PEEK)) && /* and aren't just peeking at data */
1123 (!err)) /* and haven't reached a FIN */
1124 goto restart;
1126 exit:
1127 release_sock(sk);
1128 return sz_copied ? sz_copied : res;
1132 * tipc_write_space - wake up thread if port congestion is released
1133 * @sk: socket
1135 static void tipc_write_space(struct sock *sk)
1137 struct socket_wq *wq;
1139 rcu_read_lock();
1140 wq = rcu_dereference(sk->sk_wq);
1141 if (wq_has_sleeper(wq))
1142 wake_up_interruptible_sync_poll(&wq->wait, POLLOUT |
1143 POLLWRNORM | POLLWRBAND);
1144 rcu_read_unlock();
1148 * tipc_data_ready - wake up threads to indicate messages have been received
1149 * @sk: socket
1150 * @len: the length of messages
1152 static void tipc_data_ready(struct sock *sk, int len)
1154 struct socket_wq *wq;
1156 rcu_read_lock();
1157 wq = rcu_dereference(sk->sk_wq);
1158 if (wq_has_sleeper(wq))
1159 wake_up_interruptible_sync_poll(&wq->wait, POLLIN |
1160 POLLRDNORM | POLLRDBAND);
1161 rcu_read_unlock();
1165 * rx_queue_full - determine if receive queue can accept another message
1166 * @msg: message to be added to queue
1167 * @queue_size: current size of queue
1168 * @base: nominal maximum size of queue
1170 * Returns 1 if queue is unable to accept message, 0 otherwise
1172 static int rx_queue_full(struct tipc_msg *msg, u32 queue_size, u32 base)
1174 u32 threshold;
1175 u32 imp = msg_importance(msg);
1177 if (imp == TIPC_LOW_IMPORTANCE)
1178 threshold = base;
1179 else if (imp == TIPC_MEDIUM_IMPORTANCE)
1180 threshold = base * 2;
1181 else if (imp == TIPC_HIGH_IMPORTANCE)
1182 threshold = base * 100;
1183 else
1184 return 0;
1186 if (msg_connected(msg))
1187 threshold *= 4;
1189 return queue_size >= threshold;
1193 * filter_connect - Handle all incoming messages for a connection-based socket
1194 * @tsock: TIPC socket
1195 * @msg: message
1197 * Returns TIPC error status code and socket error status code
1198 * once it encounters some errors
1200 static u32 filter_connect(struct tipc_sock *tsock, struct sk_buff **buf)
1202 struct socket *sock = tsock->sk.sk_socket;
1203 struct tipc_msg *msg = buf_msg(*buf);
1204 struct sock *sk = &tsock->sk;
1205 u32 retval = TIPC_ERR_NO_PORT;
1206 int res;
1208 if (msg_mcast(msg))
1209 return retval;
1211 switch ((int)sock->state) {
1212 case SS_CONNECTED:
1213 /* Accept only connection-based messages sent by peer */
1214 if (msg_connected(msg) && tipc_port_peer_msg(tsock->p, msg)) {
1215 if (unlikely(msg_errcode(msg))) {
1216 sock->state = SS_DISCONNECTING;
1217 __tipc_disconnect(tsock->p);
1219 retval = TIPC_OK;
1221 break;
1222 case SS_CONNECTING:
1223 /* Accept only ACK or NACK message */
1224 if (unlikely(msg_errcode(msg))) {
1225 sock->state = SS_DISCONNECTING;
1226 sk->sk_err = -ECONNREFUSED;
1227 retval = TIPC_OK;
1228 break;
1231 if (unlikely(!msg_connected(msg)))
1232 break;
1234 res = auto_connect(sock, msg);
1235 if (res) {
1236 sock->state = SS_DISCONNECTING;
1237 sk->sk_err = res;
1238 retval = TIPC_OK;
1239 break;
1242 /* If an incoming message is an 'ACK-', it should be
1243 * discarded here because it doesn't contain useful
1244 * data. In addition, we should try to wake up
1245 * connect() routine if sleeping.
1247 if (msg_data_sz(msg) == 0) {
1248 kfree_skb(*buf);
1249 *buf = NULL;
1250 if (waitqueue_active(sk_sleep(sk)))
1251 wake_up_interruptible(sk_sleep(sk));
1253 retval = TIPC_OK;
1254 break;
1255 case SS_LISTENING:
1256 case SS_UNCONNECTED:
1257 /* Accept only SYN message */
1258 if (!msg_connected(msg) && !(msg_errcode(msg)))
1259 retval = TIPC_OK;
1260 break;
1261 case SS_DISCONNECTING:
1262 break;
1263 default:
1264 pr_err("Unknown socket state %u\n", sock->state);
1266 return retval;
1270 * filter_rcv - validate incoming message
1271 * @sk: socket
1272 * @buf: message
1274 * Enqueues message on receive queue if acceptable; optionally handles
1275 * disconnect indication for a connected socket.
1277 * Called with socket lock already taken; port lock may also be taken.
1279 * Returns TIPC error status code (TIPC_OK if message is not to be rejected)
1281 static u32 filter_rcv(struct sock *sk, struct sk_buff *buf)
1283 struct socket *sock = sk->sk_socket;
1284 struct tipc_msg *msg = buf_msg(buf);
1285 u32 recv_q_len;
1286 u32 res = TIPC_OK;
1288 /* Reject message if it is wrong sort of message for socket */
1289 if (msg_type(msg) > TIPC_DIRECT_MSG)
1290 return TIPC_ERR_NO_PORT;
1292 if (sock->state == SS_READY) {
1293 if (msg_connected(msg))
1294 return TIPC_ERR_NO_PORT;
1295 } else {
1296 res = filter_connect(tipc_sk(sk), &buf);
1297 if (res != TIPC_OK || buf == NULL)
1298 return res;
1301 /* Reject message if there isn't room to queue it */
1302 recv_q_len = skb_queue_len(&sk->sk_receive_queue);
1303 if (unlikely(recv_q_len >= (OVERLOAD_LIMIT_BASE / 2))) {
1304 if (rx_queue_full(msg, recv_q_len, OVERLOAD_LIMIT_BASE / 2))
1305 return TIPC_ERR_OVERLOAD;
1308 /* Enqueue message (finally!) */
1309 TIPC_SKB_CB(buf)->handle = 0;
1310 __skb_queue_tail(&sk->sk_receive_queue, buf);
1312 sk->sk_data_ready(sk, 0);
1313 return TIPC_OK;
1317 * backlog_rcv - handle incoming message from backlog queue
1318 * @sk: socket
1319 * @buf: message
1321 * Caller must hold socket lock, but not port lock.
1323 * Returns 0
1325 static int backlog_rcv(struct sock *sk, struct sk_buff *buf)
1327 u32 res;
1329 res = filter_rcv(sk, buf);
1330 if (res)
1331 tipc_reject_msg(buf, res);
1332 return 0;
1336 * dispatch - handle incoming message
1337 * @tport: TIPC port that received message
1338 * @buf: message
1340 * Called with port lock already taken.
1342 * Returns TIPC error status code (TIPC_OK if message is not to be rejected)
1344 static u32 dispatch(struct tipc_port *tport, struct sk_buff *buf)
1346 struct sock *sk = (struct sock *)tport->usr_handle;
1347 u32 res;
1350 * Process message if socket is unlocked; otherwise add to backlog queue
1352 * This code is based on sk_receive_skb(), but must be distinct from it
1353 * since a TIPC-specific filter/reject mechanism is utilized
1355 bh_lock_sock(sk);
1356 if (!sock_owned_by_user(sk)) {
1357 res = filter_rcv(sk, buf);
1358 } else {
1359 if (sk_add_backlog(sk, buf, sk->sk_rcvbuf))
1360 res = TIPC_ERR_OVERLOAD;
1361 else
1362 res = TIPC_OK;
1364 bh_unlock_sock(sk);
1366 return res;
1370 * wakeupdispatch - wake up port after congestion
1371 * @tport: port to wakeup
1373 * Called with port lock already taken.
1375 static void wakeupdispatch(struct tipc_port *tport)
1377 struct sock *sk = (struct sock *)tport->usr_handle;
1379 sk->sk_write_space(sk);
1383 * connect - establish a connection to another TIPC port
1384 * @sock: socket structure
1385 * @dest: socket address for destination port
1386 * @destlen: size of socket address data structure
1387 * @flags: file-related flags associated with socket
1389 * Returns 0 on success, errno otherwise
1391 static int connect(struct socket *sock, struct sockaddr *dest, int destlen,
1392 int flags)
1394 struct sock *sk = sock->sk;
1395 struct sockaddr_tipc *dst = (struct sockaddr_tipc *)dest;
1396 struct msghdr m = {NULL,};
1397 unsigned int timeout;
1398 int res;
1400 lock_sock(sk);
1402 /* For now, TIPC does not allow use of connect() with DGRAM/RDM types */
1403 if (sock->state == SS_READY) {
1404 res = -EOPNOTSUPP;
1405 goto exit;
1409 * Reject connection attempt using multicast address
1411 * Note: send_msg() validates the rest of the address fields,
1412 * so there's no need to do it here
1414 if (dst->addrtype == TIPC_ADDR_MCAST) {
1415 res = -EINVAL;
1416 goto exit;
1419 timeout = (flags & O_NONBLOCK) ? 0 : tipc_sk(sk)->conn_timeout;
1421 switch (sock->state) {
1422 case SS_UNCONNECTED:
1423 /* Send a 'SYN-' to destination */
1424 m.msg_name = dest;
1425 m.msg_namelen = destlen;
1427 /* If connect is in non-blocking case, set MSG_DONTWAIT to
1428 * indicate send_msg() is never blocked.
1430 if (!timeout)
1431 m.msg_flags = MSG_DONTWAIT;
1433 res = send_msg(NULL, sock, &m, 0);
1434 if ((res < 0) && (res != -EWOULDBLOCK))
1435 goto exit;
1437 /* Just entered SS_CONNECTING state; the only
1438 * difference is that return value in non-blocking
1439 * case is EINPROGRESS, rather than EALREADY.
1441 res = -EINPROGRESS;
1442 break;
1443 case SS_CONNECTING:
1444 res = -EALREADY;
1445 break;
1446 case SS_CONNECTED:
1447 res = -EISCONN;
1448 break;
1449 default:
1450 res = -EINVAL;
1451 goto exit;
1454 if (sock->state == SS_CONNECTING) {
1455 if (!timeout)
1456 goto exit;
1458 /* Wait until an 'ACK' or 'RST' arrives, or a timeout occurs */
1459 release_sock(sk);
1460 res = wait_event_interruptible_timeout(*sk_sleep(sk),
1461 sock->state != SS_CONNECTING,
1462 timeout ? (long)msecs_to_jiffies(timeout)
1463 : MAX_SCHEDULE_TIMEOUT);
1464 lock_sock(sk);
1465 if (res <= 0) {
1466 if (res == 0)
1467 res = -ETIMEDOUT;
1468 else
1469 ; /* leave "res" unchanged */
1470 goto exit;
1474 if (unlikely(sock->state == SS_DISCONNECTING))
1475 res = sock_error(sk);
1476 else
1477 res = 0;
1479 exit:
1480 release_sock(sk);
1481 return res;
1485 * listen - allow socket to listen for incoming connections
1486 * @sock: socket structure
1487 * @len: (unused)
1489 * Returns 0 on success, errno otherwise
1491 static int listen(struct socket *sock, int len)
1493 struct sock *sk = sock->sk;
1494 int res;
1496 lock_sock(sk);
1498 if (sock->state != SS_UNCONNECTED)
1499 res = -EINVAL;
1500 else {
1501 sock->state = SS_LISTENING;
1502 res = 0;
1505 release_sock(sk);
1506 return res;
1510 * accept - wait for connection request
1511 * @sock: listening socket
1512 * @newsock: new socket that is to be connected
1513 * @flags: file-related flags associated with socket
1515 * Returns 0 on success, errno otherwise
1517 static int accept(struct socket *sock, struct socket *new_sock, int flags)
1519 struct sock *sk = sock->sk;
1520 struct sk_buff *buf;
1521 int res;
1523 lock_sock(sk);
1525 if (sock->state != SS_LISTENING) {
1526 res = -EINVAL;
1527 goto exit;
1530 while (skb_queue_empty(&sk->sk_receive_queue)) {
1531 if (flags & O_NONBLOCK) {
1532 res = -EWOULDBLOCK;
1533 goto exit;
1535 release_sock(sk);
1536 res = wait_event_interruptible(*sk_sleep(sk),
1537 (!skb_queue_empty(&sk->sk_receive_queue)));
1538 lock_sock(sk);
1539 if (res)
1540 goto exit;
1543 buf = skb_peek(&sk->sk_receive_queue);
1545 res = tipc_create(sock_net(sock->sk), new_sock, 0, 0);
1546 if (!res) {
1547 struct sock *new_sk = new_sock->sk;
1548 struct tipc_sock *new_tsock = tipc_sk(new_sk);
1549 struct tipc_port *new_tport = new_tsock->p;
1550 u32 new_ref = new_tport->ref;
1551 struct tipc_msg *msg = buf_msg(buf);
1553 lock_sock(new_sk);
1556 * Reject any stray messages received by new socket
1557 * before the socket lock was taken (very, very unlikely)
1559 reject_rx_queue(new_sk);
1561 /* Connect new socket to it's peer */
1562 new_tsock->peer_name.ref = msg_origport(msg);
1563 new_tsock->peer_name.node = msg_orignode(msg);
1564 tipc_connect(new_ref, &new_tsock->peer_name);
1565 new_sock->state = SS_CONNECTED;
1567 tipc_set_portimportance(new_ref, msg_importance(msg));
1568 if (msg_named(msg)) {
1569 new_tport->conn_type = msg_nametype(msg);
1570 new_tport->conn_instance = msg_nameinst(msg);
1574 * Respond to 'SYN-' by discarding it & returning 'ACK'-.
1575 * Respond to 'SYN+' by queuing it on new socket.
1577 if (!msg_data_sz(msg)) {
1578 struct msghdr m = {NULL,};
1580 advance_rx_queue(sk);
1581 send_packet(NULL, new_sock, &m, 0);
1582 } else {
1583 __skb_dequeue(&sk->sk_receive_queue);
1584 __skb_queue_head(&new_sk->sk_receive_queue, buf);
1586 release_sock(new_sk);
1588 exit:
1589 release_sock(sk);
1590 return res;
1594 * shutdown - shutdown socket connection
1595 * @sock: socket structure
1596 * @how: direction to close (must be SHUT_RDWR)
1598 * Terminates connection (if necessary), then purges socket's receive queue.
1600 * Returns 0 on success, errno otherwise
1602 static int shutdown(struct socket *sock, int how)
1604 struct sock *sk = sock->sk;
1605 struct tipc_port *tport = tipc_sk_port(sk);
1606 struct sk_buff *buf;
1607 int res;
1609 if (how != SHUT_RDWR)
1610 return -EINVAL;
1612 lock_sock(sk);
1614 switch (sock->state) {
1615 case SS_CONNECTING:
1616 case SS_CONNECTED:
1618 restart:
1619 /* Disconnect and send a 'FIN+' or 'FIN-' message to peer */
1620 buf = __skb_dequeue(&sk->sk_receive_queue);
1621 if (buf) {
1622 if (TIPC_SKB_CB(buf)->handle != 0) {
1623 kfree_skb(buf);
1624 goto restart;
1626 tipc_disconnect(tport->ref);
1627 tipc_reject_msg(buf, TIPC_CONN_SHUTDOWN);
1628 } else {
1629 tipc_shutdown(tport->ref);
1632 sock->state = SS_DISCONNECTING;
1634 /* fall through */
1636 case SS_DISCONNECTING:
1638 /* Discard any unreceived messages */
1639 discard_rx_queue(sk);
1641 /* Wake up anyone sleeping in poll */
1642 sk->sk_state_change(sk);
1643 res = 0;
1644 break;
1646 default:
1647 res = -ENOTCONN;
1650 release_sock(sk);
1651 return res;
1655 * setsockopt - set socket option
1656 * @sock: socket structure
1657 * @lvl: option level
1658 * @opt: option identifier
1659 * @ov: pointer to new option value
1660 * @ol: length of option value
1662 * For stream sockets only, accepts and ignores all IPPROTO_TCP options
1663 * (to ease compatibility).
1665 * Returns 0 on success, errno otherwise
1667 static int setsockopt(struct socket *sock,
1668 int lvl, int opt, char __user *ov, unsigned int ol)
1670 struct sock *sk = sock->sk;
1671 struct tipc_port *tport = tipc_sk_port(sk);
1672 u32 value;
1673 int res;
1675 if ((lvl == IPPROTO_TCP) && (sock->type == SOCK_STREAM))
1676 return 0;
1677 if (lvl != SOL_TIPC)
1678 return -ENOPROTOOPT;
1679 if (ol < sizeof(value))
1680 return -EINVAL;
1681 res = get_user(value, (u32 __user *)ov);
1682 if (res)
1683 return res;
1685 lock_sock(sk);
1687 switch (opt) {
1688 case TIPC_IMPORTANCE:
1689 res = tipc_set_portimportance(tport->ref, value);
1690 break;
1691 case TIPC_SRC_DROPPABLE:
1692 if (sock->type != SOCK_STREAM)
1693 res = tipc_set_portunreliable(tport->ref, value);
1694 else
1695 res = -ENOPROTOOPT;
1696 break;
1697 case TIPC_DEST_DROPPABLE:
1698 res = tipc_set_portunreturnable(tport->ref, value);
1699 break;
1700 case TIPC_CONN_TIMEOUT:
1701 tipc_sk(sk)->conn_timeout = value;
1702 /* no need to set "res", since already 0 at this point */
1703 break;
1704 default:
1705 res = -EINVAL;
1708 release_sock(sk);
1710 return res;
1714 * getsockopt - get socket option
1715 * @sock: socket structure
1716 * @lvl: option level
1717 * @opt: option identifier
1718 * @ov: receptacle for option value
1719 * @ol: receptacle for length of option value
1721 * For stream sockets only, returns 0 length result for all IPPROTO_TCP options
1722 * (to ease compatibility).
1724 * Returns 0 on success, errno otherwise
1726 static int getsockopt(struct socket *sock,
1727 int lvl, int opt, char __user *ov, int __user *ol)
1729 struct sock *sk = sock->sk;
1730 struct tipc_port *tport = tipc_sk_port(sk);
1731 int len;
1732 u32 value;
1733 int res;
1735 if ((lvl == IPPROTO_TCP) && (sock->type == SOCK_STREAM))
1736 return put_user(0, ol);
1737 if (lvl != SOL_TIPC)
1738 return -ENOPROTOOPT;
1739 res = get_user(len, ol);
1740 if (res)
1741 return res;
1743 lock_sock(sk);
1745 switch (opt) {
1746 case TIPC_IMPORTANCE:
1747 res = tipc_portimportance(tport->ref, &value);
1748 break;
1749 case TIPC_SRC_DROPPABLE:
1750 res = tipc_portunreliable(tport->ref, &value);
1751 break;
1752 case TIPC_DEST_DROPPABLE:
1753 res = tipc_portunreturnable(tport->ref, &value);
1754 break;
1755 case TIPC_CONN_TIMEOUT:
1756 value = tipc_sk(sk)->conn_timeout;
1757 /* no need to set "res", since already 0 at this point */
1758 break;
1759 case TIPC_NODE_RECVQ_DEPTH:
1760 value = 0; /* was tipc_queue_size, now obsolete */
1761 break;
1762 case TIPC_SOCK_RECVQ_DEPTH:
1763 value = skb_queue_len(&sk->sk_receive_queue);
1764 break;
1765 default:
1766 res = -EINVAL;
1769 release_sock(sk);
1771 if (res)
1772 return res; /* "get" failed */
1774 if (len < sizeof(value))
1775 return -EINVAL;
1777 if (copy_to_user(ov, &value, sizeof(value)))
1778 return -EFAULT;
1780 return put_user(sizeof(value), ol);
1783 /* Protocol switches for the various types of TIPC sockets */
1785 static const struct proto_ops msg_ops = {
1786 .owner = THIS_MODULE,
1787 .family = AF_TIPC,
1788 .release = release,
1789 .bind = bind,
1790 .connect = connect,
1791 .socketpair = sock_no_socketpair,
1792 .accept = sock_no_accept,
1793 .getname = get_name,
1794 .poll = poll,
1795 .ioctl = sock_no_ioctl,
1796 .listen = sock_no_listen,
1797 .shutdown = shutdown,
1798 .setsockopt = setsockopt,
1799 .getsockopt = getsockopt,
1800 .sendmsg = send_msg,
1801 .recvmsg = recv_msg,
1802 .mmap = sock_no_mmap,
1803 .sendpage = sock_no_sendpage
1806 static const struct proto_ops packet_ops = {
1807 .owner = THIS_MODULE,
1808 .family = AF_TIPC,
1809 .release = release,
1810 .bind = bind,
1811 .connect = connect,
1812 .socketpair = sock_no_socketpair,
1813 .accept = accept,
1814 .getname = get_name,
1815 .poll = poll,
1816 .ioctl = sock_no_ioctl,
1817 .listen = listen,
1818 .shutdown = shutdown,
1819 .setsockopt = setsockopt,
1820 .getsockopt = getsockopt,
1821 .sendmsg = send_packet,
1822 .recvmsg = recv_msg,
1823 .mmap = sock_no_mmap,
1824 .sendpage = sock_no_sendpage
1827 static const struct proto_ops stream_ops = {
1828 .owner = THIS_MODULE,
1829 .family = AF_TIPC,
1830 .release = release,
1831 .bind = bind,
1832 .connect = connect,
1833 .socketpair = sock_no_socketpair,
1834 .accept = accept,
1835 .getname = get_name,
1836 .poll = poll,
1837 .ioctl = sock_no_ioctl,
1838 .listen = listen,
1839 .shutdown = shutdown,
1840 .setsockopt = setsockopt,
1841 .getsockopt = getsockopt,
1842 .sendmsg = send_stream,
1843 .recvmsg = recv_stream,
1844 .mmap = sock_no_mmap,
1845 .sendpage = sock_no_sendpage
1848 static const struct net_proto_family tipc_family_ops = {
1849 .owner = THIS_MODULE,
1850 .family = AF_TIPC,
1851 .create = tipc_create
1854 static struct proto tipc_proto = {
1855 .name = "TIPC",
1856 .owner = THIS_MODULE,
1857 .obj_size = sizeof(struct tipc_sock)
1861 * tipc_socket_init - initialize TIPC socket interface
1863 * Returns 0 on success, errno otherwise
1865 int tipc_socket_init(void)
1867 int res;
1869 res = proto_register(&tipc_proto, 1);
1870 if (res) {
1871 pr_err("Failed to register TIPC protocol type\n");
1872 goto out;
1875 res = sock_register(&tipc_family_ops);
1876 if (res) {
1877 pr_err("Failed to register TIPC socket type\n");
1878 proto_unregister(&tipc_proto);
1879 goto out;
1882 sockets_enabled = 1;
1883 out:
1884 return res;
1888 * tipc_socket_stop - stop TIPC socket interface
1890 void tipc_socket_stop(void)
1892 if (!sockets_enabled)
1893 return;
1895 sockets_enabled = 0;
1896 sock_unregister(tipc_family_ops.family);
1897 proto_unregister(&tipc_proto);