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