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