[TIPC]: Remove redundant socket wait queue initialization
[safe/jmp/linux-2.6] / net / tipc / socket.c
1 /*
2  * net/tipc/socket.c: TIPC socket API
3  *
4  * Copyright (c) 2001-2007, Ericsson AB
5  * Copyright (c) 2004-2007, Wind River Systems
6  * All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions are met:
10  *
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.
19  *
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.
23  *
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.
35  */
36
37 #include <linux/module.h>
38 #include <linux/types.h>
39 #include <linux/net.h>
40 #include <linux/socket.h>
41 #include <linux/errno.h>
42 #include <linux/mm.h>
43 #include <linux/slab.h>
44 #include <linux/poll.h>
45 #include <linux/fcntl.h>
46 #include <linux/mutex.h>
47 #include <asm/string.h>
48 #include <asm/atomic.h>
49 #include <net/sock.h>
50
51 #include <linux/tipc.h>
52 #include <linux/tipc_config.h>
53 #include <net/tipc/tipc_msg.h>
54 #include <net/tipc/tipc_port.h>
55
56 #include "core.h"
57
58 #define SS_LISTENING    -1      /* socket is listening */
59 #define SS_READY        -2      /* socket is connectionless */
60
61 #define OVERLOAD_LIMIT_BASE    5000
62
63 struct tipc_sock {
64         struct sock sk;
65         struct tipc_port *p;
66         struct mutex lock;
67 };
68
69 #define tipc_sk(sk) ((struct tipc_sock*)sk)
70
71 static u32 dispatch(struct tipc_port *tport, struct sk_buff *buf);
72 static void wakeupdispatch(struct tipc_port *tport);
73
74 static const struct proto_ops packet_ops;
75 static const struct proto_ops stream_ops;
76 static const struct proto_ops msg_ops;
77
78 static struct proto tipc_proto;
79
80 static int sockets_enabled = 0;
81
82 static atomic_t tipc_queue_size = ATOMIC_INIT(0);
83
84
85 /*
86  * sock_lock(): Lock a port/socket pair. lock_sock() can
87  * not be used here, since the same lock must protect ports
88  * with non-socket interfaces.
89  * See net.c for description of locking policy.
90  */
91 static void sock_lock(struct tipc_sock* tsock)
92 {
93         spin_lock_bh(tsock->p->lock);
94 }
95
96 /*
97  * sock_unlock(): Unlock a port/socket pair
98  */
99 static void sock_unlock(struct tipc_sock* tsock)
100 {
101         spin_unlock_bh(tsock->p->lock);
102 }
103
104 /**
105  * advance_queue - discard first buffer in queue
106  * @tsock: TIPC socket
107  */
108
109 static void advance_queue(struct tipc_sock *tsock)
110 {
111         sock_lock(tsock);
112         buf_discard(skb_dequeue(&tsock->sk.sk_receive_queue));
113         sock_unlock(tsock);
114         atomic_dec(&tipc_queue_size);
115 }
116
117 /**
118  * tipc_create - create a TIPC socket
119  * @sock: pre-allocated socket structure
120  * @protocol: protocol indicator (must be 0)
121  *
122  * This routine creates and attaches a 'struct sock' to the 'struct socket',
123  * then create and attaches a TIPC port to the 'struct sock' part.
124  *
125  * Returns 0 on success, errno otherwise
126  */
127 static int tipc_create(struct net *net, struct socket *sock, int protocol)
128 {
129         struct tipc_sock *tsock;
130         struct tipc_port *port;
131         struct sock *sk;
132         u32 ref;
133
134         if (net != &init_net)
135                 return -EAFNOSUPPORT;
136
137         if (unlikely(protocol != 0))
138                 return -EPROTONOSUPPORT;
139
140         ref = tipc_createport_raw(NULL, &dispatch, &wakeupdispatch, TIPC_LOW_IMPORTANCE);
141         if (unlikely(!ref))
142                 return -ENOMEM;
143
144         sock->state = SS_UNCONNECTED;
145
146         switch (sock->type) {
147         case SOCK_STREAM:
148                 sock->ops = &stream_ops;
149                 break;
150         case SOCK_SEQPACKET:
151                 sock->ops = &packet_ops;
152                 break;
153         case SOCK_DGRAM:
154                 tipc_set_portunreliable(ref, 1);
155                 /* fall through */
156         case SOCK_RDM:
157                 tipc_set_portunreturnable(ref, 1);
158                 sock->ops = &msg_ops;
159                 sock->state = SS_READY;
160                 break;
161         default:
162                 tipc_deleteport(ref);
163                 return -EPROTOTYPE;
164         }
165
166         sk = sk_alloc(net, AF_TIPC, GFP_KERNEL, &tipc_proto);
167         if (!sk) {
168                 tipc_deleteport(ref);
169                 return -ENOMEM;
170         }
171
172         sock_init_data(sock, sk);
173         sk->sk_rcvtimeo = 8 * HZ;   /* default connect timeout = 8s */
174
175         tsock = tipc_sk(sk);
176         port = tipc_get_port(ref);
177
178         tsock->p = port;
179         port->usr_handle = tsock;
180
181         mutex_init(&tsock->lock);
182
183         dbg("sock_create: %x\n",tsock);
184
185         atomic_inc(&tipc_user_count);
186
187         return 0;
188 }
189
190 /**
191  * release - destroy a TIPC socket
192  * @sock: socket to destroy
193  *
194  * This routine cleans up any messages that are still queued on the socket.
195  * For DGRAM and RDM socket types, all queued messages are rejected.
196  * For SEQPACKET and STREAM socket types, the first message is rejected
197  * and any others are discarded.  (If the first message on a STREAM socket
198  * is partially-read, it is discarded and the next one is rejected instead.)
199  *
200  * NOTE: Rejected messages are not necessarily returned to the sender!  They
201  * are returned or discarded according to the "destination droppable" setting
202  * specified for the message by the sender.
203  *
204  * Returns 0 on success, errno otherwise
205  */
206
207 static int release(struct socket *sock)
208 {
209         struct tipc_sock *tsock = tipc_sk(sock->sk);
210         struct sock *sk = sock->sk;
211         int res = TIPC_OK;
212         struct sk_buff *buf;
213
214         dbg("sock_delete: %x\n",tsock);
215         if (!tsock)
216                 return 0;
217         mutex_lock(&tsock->lock);
218         if (!sock->sk) {
219                 mutex_unlock(&tsock->lock);
220                 return 0;
221         }
222
223         /* Reject unreceived messages, unless no longer connected */
224
225         while (sock->state != SS_DISCONNECTING) {
226                 sock_lock(tsock);
227                 buf = skb_dequeue(&sk->sk_receive_queue);
228                 if (!buf)
229                         tsock->p->usr_handle = NULL;
230                 sock_unlock(tsock);
231                 if (!buf)
232                         break;
233                 if (TIPC_SKB_CB(buf)->handle != msg_data(buf_msg(buf)))
234                         buf_discard(buf);
235                 else
236                         tipc_reject_msg(buf, TIPC_ERR_NO_PORT);
237                 atomic_dec(&tipc_queue_size);
238         }
239
240         /* Delete TIPC port */
241
242         res = tipc_deleteport(tsock->p->ref);
243         sock->sk = NULL;
244
245         /* Discard any remaining messages */
246
247         while ((buf = skb_dequeue(&sk->sk_receive_queue))) {
248                 buf_discard(buf);
249                 atomic_dec(&tipc_queue_size);
250         }
251
252         mutex_unlock(&tsock->lock);
253
254         sock_put(sk);
255
256         atomic_dec(&tipc_user_count);
257         return res;
258 }
259
260 /**
261  * bind - associate or disassocate TIPC name(s) with a socket
262  * @sock: socket structure
263  * @uaddr: socket address describing name(s) and desired operation
264  * @uaddr_len: size of socket address data structure
265  *
266  * Name and name sequence binding is indicated using a positive scope value;
267  * a negative scope value unbinds the specified name.  Specifying no name
268  * (i.e. a socket address length of 0) unbinds all names from the socket.
269  *
270  * Returns 0 on success, errno otherwise
271  */
272
273 static int bind(struct socket *sock, struct sockaddr *uaddr, int uaddr_len)
274 {
275         struct tipc_sock *tsock = tipc_sk(sock->sk);
276         struct sockaddr_tipc *addr = (struct sockaddr_tipc *)uaddr;
277         int res;
278
279         if (mutex_lock_interruptible(&tsock->lock))
280                 return -ERESTARTSYS;
281
282         if (unlikely(!uaddr_len)) {
283                 res = tipc_withdraw(tsock->p->ref, 0, NULL);
284                 goto exit;
285         }
286
287         if (uaddr_len < sizeof(struct sockaddr_tipc)) {
288                 res = -EINVAL;
289                 goto exit;
290         }
291
292         if (addr->family != AF_TIPC) {
293                 res = -EAFNOSUPPORT;
294                 goto exit;
295         }
296         if (addr->addrtype == TIPC_ADDR_NAME)
297                 addr->addr.nameseq.upper = addr->addr.nameseq.lower;
298         else if (addr->addrtype != TIPC_ADDR_NAMESEQ) {
299                 res = -EAFNOSUPPORT;
300                 goto exit;
301         }
302
303         if (addr->scope > 0)
304                 res = tipc_publish(tsock->p->ref, addr->scope,
305                                    &addr->addr.nameseq);
306         else
307                 res = tipc_withdraw(tsock->p->ref, -addr->scope,
308                                     &addr->addr.nameseq);
309 exit:
310         mutex_unlock(&tsock->lock);
311         return res;
312 }
313
314 /**
315  * get_name - get port ID of socket or peer socket
316  * @sock: socket structure
317  * @uaddr: area for returned socket address
318  * @uaddr_len: area for returned length of socket address
319  * @peer: 0 to obtain socket name, 1 to obtain peer socket name
320  *
321  * Returns 0 on success, errno otherwise
322  */
323
324 static int get_name(struct socket *sock, struct sockaddr *uaddr,
325                     int *uaddr_len, int peer)
326 {
327         struct tipc_sock *tsock = tipc_sk(sock->sk);
328         struct sockaddr_tipc *addr = (struct sockaddr_tipc *)uaddr;
329         u32 res;
330
331         if (mutex_lock_interruptible(&tsock->lock))
332                 return -ERESTARTSYS;
333
334         *uaddr_len = sizeof(*addr);
335         addr->addrtype = TIPC_ADDR_ID;
336         addr->family = AF_TIPC;
337         addr->scope = 0;
338         if (peer)
339                 res = tipc_peer(tsock->p->ref, &addr->addr.id);
340         else
341                 res = tipc_ownidentity(tsock->p->ref, &addr->addr.id);
342         addr->addr.name.domain = 0;
343
344         mutex_unlock(&tsock->lock);
345         return res;
346 }
347
348 /**
349  * poll - read and possibly block on pollmask
350  * @file: file structure associated with the socket
351  * @sock: socket for which to calculate the poll bits
352  * @wait: ???
353  *
354  * Returns pollmask value
355  *
356  * COMMENTARY:
357  * It appears that the usual socket locking mechanisms are not useful here
358  * since the pollmask info is potentially out-of-date the moment this routine
359  * exits.  TCP and other protocols seem to rely on higher level poll routines
360  * to handle any preventable race conditions, so TIPC will do the same ...
361  *
362  * TIPC sets the returned events as follows:
363  * a) POLLRDNORM and POLLIN are set if the socket's receive queue is non-empty
364  *    or if a connection-oriented socket is does not have an active connection
365  *    (i.e. a read operation will not block).
366  * b) POLLOUT is set except when a socket's connection has been terminated
367  *    (i.e. a write operation will not block).
368  * c) POLLHUP is set when a socket's connection has been terminated.
369  *
370  * IMPORTANT: The fact that a read or write operation will not block does NOT
371  * imply that the operation will succeed!
372  */
373
374 static unsigned int poll(struct file *file, struct socket *sock,
375                          poll_table *wait)
376 {
377         struct sock *sk = sock->sk;
378         u32 mask;
379
380         poll_wait(file, sk->sk_sleep, wait);
381
382         if (!skb_queue_empty(&sk->sk_receive_queue) ||
383             (sock->state == SS_UNCONNECTED) ||
384             (sock->state == SS_DISCONNECTING))
385                 mask = (POLLRDNORM | POLLIN);
386         else
387                 mask = 0;
388
389         if (sock->state == SS_DISCONNECTING)
390                 mask |= POLLHUP;
391         else
392                 mask |= POLLOUT;
393
394         return mask;
395 }
396
397 /**
398  * dest_name_check - verify user is permitted to send to specified port name
399  * @dest: destination address
400  * @m: descriptor for message to be sent
401  *
402  * Prevents restricted configuration commands from being issued by
403  * unauthorized users.
404  *
405  * Returns 0 if permission is granted, otherwise errno
406  */
407
408 static int dest_name_check(struct sockaddr_tipc *dest, struct msghdr *m)
409 {
410         struct tipc_cfg_msg_hdr hdr;
411
412         if (likely(dest->addr.name.name.type >= TIPC_RESERVED_TYPES))
413                 return 0;
414         if (likely(dest->addr.name.name.type == TIPC_TOP_SRV))
415                 return 0;
416
417         if (likely(dest->addr.name.name.type != TIPC_CFG_SRV))
418                 return -EACCES;
419
420         if (copy_from_user(&hdr, m->msg_iov[0].iov_base, sizeof(hdr)))
421                 return -EFAULT;
422         if ((ntohs(hdr.tcm_type) & 0xC000) && (!capable(CAP_NET_ADMIN)))
423                 return -EACCES;
424
425         return 0;
426 }
427
428 /**
429  * send_msg - send message in connectionless manner
430  * @iocb: (unused)
431  * @sock: socket structure
432  * @m: message to send
433  * @total_len: length of message
434  *
435  * Message must have an destination specified explicitly.
436  * Used for SOCK_RDM and SOCK_DGRAM messages,
437  * and for 'SYN' messages on SOCK_SEQPACKET and SOCK_STREAM connections.
438  * (Note: 'SYN+' is prohibited on SOCK_STREAM.)
439  *
440  * Returns the number of bytes sent on success, or errno otherwise
441  */
442
443 static int send_msg(struct kiocb *iocb, struct socket *sock,
444                     struct msghdr *m, size_t total_len)
445 {
446         struct tipc_sock *tsock = tipc_sk(sock->sk);
447         struct sockaddr_tipc *dest = (struct sockaddr_tipc *)m->msg_name;
448         struct sk_buff *buf;
449         int needs_conn;
450         int res = -EINVAL;
451
452         if (unlikely(!dest))
453                 return -EDESTADDRREQ;
454         if (unlikely((m->msg_namelen < sizeof(*dest)) ||
455                      (dest->family != AF_TIPC)))
456                 return -EINVAL;
457
458         needs_conn = (sock->state != SS_READY);
459         if (unlikely(needs_conn)) {
460                 if (sock->state == SS_LISTENING)
461                         return -EPIPE;
462                 if (sock->state != SS_UNCONNECTED)
463                         return -EISCONN;
464                 if ((tsock->p->published) ||
465                     ((sock->type == SOCK_STREAM) && (total_len != 0)))
466                         return -EOPNOTSUPP;
467                 if (dest->addrtype == TIPC_ADDR_NAME) {
468                         tsock->p->conn_type = dest->addr.name.name.type;
469                         tsock->p->conn_instance = dest->addr.name.name.instance;
470                 }
471         }
472
473         if (mutex_lock_interruptible(&tsock->lock))
474                 return -ERESTARTSYS;
475
476         if (needs_conn) {
477
478                 /* Abort any pending connection attempts (very unlikely) */
479
480                 while ((buf = skb_dequeue(&sock->sk->sk_receive_queue))) {
481                         tipc_reject_msg(buf, TIPC_ERR_NO_PORT);
482                         atomic_dec(&tipc_queue_size);
483                 }
484
485                 sock->state = SS_CONNECTING;
486         }
487
488         do {
489                 if (dest->addrtype == TIPC_ADDR_NAME) {
490                         if ((res = dest_name_check(dest, m)))
491                                 goto exit;
492                         res = tipc_send2name(tsock->p->ref,
493                                              &dest->addr.name.name,
494                                              dest->addr.name.domain,
495                                              m->msg_iovlen,
496                                              m->msg_iov);
497                 }
498                 else if (dest->addrtype == TIPC_ADDR_ID) {
499                         res = tipc_send2port(tsock->p->ref,
500                                              &dest->addr.id,
501                                              m->msg_iovlen,
502                                              m->msg_iov);
503                 }
504                 else if (dest->addrtype == TIPC_ADDR_MCAST) {
505                         if (needs_conn) {
506                                 res = -EOPNOTSUPP;
507                                 goto exit;
508                         }
509                         if ((res = dest_name_check(dest, m)))
510                                 goto exit;
511                         res = tipc_multicast(tsock->p->ref,
512                                              &dest->addr.nameseq,
513                                              0,
514                                              m->msg_iovlen,
515                                              m->msg_iov);
516                 }
517                 if (likely(res != -ELINKCONG)) {
518 exit:
519                         mutex_unlock(&tsock->lock);
520                         return res;
521                 }
522                 if (m->msg_flags & MSG_DONTWAIT) {
523                         res = -EWOULDBLOCK;
524                         goto exit;
525                 }
526                 if (wait_event_interruptible(*sock->sk->sk_sleep,
527                                              !tsock->p->congested)) {
528                     res = -ERESTARTSYS;
529                     goto exit;
530                 }
531         } while (1);
532 }
533
534 /**
535  * send_packet - send a connection-oriented message
536  * @iocb: (unused)
537  * @sock: socket structure
538  * @m: message to send
539  * @total_len: length of message
540  *
541  * Used for SOCK_SEQPACKET messages and SOCK_STREAM data.
542  *
543  * Returns the number of bytes sent on success, or errno otherwise
544  */
545
546 static int send_packet(struct kiocb *iocb, struct socket *sock,
547                        struct msghdr *m, size_t total_len)
548 {
549         struct tipc_sock *tsock = tipc_sk(sock->sk);
550         struct sockaddr_tipc *dest = (struct sockaddr_tipc *)m->msg_name;
551         int res;
552
553         /* Handle implied connection establishment */
554
555         if (unlikely(dest))
556                 return send_msg(iocb, sock, m, total_len);
557
558         if (mutex_lock_interruptible(&tsock->lock)) {
559                 return -ERESTARTSYS;
560         }
561
562         do {
563                 if (unlikely(sock->state != SS_CONNECTED)) {
564                         if (sock->state == SS_DISCONNECTING)
565                                 res = -EPIPE;
566                         else
567                                 res = -ENOTCONN;
568                         goto exit;
569                 }
570
571                 res = tipc_send(tsock->p->ref, m->msg_iovlen, m->msg_iov);
572                 if (likely(res != -ELINKCONG)) {
573 exit:
574                         mutex_unlock(&tsock->lock);
575                         return res;
576                 }
577                 if (m->msg_flags & MSG_DONTWAIT) {
578                         res = -EWOULDBLOCK;
579                         goto exit;
580                 }
581                 if (wait_event_interruptible(*sock->sk->sk_sleep,
582                                              !tsock->p->congested)) {
583                     res = -ERESTARTSYS;
584                     goto exit;
585                 }
586         } while (1);
587 }
588
589 /**
590  * send_stream - send stream-oriented data
591  * @iocb: (unused)
592  * @sock: socket structure
593  * @m: data to send
594  * @total_len: total length of data to be sent
595  *
596  * Used for SOCK_STREAM data.
597  *
598  * Returns the number of bytes sent on success (or partial success),
599  * or errno if no data sent
600  */
601
602
603 static int send_stream(struct kiocb *iocb, struct socket *sock,
604                        struct msghdr *m, size_t total_len)
605 {
606         struct tipc_port *tport;
607         struct msghdr my_msg;
608         struct iovec my_iov;
609         struct iovec *curr_iov;
610         int curr_iovlen;
611         char __user *curr_start;
612         u32 hdr_size;
613         int curr_left;
614         int bytes_to_send;
615         int bytes_sent;
616         int res;
617
618         /* Handle special cases where there is no connection */
619
620         if (unlikely(sock->state != SS_CONNECTED)) {
621                 if (sock->state == SS_UNCONNECTED)
622                         return send_packet(iocb, sock, m, total_len);
623                 else if (sock->state == SS_DISCONNECTING)
624                         return -EPIPE;
625                 else
626                         return -ENOTCONN;
627         }
628
629         if (unlikely(m->msg_name))
630                 return -EISCONN;
631
632         /*
633          * Send each iovec entry using one or more messages
634          *
635          * Note: This algorithm is good for the most likely case
636          * (i.e. one large iovec entry), but could be improved to pass sets
637          * of small iovec entries into send_packet().
638          */
639
640         curr_iov = m->msg_iov;
641         curr_iovlen = m->msg_iovlen;
642         my_msg.msg_iov = &my_iov;
643         my_msg.msg_iovlen = 1;
644         my_msg.msg_flags = m->msg_flags;
645         my_msg.msg_name = NULL;
646         bytes_sent = 0;
647
648         tport = tipc_sk(sock->sk)->p;
649         hdr_size = msg_hdr_sz(&tport->phdr);
650
651         while (curr_iovlen--) {
652                 curr_start = curr_iov->iov_base;
653                 curr_left = curr_iov->iov_len;
654
655                 while (curr_left) {
656                         bytes_to_send = tport->max_pkt - hdr_size;
657                         if (bytes_to_send > TIPC_MAX_USER_MSG_SIZE)
658                                 bytes_to_send = TIPC_MAX_USER_MSG_SIZE;
659                         if (curr_left < bytes_to_send)
660                                 bytes_to_send = curr_left;
661                         my_iov.iov_base = curr_start;
662                         my_iov.iov_len = bytes_to_send;
663                         if ((res = send_packet(iocb, sock, &my_msg, 0)) < 0) {
664                                 if (bytes_sent != 0)
665                                         res = bytes_sent;
666                                 return res;
667                         }
668                         curr_left -= bytes_to_send;
669                         curr_start += bytes_to_send;
670                         bytes_sent += bytes_to_send;
671                 }
672
673                 curr_iov++;
674         }
675
676         return bytes_sent;
677 }
678
679 /**
680  * auto_connect - complete connection setup to a remote port
681  * @sock: socket structure
682  * @tsock: TIPC-specific socket structure
683  * @msg: peer's response message
684  *
685  * Returns 0 on success, errno otherwise
686  */
687
688 static int auto_connect(struct socket *sock, struct tipc_sock *tsock,
689                         struct tipc_msg *msg)
690 {
691         struct tipc_portid peer;
692
693         if (msg_errcode(msg)) {
694                 sock->state = SS_DISCONNECTING;
695                 return -ECONNREFUSED;
696         }
697
698         peer.ref = msg_origport(msg);
699         peer.node = msg_orignode(msg);
700         tipc_connect2port(tsock->p->ref, &peer);
701         tipc_set_portimportance(tsock->p->ref, msg_importance(msg));
702         sock->state = SS_CONNECTED;
703         return 0;
704 }
705
706 /**
707  * set_orig_addr - capture sender's address for received message
708  * @m: descriptor for message info
709  * @msg: received message header
710  *
711  * Note: Address is not captured if not requested by receiver.
712  */
713
714 static void set_orig_addr(struct msghdr *m, struct tipc_msg *msg)
715 {
716         struct sockaddr_tipc *addr = (struct sockaddr_tipc *)m->msg_name;
717
718         if (addr) {
719                 addr->family = AF_TIPC;
720                 addr->addrtype = TIPC_ADDR_ID;
721                 addr->addr.id.ref = msg_origport(msg);
722                 addr->addr.id.node = msg_orignode(msg);
723                 addr->addr.name.domain = 0;     /* could leave uninitialized */
724                 addr->scope = 0;                /* could leave uninitialized */
725                 m->msg_namelen = sizeof(struct sockaddr_tipc);
726         }
727 }
728
729 /**
730  * anc_data_recv - optionally capture ancillary data for received message
731  * @m: descriptor for message info
732  * @msg: received message header
733  * @tport: TIPC port associated with message
734  *
735  * Note: Ancillary data is not captured if not requested by receiver.
736  *
737  * Returns 0 if successful, otherwise errno
738  */
739
740 static int anc_data_recv(struct msghdr *m, struct tipc_msg *msg,
741                                 struct tipc_port *tport)
742 {
743         u32 anc_data[3];
744         u32 err;
745         u32 dest_type;
746         int has_name;
747         int res;
748
749         if (likely(m->msg_controllen == 0))
750                 return 0;
751
752         /* Optionally capture errored message object(s) */
753
754         err = msg ? msg_errcode(msg) : 0;
755         if (unlikely(err)) {
756                 anc_data[0] = err;
757                 anc_data[1] = msg_data_sz(msg);
758                 if ((res = put_cmsg(m, SOL_TIPC, TIPC_ERRINFO, 8, anc_data)))
759                         return res;
760                 if (anc_data[1] &&
761                     (res = put_cmsg(m, SOL_TIPC, TIPC_RETDATA, anc_data[1],
762                                     msg_data(msg))))
763                         return res;
764         }
765
766         /* Optionally capture message destination object */
767
768         dest_type = msg ? msg_type(msg) : TIPC_DIRECT_MSG;
769         switch (dest_type) {
770         case TIPC_NAMED_MSG:
771                 has_name = 1;
772                 anc_data[0] = msg_nametype(msg);
773                 anc_data[1] = msg_namelower(msg);
774                 anc_data[2] = msg_namelower(msg);
775                 break;
776         case TIPC_MCAST_MSG:
777                 has_name = 1;
778                 anc_data[0] = msg_nametype(msg);
779                 anc_data[1] = msg_namelower(msg);
780                 anc_data[2] = msg_nameupper(msg);
781                 break;
782         case TIPC_CONN_MSG:
783                 has_name = (tport->conn_type != 0);
784                 anc_data[0] = tport->conn_type;
785                 anc_data[1] = tport->conn_instance;
786                 anc_data[2] = tport->conn_instance;
787                 break;
788         default:
789                 has_name = 0;
790         }
791         if (has_name &&
792             (res = put_cmsg(m, SOL_TIPC, TIPC_DESTNAME, 12, anc_data)))
793                 return res;
794
795         return 0;
796 }
797
798 /**
799  * recv_msg - receive packet-oriented message
800  * @iocb: (unused)
801  * @m: descriptor for message info
802  * @buf_len: total size of user buffer area
803  * @flags: receive flags
804  *
805  * Used for SOCK_DGRAM, SOCK_RDM, and SOCK_SEQPACKET messages.
806  * If the complete message doesn't fit in user area, truncate it.
807  *
808  * Returns size of returned message data, errno otherwise
809  */
810
811 static int recv_msg(struct kiocb *iocb, struct socket *sock,
812                     struct msghdr *m, size_t buf_len, int flags)
813 {
814         struct tipc_sock *tsock = tipc_sk(sock->sk);
815         struct sk_buff *buf;
816         struct tipc_msg *msg;
817         unsigned int q_len;
818         unsigned int sz;
819         u32 err;
820         int res;
821
822         /* Currently doesn't support receiving into multiple iovec entries */
823
824         if (m->msg_iovlen != 1)
825                 return -EOPNOTSUPP;
826
827         /* Catch invalid receive attempts */
828
829         if (unlikely(!buf_len))
830                 return -EINVAL;
831
832         if (sock->type == SOCK_SEQPACKET) {
833                 if (unlikely(sock->state == SS_UNCONNECTED))
834                         return -ENOTCONN;
835                 if (unlikely((sock->state == SS_DISCONNECTING) &&
836                              (skb_queue_len(&sock->sk->sk_receive_queue) == 0)))
837                         return -ENOTCONN;
838         }
839
840         /* Look for a message in receive queue; wait if necessary */
841
842         if (unlikely(mutex_lock_interruptible(&tsock->lock)))
843                 return -ERESTARTSYS;
844
845 restart:
846         if (unlikely((skb_queue_len(&sock->sk->sk_receive_queue) == 0) &&
847                      (flags & MSG_DONTWAIT))) {
848                 res = -EWOULDBLOCK;
849                 goto exit;
850         }
851
852         if ((res = wait_event_interruptible(
853                 *sock->sk->sk_sleep,
854                 ((q_len = skb_queue_len(&sock->sk->sk_receive_queue)) ||
855                  (sock->state == SS_DISCONNECTING))) )) {
856                 goto exit;
857         }
858
859         /* Catch attempt to receive on an already terminated connection */
860         /* [THIS CHECK MAY OVERLAP WITH AN EARLIER CHECK] */
861
862         if (!q_len) {
863                 res = -ENOTCONN;
864                 goto exit;
865         }
866
867         /* Get access to first message in receive queue */
868
869         buf = skb_peek(&sock->sk->sk_receive_queue);
870         msg = buf_msg(buf);
871         sz = msg_data_sz(msg);
872         err = msg_errcode(msg);
873
874         /* Complete connection setup for an implied connect */
875
876         if (unlikely(sock->state == SS_CONNECTING)) {
877                 if ((res = auto_connect(sock, tsock, msg)))
878                         goto exit;
879         }
880
881         /* Discard an empty non-errored message & try again */
882
883         if ((!sz) && (!err)) {
884                 advance_queue(tsock);
885                 goto restart;
886         }
887
888         /* Capture sender's address (optional) */
889
890         set_orig_addr(m, msg);
891
892         /* Capture ancillary data (optional) */
893
894         if ((res = anc_data_recv(m, msg, tsock->p)))
895                 goto exit;
896
897         /* Capture message data (if valid) & compute return value (always) */
898
899         if (!err) {
900                 if (unlikely(buf_len < sz)) {
901                         sz = buf_len;
902                         m->msg_flags |= MSG_TRUNC;
903                 }
904                 if (unlikely(copy_to_user(m->msg_iov->iov_base, msg_data(msg),
905                                           sz))) {
906                         res = -EFAULT;
907                         goto exit;
908                 }
909                 res = sz;
910         } else {
911                 if ((sock->state == SS_READY) ||
912                     ((err == TIPC_CONN_SHUTDOWN) || m->msg_control))
913                         res = 0;
914                 else
915                         res = -ECONNRESET;
916         }
917
918         /* Consume received message (optional) */
919
920         if (likely(!(flags & MSG_PEEK))) {
921                 if (unlikely(++tsock->p->conn_unacked >= TIPC_FLOW_CONTROL_WIN))
922                         tipc_acknowledge(tsock->p->ref, tsock->p->conn_unacked);
923                 advance_queue(tsock);
924         }
925 exit:
926         mutex_unlock(&tsock->lock);
927         return res;
928 }
929
930 /**
931  * recv_stream - receive stream-oriented data
932  * @iocb: (unused)
933  * @m: descriptor for message info
934  * @buf_len: total size of user buffer area
935  * @flags: receive flags
936  *
937  * Used for SOCK_STREAM messages only.  If not enough data is available
938  * will optionally wait for more; never truncates data.
939  *
940  * Returns size of returned message data, errno otherwise
941  */
942
943 static int recv_stream(struct kiocb *iocb, struct socket *sock,
944                        struct msghdr *m, size_t buf_len, int flags)
945 {
946         struct tipc_sock *tsock = tipc_sk(sock->sk);
947         struct sk_buff *buf;
948         struct tipc_msg *msg;
949         unsigned int q_len;
950         unsigned int sz;
951         int sz_to_copy;
952         int sz_copied = 0;
953         int needed;
954         char __user *crs = m->msg_iov->iov_base;
955         unsigned char *buf_crs;
956         u32 err;
957         int res;
958
959         /* Currently doesn't support receiving into multiple iovec entries */
960
961         if (m->msg_iovlen != 1)
962                 return -EOPNOTSUPP;
963
964         /* Catch invalid receive attempts */
965
966         if (unlikely(!buf_len))
967                 return -EINVAL;
968
969         if (unlikely(sock->state == SS_DISCONNECTING)) {
970                 if (skb_queue_len(&sock->sk->sk_receive_queue) == 0)
971                         return -ENOTCONN;
972         } else if (unlikely(sock->state != SS_CONNECTED))
973                 return -ENOTCONN;
974
975         /* Look for a message in receive queue; wait if necessary */
976
977         if (unlikely(mutex_lock_interruptible(&tsock->lock)))
978                 return -ERESTARTSYS;
979
980 restart:
981         if (unlikely((skb_queue_len(&sock->sk->sk_receive_queue) == 0) &&
982                      (flags & MSG_DONTWAIT))) {
983                 res = -EWOULDBLOCK;
984                 goto exit;
985         }
986
987         if ((res = wait_event_interruptible(
988                 *sock->sk->sk_sleep,
989                 ((q_len = skb_queue_len(&sock->sk->sk_receive_queue)) ||
990                  (sock->state == SS_DISCONNECTING))) )) {
991                 goto exit;
992         }
993
994         /* Catch attempt to receive on an already terminated connection */
995         /* [THIS CHECK MAY OVERLAP WITH AN EARLIER CHECK] */
996
997         if (!q_len) {
998                 res = -ENOTCONN;
999                 goto exit;
1000         }
1001
1002         /* Get access to first message in receive queue */
1003
1004         buf = skb_peek(&sock->sk->sk_receive_queue);
1005         msg = buf_msg(buf);
1006         sz = msg_data_sz(msg);
1007         err = msg_errcode(msg);
1008
1009         /* Discard an empty non-errored message & try again */
1010
1011         if ((!sz) && (!err)) {
1012                 advance_queue(tsock);
1013                 goto restart;
1014         }
1015
1016         /* Optionally capture sender's address & ancillary data of first msg */
1017
1018         if (sz_copied == 0) {
1019                 set_orig_addr(m, msg);
1020                 if ((res = anc_data_recv(m, msg, tsock->p)))
1021                         goto exit;
1022         }
1023
1024         /* Capture message data (if valid) & compute return value (always) */
1025
1026         if (!err) {
1027                 buf_crs = (unsigned char *)(TIPC_SKB_CB(buf)->handle);
1028                 sz = skb_tail_pointer(buf) - buf_crs;
1029
1030                 needed = (buf_len - sz_copied);
1031                 sz_to_copy = (sz <= needed) ? sz : needed;
1032                 if (unlikely(copy_to_user(crs, buf_crs, sz_to_copy))) {
1033                         res = -EFAULT;
1034                         goto exit;
1035                 }
1036                 sz_copied += sz_to_copy;
1037
1038                 if (sz_to_copy < sz) {
1039                         if (!(flags & MSG_PEEK))
1040                                 TIPC_SKB_CB(buf)->handle = buf_crs + sz_to_copy;
1041                         goto exit;
1042                 }
1043
1044                 crs += sz_to_copy;
1045         } else {
1046                 if (sz_copied != 0)
1047                         goto exit; /* can't add error msg to valid data */
1048
1049                 if ((err == TIPC_CONN_SHUTDOWN) || m->msg_control)
1050                         res = 0;
1051                 else
1052                         res = -ECONNRESET;
1053         }
1054
1055         /* Consume received message (optional) */
1056
1057         if (likely(!(flags & MSG_PEEK))) {
1058                 if (unlikely(++tsock->p->conn_unacked >= TIPC_FLOW_CONTROL_WIN))
1059                         tipc_acknowledge(tsock->p->ref, tsock->p->conn_unacked);
1060                 advance_queue(tsock);
1061         }
1062
1063         /* Loop around if more data is required */
1064
1065         if ((sz_copied < buf_len)    /* didn't get all requested data */
1066             && (flags & MSG_WAITALL) /* ... and need to wait for more */
1067             && (!(flags & MSG_PEEK)) /* ... and aren't just peeking at data */
1068             && (!err)                /* ... and haven't reached a FIN */
1069             )
1070                 goto restart;
1071
1072 exit:
1073         mutex_unlock(&tsock->lock);
1074         return sz_copied ? sz_copied : res;
1075 }
1076
1077 /**
1078  * queue_overloaded - test if queue overload condition exists
1079  * @queue_size: current size of queue
1080  * @base: nominal maximum size of queue
1081  * @msg: message to be added to queue
1082  *
1083  * Returns 1 if queue is currently overloaded, 0 otherwise
1084  */
1085
1086 static int queue_overloaded(u32 queue_size, u32 base, struct tipc_msg *msg)
1087 {
1088         u32 threshold;
1089         u32 imp = msg_importance(msg);
1090
1091         if (imp == TIPC_LOW_IMPORTANCE)
1092                 threshold = base;
1093         else if (imp == TIPC_MEDIUM_IMPORTANCE)
1094                 threshold = base * 2;
1095         else if (imp == TIPC_HIGH_IMPORTANCE)
1096                 threshold = base * 100;
1097         else
1098                 return 0;
1099
1100         if (msg_connected(msg))
1101                 threshold *= 4;
1102
1103         return (queue_size > threshold);
1104 }
1105
1106 /**
1107  * async_disconnect - wrapper function used to disconnect port
1108  * @portref: TIPC port reference (passed as pointer-sized value)
1109  */
1110
1111 static void async_disconnect(unsigned long portref)
1112 {
1113         tipc_disconnect((u32)portref);
1114 }
1115
1116 /**
1117  * dispatch - handle arriving message
1118  * @tport: TIPC port that received message
1119  * @buf: message
1120  *
1121  * Called with port locked.  Must not take socket lock to avoid deadlock risk.
1122  *
1123  * Returns TIPC error status code (TIPC_OK if message is not to be rejected)
1124  */
1125
1126 static u32 dispatch(struct tipc_port *tport, struct sk_buff *buf)
1127 {
1128         struct tipc_msg *msg = buf_msg(buf);
1129         struct tipc_sock *tsock = (struct tipc_sock *)tport->usr_handle;
1130         struct socket *sock;
1131         u32 recv_q_len;
1132
1133         /* Reject message if socket is closing */
1134
1135         if (!tsock)
1136                 return TIPC_ERR_NO_PORT;
1137
1138         /* Reject message if it is wrong sort of message for socket */
1139
1140         /*
1141          * WOULD IT BE BETTER TO JUST DISCARD THESE MESSAGES INSTEAD?
1142          * "NO PORT" ISN'T REALLY THE RIGHT ERROR CODE, AND THERE MAY
1143          * BE SECURITY IMPLICATIONS INHERENT IN REJECTING INVALID TRAFFIC
1144          */
1145         sock = tsock->sk.sk_socket;
1146         if (sock->state == SS_READY) {
1147                 if (msg_connected(msg)) {
1148                         msg_dbg(msg, "dispatch filter 1\n");
1149                         return TIPC_ERR_NO_PORT;
1150                 }
1151         } else {
1152                 if (msg_mcast(msg)) {
1153                         msg_dbg(msg, "dispatch filter 2\n");
1154                         return TIPC_ERR_NO_PORT;
1155                 }
1156                 if (sock->state == SS_CONNECTED) {
1157                         if (!msg_connected(msg)) {
1158                                 msg_dbg(msg, "dispatch filter 3\n");
1159                                 return TIPC_ERR_NO_PORT;
1160                         }
1161                 }
1162                 else if (sock->state == SS_CONNECTING) {
1163                         if (!msg_connected(msg) && (msg_errcode(msg) == 0)) {
1164                                 msg_dbg(msg, "dispatch filter 4\n");
1165                                 return TIPC_ERR_NO_PORT;
1166                         }
1167                 }
1168                 else if (sock->state == SS_LISTENING) {
1169                         if (msg_connected(msg) || msg_errcode(msg)) {
1170                                 msg_dbg(msg, "dispatch filter 5\n");
1171                                 return TIPC_ERR_NO_PORT;
1172                         }
1173                 }
1174                 else if (sock->state == SS_DISCONNECTING) {
1175                         msg_dbg(msg, "dispatch filter 6\n");
1176                         return TIPC_ERR_NO_PORT;
1177                 }
1178                 else /* (sock->state == SS_UNCONNECTED) */ {
1179                         if (msg_connected(msg) || msg_errcode(msg)) {
1180                                 msg_dbg(msg, "dispatch filter 7\n");
1181                                 return TIPC_ERR_NO_PORT;
1182                         }
1183                 }
1184         }
1185
1186         /* Reject message if there isn't room to queue it */
1187
1188         if (unlikely((u32)atomic_read(&tipc_queue_size) >
1189                      OVERLOAD_LIMIT_BASE)) {
1190                 if (queue_overloaded(atomic_read(&tipc_queue_size),
1191                                      OVERLOAD_LIMIT_BASE, msg))
1192                         return TIPC_ERR_OVERLOAD;
1193         }
1194         recv_q_len = skb_queue_len(&tsock->sk.sk_receive_queue);
1195         if (unlikely(recv_q_len > (OVERLOAD_LIMIT_BASE / 2))) {
1196                 if (queue_overloaded(recv_q_len,
1197                                      OVERLOAD_LIMIT_BASE / 2, msg))
1198                         return TIPC_ERR_OVERLOAD;
1199         }
1200
1201         /* Initiate connection termination for an incoming 'FIN' */
1202
1203         if (unlikely(msg_errcode(msg) && (sock->state == SS_CONNECTED))) {
1204                 sock->state = SS_DISCONNECTING;
1205                 /* Note: Use signal since port lock is already taken! */
1206                 tipc_k_signal((Handler)async_disconnect, tport->ref);
1207         }
1208
1209         /* Enqueue message (finally!) */
1210
1211         msg_dbg(msg,"<DISP<: ");
1212         TIPC_SKB_CB(buf)->handle = msg_data(msg);
1213         atomic_inc(&tipc_queue_size);
1214         skb_queue_tail(&sock->sk->sk_receive_queue, buf);
1215
1216         if (waitqueue_active(sock->sk->sk_sleep))
1217                 wake_up_interruptible(sock->sk->sk_sleep);
1218         return TIPC_OK;
1219 }
1220
1221 /**
1222  * wakeupdispatch - wake up port after congestion
1223  * @tport: port to wakeup
1224  *
1225  * Called with port lock on.
1226  */
1227
1228 static void wakeupdispatch(struct tipc_port *tport)
1229 {
1230         struct tipc_sock *tsock = (struct tipc_sock *)tport->usr_handle;
1231
1232         if (waitqueue_active(tsock->sk.sk_sleep))
1233                 wake_up_interruptible(tsock->sk.sk_sleep);
1234 }
1235
1236 /**
1237  * connect - establish a connection to another TIPC port
1238  * @sock: socket structure
1239  * @dest: socket address for destination port
1240  * @destlen: size of socket address data structure
1241  * @flags: (unused)
1242  *
1243  * Returns 0 on success, errno otherwise
1244  */
1245
1246 static int connect(struct socket *sock, struct sockaddr *dest, int destlen,
1247                    int flags)
1248 {
1249    struct tipc_sock *tsock = tipc_sk(sock->sk);
1250    struct sockaddr_tipc *dst = (struct sockaddr_tipc *)dest;
1251    struct msghdr m = {NULL,};
1252    struct sk_buff *buf;
1253    struct tipc_msg *msg;
1254    int res;
1255
1256    /* For now, TIPC does not allow use of connect() with DGRAM or RDM types */
1257
1258    if (sock->state == SS_READY)
1259            return -EOPNOTSUPP;
1260
1261    /* Issue Posix-compliant error code if socket is in the wrong state */
1262
1263    if (sock->state == SS_LISTENING)
1264            return -EOPNOTSUPP;
1265    if (sock->state == SS_CONNECTING)
1266            return -EALREADY;
1267    if (sock->state != SS_UNCONNECTED)
1268            return -EISCONN;
1269
1270    /*
1271     * Reject connection attempt using multicast address
1272     *
1273     * Note: send_msg() validates the rest of the address fields,
1274     *       so there's no need to do it here
1275     */
1276
1277    if (dst->addrtype == TIPC_ADDR_MCAST)
1278            return -EINVAL;
1279
1280    /* Send a 'SYN-' to destination */
1281
1282    m.msg_name = dest;
1283    m.msg_namelen = destlen;
1284    if ((res = send_msg(NULL, sock, &m, 0)) < 0) {
1285            sock->state = SS_DISCONNECTING;
1286            return res;
1287    }
1288
1289    if (mutex_lock_interruptible(&tsock->lock))
1290            return -ERESTARTSYS;
1291
1292    /* Wait for destination's 'ACK' response */
1293
1294    res = wait_event_interruptible_timeout(*sock->sk->sk_sleep,
1295                                           skb_queue_len(&sock->sk->sk_receive_queue),
1296                                           sock->sk->sk_rcvtimeo);
1297    buf = skb_peek(&sock->sk->sk_receive_queue);
1298    if (res > 0) {
1299            msg = buf_msg(buf);
1300            res = auto_connect(sock, tsock, msg);
1301            if (!res) {
1302                    if (!msg_data_sz(msg))
1303                            advance_queue(tsock);
1304            }
1305    } else {
1306            if (res == 0) {
1307                    res = -ETIMEDOUT;
1308            } else
1309                    { /* leave "res" unchanged */ }
1310            sock->state = SS_DISCONNECTING;
1311    }
1312
1313    mutex_unlock(&tsock->lock);
1314    return res;
1315 }
1316
1317 /**
1318  * listen - allow socket to listen for incoming connections
1319  * @sock: socket structure
1320  * @len: (unused)
1321  *
1322  * Returns 0 on success, errno otherwise
1323  */
1324
1325 static int listen(struct socket *sock, int len)
1326 {
1327         /* REQUIRES SOCKET LOCKING OF SOME SORT? */
1328
1329         if (sock->state == SS_READY)
1330                 return -EOPNOTSUPP;
1331         if (sock->state != SS_UNCONNECTED)
1332                 return -EINVAL;
1333         sock->state = SS_LISTENING;
1334         return 0;
1335 }
1336
1337 /**
1338  * accept - wait for connection request
1339  * @sock: listening socket
1340  * @newsock: new socket that is to be connected
1341  * @flags: file-related flags associated with socket
1342  *
1343  * Returns 0 on success, errno otherwise
1344  */
1345
1346 static int accept(struct socket *sock, struct socket *newsock, int flags)
1347 {
1348         struct tipc_sock *tsock = tipc_sk(sock->sk);
1349         struct sk_buff *buf;
1350         int res = -EFAULT;
1351
1352         if (sock->state == SS_READY)
1353                 return -EOPNOTSUPP;
1354         if (sock->state != SS_LISTENING)
1355                 return -EINVAL;
1356
1357         if (unlikely((skb_queue_len(&sock->sk->sk_receive_queue) == 0) &&
1358                      (flags & O_NONBLOCK)))
1359                 return -EWOULDBLOCK;
1360
1361         if (mutex_lock_interruptible(&tsock->lock))
1362                 return -ERESTARTSYS;
1363
1364         if (wait_event_interruptible(*sock->sk->sk_sleep,
1365                                      skb_queue_len(&sock->sk->sk_receive_queue))) {
1366                 res = -ERESTARTSYS;
1367                 goto exit;
1368         }
1369         buf = skb_peek(&sock->sk->sk_receive_queue);
1370
1371         res = tipc_create(sock_net(sock->sk), newsock, 0);
1372         if (!res) {
1373                 struct tipc_sock *new_tsock = tipc_sk(newsock->sk);
1374                 struct tipc_portid id;
1375                 struct tipc_msg *msg = buf_msg(buf);
1376                 u32 new_ref = new_tsock->p->ref;
1377
1378                 id.ref = msg_origport(msg);
1379                 id.node = msg_orignode(msg);
1380                 tipc_connect2port(new_ref, &id);
1381                 newsock->state = SS_CONNECTED;
1382
1383                 tipc_set_portimportance(new_ref, msg_importance(msg));
1384                 if (msg_named(msg)) {
1385                         new_tsock->p->conn_type = msg_nametype(msg);
1386                         new_tsock->p->conn_instance = msg_nameinst(msg);
1387                 }
1388
1389                /*
1390                  * Respond to 'SYN-' by discarding it & returning 'ACK'-.
1391                  * Respond to 'SYN+' by queuing it on new socket.
1392                  */
1393
1394                 msg_dbg(msg,"<ACC<: ");
1395                 if (!msg_data_sz(msg)) {
1396                         struct msghdr m = {NULL,};
1397
1398                         send_packet(NULL, newsock, &m, 0);
1399                         advance_queue(tsock);
1400                 } else {
1401                         sock_lock(tsock);
1402                         skb_dequeue(&sock->sk->sk_receive_queue);
1403                         sock_unlock(tsock);
1404                         skb_queue_head(&newsock->sk->sk_receive_queue, buf);
1405                 }
1406         }
1407 exit:
1408         mutex_unlock(&tsock->lock);
1409         return res;
1410 }
1411
1412 /**
1413  * shutdown - shutdown socket connection
1414  * @sock: socket structure
1415  * @how: direction to close (must be SHUT_RDWR)
1416  *
1417  * Terminates connection (if necessary), then purges socket's receive queue.
1418  *
1419  * Returns 0 on success, errno otherwise
1420  */
1421
1422 static int shutdown(struct socket *sock, int how)
1423 {
1424         struct tipc_sock* tsock = tipc_sk(sock->sk);
1425         struct sk_buff *buf;
1426         int res;
1427
1428         if (how != SHUT_RDWR)
1429                 return -EINVAL;
1430
1431         if (mutex_lock_interruptible(&tsock->lock))
1432                 return -ERESTARTSYS;
1433
1434         sock_lock(tsock);
1435
1436         switch (sock->state) {
1437         case SS_CONNECTED:
1438
1439                 /* Send 'FIN+' or 'FIN-' message to peer */
1440
1441                 sock_unlock(tsock);
1442 restart:
1443                 if ((buf = skb_dequeue(&sock->sk->sk_receive_queue))) {
1444                         atomic_dec(&tipc_queue_size);
1445                         if (TIPC_SKB_CB(buf)->handle != msg_data(buf_msg(buf))) {
1446                                 buf_discard(buf);
1447                                 goto restart;
1448                         }
1449                         tipc_reject_msg(buf, TIPC_CONN_SHUTDOWN);
1450                 }
1451                 else {
1452                         tipc_shutdown(tsock->p->ref);
1453                 }
1454                 sock_lock(tsock);
1455
1456                 /* fall through */
1457
1458         case SS_DISCONNECTING:
1459
1460                 /* Discard any unreceived messages */
1461
1462                 while ((buf = skb_dequeue(&sock->sk->sk_receive_queue))) {
1463                         atomic_dec(&tipc_queue_size);
1464                         buf_discard(buf);
1465                 }
1466                 tsock->p->conn_unacked = 0;
1467
1468                 /* fall through */
1469
1470         case SS_CONNECTING:
1471                 sock->state = SS_DISCONNECTING;
1472                 res = 0;
1473                 break;
1474
1475         default:
1476                 res = -ENOTCONN;
1477         }
1478
1479         sock_unlock(tsock);
1480
1481         mutex_unlock(&tsock->lock);
1482         return res;
1483 }
1484
1485 /**
1486  * setsockopt - set socket option
1487  * @sock: socket structure
1488  * @lvl: option level
1489  * @opt: option identifier
1490  * @ov: pointer to new option value
1491  * @ol: length of option value
1492  *
1493  * For stream sockets only, accepts and ignores all IPPROTO_TCP options
1494  * (to ease compatibility).
1495  *
1496  * Returns 0 on success, errno otherwise
1497  */
1498
1499 static int setsockopt(struct socket *sock,
1500                       int lvl, int opt, char __user *ov, int ol)
1501 {
1502         struct tipc_sock *tsock = tipc_sk(sock->sk);
1503         u32 value;
1504         int res;
1505
1506         if ((lvl == IPPROTO_TCP) && (sock->type == SOCK_STREAM))
1507                 return 0;
1508         if (lvl != SOL_TIPC)
1509                 return -ENOPROTOOPT;
1510         if (ol < sizeof(value))
1511                 return -EINVAL;
1512         if ((res = get_user(value, (u32 __user *)ov)))
1513                 return res;
1514
1515         if (mutex_lock_interruptible(&tsock->lock))
1516                 return -ERESTARTSYS;
1517
1518         switch (opt) {
1519         case TIPC_IMPORTANCE:
1520                 res = tipc_set_portimportance(tsock->p->ref, value);
1521                 break;
1522         case TIPC_SRC_DROPPABLE:
1523                 if (sock->type != SOCK_STREAM)
1524                         res = tipc_set_portunreliable(tsock->p->ref, value);
1525                 else
1526                         res = -ENOPROTOOPT;
1527                 break;
1528         case TIPC_DEST_DROPPABLE:
1529                 res = tipc_set_portunreturnable(tsock->p->ref, value);
1530                 break;
1531         case TIPC_CONN_TIMEOUT:
1532                 sock->sk->sk_rcvtimeo = (value * HZ / 1000);
1533                 break;
1534         default:
1535                 res = -EINVAL;
1536         }
1537
1538         mutex_unlock(&tsock->lock);
1539         return res;
1540 }
1541
1542 /**
1543  * getsockopt - get socket option
1544  * @sock: socket structure
1545  * @lvl: option level
1546  * @opt: option identifier
1547  * @ov: receptacle for option value
1548  * @ol: receptacle for length of option value
1549  *
1550  * For stream sockets only, returns 0 length result for all IPPROTO_TCP options
1551  * (to ease compatibility).
1552  *
1553  * Returns 0 on success, errno otherwise
1554  */
1555
1556 static int getsockopt(struct socket *sock,
1557                       int lvl, int opt, char __user *ov, int __user *ol)
1558 {
1559         struct tipc_sock *tsock = tipc_sk(sock->sk);
1560         int len;
1561         u32 value;
1562         int res;
1563
1564         if ((lvl == IPPROTO_TCP) && (sock->type == SOCK_STREAM))
1565                 return put_user(0, ol);
1566         if (lvl != SOL_TIPC)
1567                 return -ENOPROTOOPT;
1568         if ((res = get_user(len, ol)))
1569                 return res;
1570
1571         if (mutex_lock_interruptible(&tsock->lock))
1572                 return -ERESTARTSYS;
1573
1574         switch (opt) {
1575         case TIPC_IMPORTANCE:
1576                 res = tipc_portimportance(tsock->p->ref, &value);
1577                 break;
1578         case TIPC_SRC_DROPPABLE:
1579                 res = tipc_portunreliable(tsock->p->ref, &value);
1580                 break;
1581         case TIPC_DEST_DROPPABLE:
1582                 res = tipc_portunreturnable(tsock->p->ref, &value);
1583                 break;
1584         case TIPC_CONN_TIMEOUT:
1585                 value = (sock->sk->sk_rcvtimeo * 1000) / HZ;
1586                 break;
1587         default:
1588                 res = -EINVAL;
1589         }
1590
1591         if (res) {
1592                 /* "get" failed */
1593         }
1594         else if (len < sizeof(value)) {
1595                 res = -EINVAL;
1596         }
1597         else if ((res = copy_to_user(ov, &value, sizeof(value)))) {
1598                 /* couldn't return value */
1599         }
1600         else {
1601                 res = put_user(sizeof(value), ol);
1602         }
1603
1604         mutex_unlock(&tsock->lock);
1605         return res;
1606 }
1607
1608 /**
1609  * Protocol switches for the various types of TIPC sockets
1610  */
1611
1612 static const struct proto_ops msg_ops = {
1613         .owner          = THIS_MODULE,
1614         .family         = AF_TIPC,
1615         .release        = release,
1616         .bind           = bind,
1617         .connect        = connect,
1618         .socketpair     = sock_no_socketpair,
1619         .accept         = accept,
1620         .getname        = get_name,
1621         .poll           = poll,
1622         .ioctl          = sock_no_ioctl,
1623         .listen         = listen,
1624         .shutdown       = shutdown,
1625         .setsockopt     = setsockopt,
1626         .getsockopt     = getsockopt,
1627         .sendmsg        = send_msg,
1628         .recvmsg        = recv_msg,
1629         .mmap           = sock_no_mmap,
1630         .sendpage       = sock_no_sendpage
1631 };
1632
1633 static const struct proto_ops packet_ops = {
1634         .owner          = THIS_MODULE,
1635         .family         = AF_TIPC,
1636         .release        = release,
1637         .bind           = bind,
1638         .connect        = connect,
1639         .socketpair     = sock_no_socketpair,
1640         .accept         = accept,
1641         .getname        = get_name,
1642         .poll           = poll,
1643         .ioctl          = sock_no_ioctl,
1644         .listen         = listen,
1645         .shutdown       = shutdown,
1646         .setsockopt     = setsockopt,
1647         .getsockopt     = getsockopt,
1648         .sendmsg        = send_packet,
1649         .recvmsg        = recv_msg,
1650         .mmap           = sock_no_mmap,
1651         .sendpage       = sock_no_sendpage
1652 };
1653
1654 static const struct proto_ops stream_ops = {
1655         .owner          = THIS_MODULE,
1656         .family         = AF_TIPC,
1657         .release        = release,
1658         .bind           = bind,
1659         .connect        = connect,
1660         .socketpair     = sock_no_socketpair,
1661         .accept         = accept,
1662         .getname        = get_name,
1663         .poll           = poll,
1664         .ioctl          = sock_no_ioctl,
1665         .listen         = listen,
1666         .shutdown       = shutdown,
1667         .setsockopt     = setsockopt,
1668         .getsockopt     = getsockopt,
1669         .sendmsg        = send_stream,
1670         .recvmsg        = recv_stream,
1671         .mmap           = sock_no_mmap,
1672         .sendpage       = sock_no_sendpage
1673 };
1674
1675 static const struct net_proto_family tipc_family_ops = {
1676         .owner          = THIS_MODULE,
1677         .family         = AF_TIPC,
1678         .create         = tipc_create
1679 };
1680
1681 static struct proto tipc_proto = {
1682         .name           = "TIPC",
1683         .owner          = THIS_MODULE,
1684         .obj_size       = sizeof(struct tipc_sock)
1685 };
1686
1687 /**
1688  * tipc_socket_init - initialize TIPC socket interface
1689  *
1690  * Returns 0 on success, errno otherwise
1691  */
1692 int tipc_socket_init(void)
1693 {
1694         int res;
1695
1696         res = proto_register(&tipc_proto, 1);
1697         if (res) {
1698                 err("Failed to register TIPC protocol type\n");
1699                 goto out;
1700         }
1701
1702         res = sock_register(&tipc_family_ops);
1703         if (res) {
1704                 err("Failed to register TIPC socket type\n");
1705                 proto_unregister(&tipc_proto);
1706                 goto out;
1707         }
1708
1709         sockets_enabled = 1;
1710  out:
1711         return res;
1712 }
1713
1714 /**
1715  * tipc_socket_stop - stop TIPC socket interface
1716  */
1717 void tipc_socket_stop(void)
1718 {
1719         if (!sockets_enabled)
1720                 return;
1721
1722         sockets_enabled = 0;
1723         sock_unregister(tipc_family_ops.family);
1724         proto_unregister(&tipc_proto);
1725 }
1726