This commit was manufactured by cvs2svn to create tag
[linux-2.6.git] / net / sctp / socket.c
1 /* SCTP kernel reference Implementation
2  * (C) Copyright IBM Corp. 2001, 2004
3  * Copyright (c) 1999-2000 Cisco, Inc.
4  * Copyright (c) 1999-2001 Motorola, Inc.
5  * Copyright (c) 2001-2003 Intel Corp.
6  * Copyright (c) 2001-2002 Nokia, Inc.
7  * Copyright (c) 2001 La Monte H.P. Yarroll
8  *
9  * This file is part of the SCTP kernel reference Implementation
10  *
11  * These functions interface with the sockets layer to implement the
12  * SCTP Extensions for the Sockets API.
13  *
14  * Note that the descriptions from the specification are USER level
15  * functions--this file is the functions which populate the struct proto
16  * for SCTP which is the BOTTOM of the sockets interface.
17  *
18  * The SCTP reference implementation is free software;
19  * you can redistribute it and/or modify it under the terms of
20  * the GNU General Public License as published by
21  * the Free Software Foundation; either version 2, or (at your option)
22  * any later version.
23  *
24  * The SCTP reference implementation is distributed in the hope that it
25  * will be useful, but WITHOUT ANY WARRANTY; without even the implied
26  *                 ************************
27  * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
28  * See the GNU General Public License for more details.
29  *
30  * You should have received a copy of the GNU General Public License
31  * along with GNU CC; see the file COPYING.  If not, write to
32  * the Free Software Foundation, 59 Temple Place - Suite 330,
33  * Boston, MA 02111-1307, USA.
34  *
35  * Please send any bug reports or fixes you make to the
36  * email address(es):
37  *    lksctp developers <lksctp-developers@lists.sourceforge.net>
38  *
39  * Or submit a bug report through the following website:
40  *    http://www.sf.net/projects/lksctp
41  *
42  * Written or modified by:
43  *    La Monte H.P. Yarroll <piggy@acm.org>
44  *    Narasimha Budihal     <narsi@refcode.org>
45  *    Karl Knutson          <karl@athena.chicago.il.us>
46  *    Jon Grimm             <jgrimm@us.ibm.com>
47  *    Xingang Guo           <xingang.guo@intel.com>
48  *    Daisy Chang           <daisyc@us.ibm.com>
49  *    Sridhar Samudrala     <samudrala@us.ibm.com>
50  *    Inaky Perez-Gonzalez  <inaky.gonzalez@intel.com>
51  *    Ardelle Fan           <ardelle.fan@intel.com>
52  *    Ryan Layer            <rmlayer@us.ibm.com>
53  *    Anup Pemmaiah         <pemmaiah@cc.usu.edu>
54  *    Kevin Gao             <kevin.gao@intel.com>
55  *
56  * Any bugs reported given to us we will try to fix... any fixes shared will
57  * be incorporated into the next SCTP release.
58  */
59
60 #include <linux/config.h>
61 #include <linux/types.h>
62 #include <linux/kernel.h>
63 #include <linux/wait.h>
64 #include <linux/time.h>
65 #include <linux/ip.h>
66 #include <linux/fcntl.h>
67 #include <linux/poll.h>
68 #include <linux/init.h>
69 #include <linux/crypto.h>
70
71 #include <net/ip.h>
72 #include <net/icmp.h>
73 #include <net/route.h>
74 #include <net/ipv6.h>
75 #include <net/inet_common.h>
76
77 #include <linux/socket.h> /* for sa_family_t */
78 #include <net/sock.h>
79 #include <net/sctp/sctp.h>
80 #include <net/sctp/sm.h>
81
82 /* WARNING:  Please do not remove the SCTP_STATIC attribute to
83  * any of the functions below as they are used to export functions
84  * used by a project regression testsuite.
85  */
86
87 /* Forward declarations for internal helper functions. */
88 static int sctp_writeable(struct sock *sk);
89 static void sctp_wfree(struct sk_buff *skb);
90 static int sctp_wait_for_sndbuf(struct sctp_association *, long *timeo_p,
91                                 size_t msg_len);
92 static int sctp_wait_for_packet(struct sock * sk, int *err, long *timeo_p);
93 static int sctp_wait_for_connect(struct sctp_association *, long *timeo_p);
94 static int sctp_wait_for_accept(struct sock *sk, long timeo);
95 static void sctp_wait_for_close(struct sock *sk, long timeo);
96 static struct sctp_af *sctp_sockaddr_af(struct sctp_opt *opt,
97                                         union sctp_addr *addr, int len);
98 static int sctp_bindx_add(struct sock *, struct sockaddr *, int);
99 static int sctp_bindx_rem(struct sock *, struct sockaddr *, int);
100 static int sctp_send_asconf_add_ip(struct sock *, struct sockaddr *, int);
101 static int sctp_send_asconf_del_ip(struct sock *, struct sockaddr *, int);
102 static int sctp_send_asconf(struct sctp_association *asoc,
103                             struct sctp_chunk *chunk);
104 static int sctp_do_bind(struct sock *, union sctp_addr *, int);
105 static int sctp_autobind(struct sock *sk);
106 static void sctp_sock_migrate(struct sock *, struct sock *,
107                               struct sctp_association *, sctp_socket_type_t);
108 static char *sctp_hmac_alg = SCTP_COOKIE_HMAC_ALG;
109
110 extern kmem_cache_t *sctp_bucket_cachep;
111 extern int sctp_assoc_valid(struct sock *sk, struct sctp_association *asoc);
112
113 /* Get the sndbuf space available at the time on the association.  */
114 static inline int sctp_wspace(struct sctp_association *asoc)
115 {
116         struct sock *sk = asoc->base.sk;
117         int amt = 0;
118
119         amt = sk->sk_sndbuf - asoc->sndbuf_used;
120         if (amt < 0)
121                 amt = 0;
122         return amt;
123 }
124
125 /* Increment the used sndbuf space count of the corresponding association by
126  * the size of the outgoing data chunk.
127  * Also, set the skb destructor for sndbuf accounting later.
128  *
129  * Since it is always 1-1 between chunk and skb, and also a new skb is always
130  * allocated for chunk bundling in sctp_packet_transmit(), we can use the
131  * destructor in the data chunk skb for the purpose of the sndbuf space
132  * tracking.
133  */
134 static inline void sctp_set_owner_w(struct sctp_chunk *chunk)
135 {
136         struct sctp_association *asoc = chunk->asoc;
137         struct sock *sk = asoc->base.sk;
138
139         /* The sndbuf space is tracked per association.  */
140         sctp_association_hold(asoc);
141
142         chunk->skb->destructor = sctp_wfree;
143         /* Save the chunk pointer in skb for sctp_wfree to use later.  */
144         *((struct sctp_chunk **)(chunk->skb->cb)) = chunk;
145
146         asoc->sndbuf_used += SCTP_DATA_SNDSIZE(chunk);
147         sk->sk_wmem_queued += SCTP_DATA_SNDSIZE(chunk);
148 }
149
150 /* Verify that this is a valid address. */
151 static inline int sctp_verify_addr(struct sock *sk, union sctp_addr *addr,
152                                    int len)
153 {
154         struct sctp_af *af;
155
156         /* Verify basic sockaddr. */
157         af = sctp_sockaddr_af(sctp_sk(sk), addr, len);
158         if (!af)
159                 return -EINVAL;
160
161         /* Is this a valid SCTP address?  */
162         if (!af->addr_valid(addr, sctp_sk(sk)))
163                 return -EINVAL;
164
165         if (!sctp_sk(sk)->pf->send_verify(sctp_sk(sk), (addr)))
166                 return -EINVAL;
167
168         return 0;
169 }
170
171 /* Look up the association by its id.  If this is not a UDP-style
172  * socket, the ID field is always ignored.
173  */
174 struct sctp_association *sctp_id2assoc(struct sock *sk, sctp_assoc_t id)
175 {
176         struct sctp_association *asoc = NULL;
177
178         /* If this is not a UDP-style socket, assoc id should be ignored. */
179         if (!sctp_style(sk, UDP)) {
180                 /* Return NULL if the socket state is not ESTABLISHED. It
181                  * could be a TCP-style listening socket or a socket which
182                  * hasn't yet called connect() to establish an association.
183                  */
184                 if (!sctp_sstate(sk, ESTABLISHED))
185                         return NULL;
186
187                 /* Get the first and the only association from the list. */
188                 if (!list_empty(&sctp_sk(sk)->ep->asocs))
189                         asoc = list_entry(sctp_sk(sk)->ep->asocs.next,
190                                           struct sctp_association, asocs);
191                 return asoc;
192         }
193
194         /* Otherwise this is a UDP-style socket. */
195         if (!id || (id == (sctp_assoc_t)-1))
196                 return NULL;
197
198         spin_lock_bh(&sctp_assocs_id_lock);
199         asoc = (struct sctp_association *)idr_find(&sctp_assocs_id, (int)id);
200         spin_unlock_bh(&sctp_assocs_id_lock);
201
202         if (!asoc || (asoc->base.sk != sk) || asoc->base.dead)
203                 return NULL;
204
205         return asoc;
206 }
207
208 /* Look up the transport from an address and an assoc id. If both address and
209  * id are specified, the associations matching the address and the id should be
210  * the same.
211  */
212 struct sctp_transport *sctp_addr_id2transport(struct sock *sk,
213                                               struct sockaddr_storage *addr,
214                                               sctp_assoc_t id)
215 {
216         struct sctp_association *addr_asoc = NULL, *id_asoc = NULL;
217         struct sctp_transport *transport;
218         union sctp_addr *laddr = (union sctp_addr *)addr;
219
220         laddr->v4.sin_port = ntohs(laddr->v4.sin_port);
221         addr_asoc = sctp_endpoint_lookup_assoc(sctp_sk(sk)->ep,
222                                                (union sctp_addr *)addr,
223                                                &transport);
224         laddr->v4.sin_port = htons(laddr->v4.sin_port);
225
226         if (!addr_asoc)
227                 return NULL;
228
229         id_asoc = sctp_id2assoc(sk, id);
230         if (id_asoc && (id_asoc != addr_asoc))
231                 return NULL;
232
233         sctp_get_pf_specific(sk->sk_family)->addr_v4map(sctp_sk(sk),
234                                                 (union sctp_addr *)addr);
235
236         return transport;
237 }
238
239 /* API 3.1.2 bind() - UDP Style Syntax
240  * The syntax of bind() is,
241  *
242  *   ret = bind(int sd, struct sockaddr *addr, int addrlen);
243  *
244  *   sd      - the socket descriptor returned by socket().
245  *   addr    - the address structure (struct sockaddr_in or struct
246  *             sockaddr_in6 [RFC 2553]),
247  *   addr_len - the size of the address structure.
248  */
249 int sctp_bind(struct sock *sk, struct sockaddr *uaddr, int addr_len)
250 {
251         int retval = 0;
252
253         sctp_lock_sock(sk);
254
255         SCTP_DEBUG_PRINTK("sctp_bind(sk: %p, uaddr: %p, addr_len: %d)\n",
256                           sk, uaddr, addr_len);
257
258         /* Disallow binding twice. */
259         if (!sctp_sk(sk)->ep->base.bind_addr.port)
260                 retval = sctp_do_bind(sk, (union sctp_addr *)uaddr,
261                                       addr_len);
262         else
263                 retval = -EINVAL;
264
265         sctp_release_sock(sk);
266
267         return retval;
268 }
269
270 static long sctp_get_port_local(struct sock *, union sctp_addr *);
271
272 /* Verify this is a valid sockaddr. */
273 static struct sctp_af *sctp_sockaddr_af(struct sctp_opt *opt,
274                                         union sctp_addr *addr, int len)
275 {
276         struct sctp_af *af;
277
278         /* Check minimum size.  */
279         if (len < sizeof (struct sockaddr))
280                 return NULL;
281
282         /* Does this PF support this AF? */
283         if (!opt->pf->af_supported(addr->sa.sa_family, opt))
284                 return NULL;
285
286         /* If we get this far, af is valid. */
287         af = sctp_get_af_specific(addr->sa.sa_family);
288
289         if (len < af->sockaddr_len)
290                 return NULL;
291
292         return af;
293 }
294
295 /* Bind a local address either to an endpoint or to an association.  */
296 SCTP_STATIC int sctp_do_bind(struct sock *sk, union sctp_addr *addr, int len)
297 {
298         struct sctp_opt *sp = sctp_sk(sk);
299         struct sctp_endpoint *ep = sp->ep;
300         struct sctp_bind_addr *bp = &ep->base.bind_addr;
301         struct sctp_af *af;
302         unsigned short snum;
303         int ret = 0;
304
305         SCTP_DEBUG_PRINTK("sctp_do_bind(sk: %p, newaddr: %p, len: %d)\n",
306                           sk, addr, len);
307
308         /* Common sockaddr verification. */
309         af = sctp_sockaddr_af(sp, addr, len);
310         if (!af)
311                 return -EINVAL;
312
313         /* PF specific bind() address verification. */
314         if (!sp->pf->bind_verify(sp, addr))
315                 return -EADDRNOTAVAIL;
316
317         snum= ntohs(addr->v4.sin_port);
318
319         SCTP_DEBUG_PRINTK("sctp_do_bind: port: %d, new port: %d\n",
320                           bp->port, snum);
321
322         /* We must either be unbound, or bind to the same port.  */
323         if (bp->port && (snum != bp->port)) {
324                 SCTP_DEBUG_PRINTK("sctp_do_bind:"
325                                   " New port %d does not match existing port "
326                                   "%d.\n", snum, bp->port);
327                 return -EINVAL;
328         }
329
330         if (snum && snum < PROT_SOCK && !capable(CAP_NET_BIND_SERVICE))
331                 return -EACCES;
332
333         /* Make sure we are allowed to bind here.
334          * The function sctp_get_port_local() does duplicate address
335          * detection.
336          */
337         if ((ret = sctp_get_port_local(sk, addr))) {
338                 if (ret == (long) sk) {
339                         /* This endpoint has a conflicting address. */
340                         return -EINVAL;
341                 } else {
342                         return -EADDRINUSE;
343                 }
344         }
345
346         /* Refresh ephemeral port.  */
347         if (!snum)
348                 snum = inet_sk(sk)->num;
349
350         /* Add the address to the bind address list.  */
351         sctp_local_bh_disable();
352         sctp_write_lock(&ep->base.addr_lock);
353
354         /* Use GFP_ATOMIC since BHs are disabled.  */
355         addr->v4.sin_port = ntohs(addr->v4.sin_port);
356         ret = sctp_add_bind_addr(bp, addr, GFP_ATOMIC);
357         addr->v4.sin_port = htons(addr->v4.sin_port);
358         if (!ret && !bp->port)
359                 bp->port = snum;
360         sctp_write_unlock(&ep->base.addr_lock);
361         sctp_local_bh_enable();
362
363         /* Copy back into socket for getsockname() use. */
364         if (!ret) {
365                 inet_sk(sk)->sport = htons(inet_sk(sk)->num);
366                 af->to_sk_saddr(addr, sk);
367         }
368
369         return ret;
370 }
371
372  /* ADDIP Section 4.1.1 Congestion Control of ASCONF Chunks
373  *
374  * R1) One and only one ASCONF Chunk MAY be in transit and unacknowledged 
375  * at any one time.  If a sender, after sending an ASCONF chunk, decides
376  * it needs to transfer another ASCONF Chunk, it MUST wait until the 
377  * ASCONF-ACK Chunk returns from the previous ASCONF Chunk before sending a
378  * subsequent ASCONF. Note this restriction binds each side, so at any 
379  * time two ASCONF may be in-transit on any given association (one sent 
380  * from each endpoint).
381  */
382 static int sctp_send_asconf(struct sctp_association *asoc,
383                             struct sctp_chunk *chunk)
384 {
385         int             retval = 0;
386
387         /* If there is an outstanding ASCONF chunk, queue it for later
388          * transmission.
389          */     
390         if (asoc->addip_last_asconf) {
391                 __skb_queue_tail(&asoc->addip_chunks, (struct sk_buff *)chunk);
392                 goto out;       
393         }
394
395         /* Hold the chunk until an ASCONF_ACK is received. */
396         sctp_chunk_hold(chunk);
397         retval = sctp_primitive_ASCONF(asoc, chunk);
398         if (retval)
399                 sctp_chunk_free(chunk);
400         else
401                 asoc->addip_last_asconf = chunk;
402
403 out:
404         return retval;
405 }
406
407 /* Add a list of addresses as bind addresses to local endpoint or
408  * association.
409  *
410  * Basically run through each address specified in the addrs/addrcnt
411  * array/length pair, determine if it is IPv6 or IPv4 and call
412  * sctp_do_bind() on it.
413  *
414  * If any of them fails, then the operation will be reversed and the
415  * ones that were added will be removed.
416  *
417  * Only sctp_setsockopt_bindx() is supposed to call this function.
418  */
419 int sctp_bindx_add(struct sock *sk, struct sockaddr *addrs, int addrcnt)
420 {
421         int cnt;
422         int retval = 0;
423         void *addr_buf;
424         struct sockaddr *sa_addr;
425         struct sctp_af *af;
426
427         SCTP_DEBUG_PRINTK("sctp_bindx_add (sk: %p, addrs: %p, addrcnt: %d)\n",
428                           sk, addrs, addrcnt);
429
430         addr_buf = addrs;
431         for (cnt = 0; cnt < addrcnt; cnt++) {
432                 /* The list may contain either IPv4 or IPv6 address;
433                  * determine the address length for walking thru the list.
434                  */
435                 sa_addr = (struct sockaddr *)addr_buf;
436                 af = sctp_get_af_specific(sa_addr->sa_family);
437                 if (!af) {
438                         retval = -EINVAL;
439                         goto err_bindx_add;
440                 }
441
442                 retval = sctp_do_bind(sk, (union sctp_addr *)sa_addr, 
443                                       af->sockaddr_len);
444
445                 addr_buf += af->sockaddr_len;
446
447 err_bindx_add:
448                 if (retval < 0) {
449                         /* Failed. Cleanup the ones that have been added */
450                         if (cnt > 0)
451                                 sctp_bindx_rem(sk, addrs, cnt);
452                         return retval;
453                 }
454         }
455
456         return retval;
457 }
458
459 /* Send an ASCONF chunk with Add IP address parameters to all the peers of the
460  * associations that are part of the endpoint indicating that a list of local
461  * addresses are added to the endpoint.
462  *
463  * If any of the addresses is already in the bind address list of the 
464  * association, we do not send the chunk for that association.  But it will not
465  * affect other associations.
466  *
467  * Only sctp_setsockopt_bindx() is supposed to call this function.
468  */
469 static int sctp_send_asconf_add_ip(struct sock          *sk, 
470                                    struct sockaddr      *addrs,
471                                    int                  addrcnt)
472 {
473         struct sctp_opt                 *sp;
474         struct sctp_endpoint            *ep;
475         struct sctp_association         *asoc;
476         struct sctp_bind_addr           *bp;
477         struct sctp_chunk               *chunk;
478         struct sctp_sockaddr_entry      *laddr;
479         union sctp_addr                 *addr;
480         void                            *addr_buf;
481         struct sctp_af                  *af;
482         struct list_head                *pos;
483         struct list_head                *p;
484         int                             i;
485         int                             retval = 0;
486
487         if (!sctp_addip_enable)
488                 return retval;
489
490         sp = sctp_sk(sk);
491         ep = sp->ep;
492
493         SCTP_DEBUG_PRINTK("%s: (sk: %p, addrs: %p, addrcnt: %d)\n",
494                           __FUNCTION__, sk, addrs, addrcnt);
495
496         list_for_each(pos, &ep->asocs) {
497                 asoc = list_entry(pos, struct sctp_association, asocs);
498
499                 if (!asoc->peer.asconf_capable)
500                         continue;
501
502                 if (asoc->peer.addip_disabled_mask & SCTP_PARAM_ADD_IP)
503                         continue;
504
505                 if (!sctp_state(asoc, ESTABLISHED))
506                         continue;
507
508                 /* Check if any address in the packed array of addresses is
509                  * in the bind address list of the association. If so, 
510                  * do not send the asconf chunk to its peer, but continue with 
511                  * other associations.
512                  */
513                 addr_buf = addrs;
514                 for (i = 0; i < addrcnt; i++) {
515                         addr = (union sctp_addr *)addr_buf;
516                         af = sctp_get_af_specific(addr->v4.sin_family);
517                         if (!af) {
518                                 retval = -EINVAL;
519                                 goto out;
520                         }
521
522                         if (sctp_assoc_lookup_laddr(asoc, addr))
523                                 break;
524
525                         addr_buf += af->sockaddr_len;
526                 }
527                 if (i < addrcnt)
528                         continue;
529
530                 /* Use the first address in bind addr list of association as
531                  * Address Parameter of ASCONF CHUNK.
532                  */
533                 sctp_read_lock(&asoc->base.addr_lock);
534                 bp = &asoc->base.bind_addr;
535                 p = bp->address_list.next;
536                 laddr = list_entry(p, struct sctp_sockaddr_entry, list);
537                 sctp_read_unlock(&asoc->base.addr_lock);
538
539                 chunk = sctp_make_asconf_update_ip(asoc, &laddr->a, addrs,
540                                                    addrcnt, SCTP_PARAM_ADD_IP);
541                 if (!chunk) {
542                         retval = -ENOMEM;
543                         goto out;
544                 }
545
546                 retval = sctp_send_asconf(asoc, chunk);
547
548                 /* FIXME: After sending the add address ASCONF chunk, we
549                  * cannot append the address to the association's binding
550                  * address list, because the new address may be used as the
551                  * source of a message sent to the peer before the ASCONF
552                  * chunk is received by the peer.  So we should wait until
553                  * ASCONF_ACK is received.
554                  */
555         }
556
557 out:
558         return retval;
559 }
560
561 /* Remove a list of addresses from bind addresses list.  Do not remove the
562  * last address.
563  *
564  * Basically run through each address specified in the addrs/addrcnt
565  * array/length pair, determine if it is IPv6 or IPv4 and call
566  * sctp_del_bind() on it.
567  *
568  * If any of them fails, then the operation will be reversed and the
569  * ones that were removed will be added back.
570  *
571  * At least one address has to be left; if only one address is
572  * available, the operation will return -EBUSY.
573  *
574  * Only sctp_setsockopt_bindx() is supposed to call this function.
575  */
576 int sctp_bindx_rem(struct sock *sk, struct sockaddr *addrs, int addrcnt)
577 {
578         struct sctp_opt *sp = sctp_sk(sk);
579         struct sctp_endpoint *ep = sp->ep;
580         int cnt;
581         struct sctp_bind_addr *bp = &ep->base.bind_addr;
582         int retval = 0;
583         union sctp_addr saveaddr;
584         void *addr_buf;
585         struct sockaddr *sa_addr;
586         struct sctp_af *af;
587
588         SCTP_DEBUG_PRINTK("sctp_bindx_rem (sk: %p, addrs: %p, addrcnt: %d)\n",
589                           sk, addrs, addrcnt);
590
591         addr_buf = addrs;
592         for (cnt = 0; cnt < addrcnt; cnt++) {
593                 /* If the bind address list is empty or if there is only one
594                  * bind address, there is nothing more to be removed (we need
595                  * at least one address here).
596                  */
597                 if (list_empty(&bp->address_list) ||
598                     (sctp_list_single_entry(&bp->address_list))) {
599                         retval = -EBUSY;
600                         goto err_bindx_rem;
601                 }
602
603                 /* The list may contain either IPv4 or IPv6 address;
604                  * determine the address length to copy the address to
605                  * saveaddr. 
606                  */
607                 sa_addr = (struct sockaddr *)addr_buf;
608                 af = sctp_get_af_specific(sa_addr->sa_family);
609                 if (!af) {
610                         retval = -EINVAL;
611                         goto err_bindx_rem;
612                 }
613                 memcpy(&saveaddr, sa_addr, af->sockaddr_len); 
614                 saveaddr.v4.sin_port = ntohs(saveaddr.v4.sin_port);
615                 if (saveaddr.v4.sin_port != bp->port) {
616                         retval = -EINVAL;
617                         goto err_bindx_rem;
618                 }
619
620                 /* FIXME - There is probably a need to check if sk->sk_saddr and
621                  * sk->sk_rcv_addr are currently set to one of the addresses to
622                  * be removed. This is something which needs to be looked into
623                  * when we are fixing the outstanding issues with multi-homing
624                  * socket routing and failover schemes. Refer to comments in
625                  * sctp_do_bind(). -daisy
626                  */
627                 sctp_local_bh_disable();
628                 sctp_write_lock(&ep->base.addr_lock);
629
630                 retval = sctp_del_bind_addr(bp, &saveaddr);
631
632                 sctp_write_unlock(&ep->base.addr_lock);
633                 sctp_local_bh_enable();
634
635                 addr_buf += af->sockaddr_len;
636 err_bindx_rem:
637                 if (retval < 0) {
638                         /* Failed. Add the ones that has been removed back */
639                         if (cnt > 0)
640                                 sctp_bindx_add(sk, addrs, cnt);
641                         return retval;
642                 }
643         }
644
645         return retval;
646 }
647
648 /* Send an ASCONF chunk with Delete IP address parameters to all the peers of
649  * the associations that are part of the endpoint indicating that a list of
650  * local addresses are removed from the endpoint.
651  *
652  * If any of the addresses is already in the bind address list of the 
653  * association, we do not send the chunk for that association.  But it will not
654  * affect other associations.
655  *
656  * Only sctp_setsockopt_bindx() is supposed to call this function.
657  */
658 static int sctp_send_asconf_del_ip(struct sock          *sk,
659                                    struct sockaddr      *addrs,
660                                    int                  addrcnt)
661 {
662         struct sctp_opt         *sp;
663         struct sctp_endpoint    *ep;
664         struct sctp_association *asoc;
665         struct sctp_bind_addr   *bp;
666         struct sctp_chunk       *chunk;
667         union sctp_addr         *laddr;
668         void                    *addr_buf;
669         struct sctp_af          *af;
670         struct list_head        *pos;
671         int                     i;
672         int                     retval = 0;
673
674         if (!sctp_addip_enable)
675                 return retval;
676
677         sp = sctp_sk(sk);
678         ep = sp->ep;
679
680         SCTP_DEBUG_PRINTK("%s: (sk: %p, addrs: %p, addrcnt: %d)\n",
681                           __FUNCTION__, sk, addrs, addrcnt);
682
683         list_for_each(pos, &ep->asocs) {
684                 asoc = list_entry(pos, struct sctp_association, asocs);
685
686                 if (!asoc->peer.asconf_capable)
687                         continue;
688
689                 if (asoc->peer.addip_disabled_mask & SCTP_PARAM_DEL_IP)
690                         continue;
691
692                 if (!sctp_state(asoc, ESTABLISHED))
693                         continue;
694
695                 /* Check if any address in the packed array of addresses is
696                  * not present in the bind address list of the association.
697                  * If so, do not send the asconf chunk to its peer, but
698                  * continue with other associations.
699                  */
700                 addr_buf = addrs;
701                 for (i = 0; i < addrcnt; i++) {
702                         laddr = (union sctp_addr *)addr_buf;
703                         af = sctp_get_af_specific(laddr->v4.sin_family);
704                         if (!af) {
705                                 retval = -EINVAL;
706                                 goto out;
707                         }
708
709                         if (!sctp_assoc_lookup_laddr(asoc, laddr))
710                                 break;
711
712                         addr_buf += af->sockaddr_len;
713                 }
714                 if (i < addrcnt)
715                         continue;
716
717                 /* Find one address in the association's bind address list
718                  * that is not in the packed array of addresses. This is to
719                  * make sure that we do not delete all the addresses in the
720                  * association.
721                  */
722                 sctp_read_lock(&asoc->base.addr_lock);
723                 bp = &asoc->base.bind_addr;
724                 laddr = sctp_find_unmatch_addr(bp, (union sctp_addr *)addrs,
725                                                addrcnt, sp);
726                 sctp_read_unlock(&asoc->base.addr_lock);
727                 if (!laddr)
728                         continue;
729
730                 chunk = sctp_make_asconf_update_ip(asoc, laddr, addrs, addrcnt,
731                                                    SCTP_PARAM_DEL_IP);
732                 if (!chunk) {
733                         retval = -ENOMEM;
734                         goto out;
735                 }
736
737                 retval = sctp_send_asconf(asoc, chunk);
738
739                 /* FIXME: After sending the delete address ASCONF chunk, we
740                  * cannot remove the addresses from the association's bind
741                  * address list, because there maybe some packet send to
742                  * the delete addresses, so we should wait until ASCONF_ACK
743                  * packet is received.
744                  */
745         }
746 out:
747         return retval;
748 }
749
750 /* Helper for tunneling sctp_bindx() requests through sctp_setsockopt()
751  *
752  * API 8.1
753  * int sctp_bindx(int sd, struct sockaddr *addrs, int addrcnt,
754  *                int flags);
755  *
756  * If sd is an IPv4 socket, the addresses passed must be IPv4 addresses.
757  * If the sd is an IPv6 socket, the addresses passed can either be IPv4
758  * or IPv6 addresses.
759  *
760  * A single address may be specified as INADDR_ANY or IN6ADDR_ANY, see
761  * Section 3.1.2 for this usage.
762  *
763  * addrs is a pointer to an array of one or more socket addresses. Each
764  * address is contained in its appropriate structure (i.e. struct
765  * sockaddr_in or struct sockaddr_in6) the family of the address type
766  * must be used to distengish the address length (note that this
767  * representation is termed a "packed array" of addresses). The caller
768  * specifies the number of addresses in the array with addrcnt.
769  *
770  * On success, sctp_bindx() returns 0. On failure, sctp_bindx() returns
771  * -1, and sets errno to the appropriate error code.
772  *
773  * For SCTP, the port given in each socket address must be the same, or
774  * sctp_bindx() will fail, setting errno to EINVAL.
775  *
776  * The flags parameter is formed from the bitwise OR of zero or more of
777  * the following currently defined flags:
778  *
779  * SCTP_BINDX_ADD_ADDR
780  *
781  * SCTP_BINDX_REM_ADDR
782  *
783  * SCTP_BINDX_ADD_ADDR directs SCTP to add the given addresses to the
784  * association, and SCTP_BINDX_REM_ADDR directs SCTP to remove the given
785  * addresses from the association. The two flags are mutually exclusive;
786  * if both are given, sctp_bindx() will fail with EINVAL. A caller may
787  * not remove all addresses from an association; sctp_bindx() will
788  * reject such an attempt with EINVAL.
789  *
790  * An application can use sctp_bindx(SCTP_BINDX_ADD_ADDR) to associate
791  * additional addresses with an endpoint after calling bind().  Or use
792  * sctp_bindx(SCTP_BINDX_REM_ADDR) to remove some addresses a listening
793  * socket is associated with so that no new association accepted will be
794  * associated with those addresses. If the endpoint supports dynamic
795  * address a SCTP_BINDX_REM_ADDR or SCTP_BINDX_ADD_ADDR may cause a
796  * endpoint to send the appropriate message to the peer to change the
797  * peers address lists.
798  *
799  * Adding and removing addresses from a connected association is
800  * optional functionality. Implementations that do not support this
801  * functionality should return EOPNOTSUPP.
802  *
803  * Basically do nothing but copying the addresses from user to kernel
804  * land and invoking either sctp_bindx_add() or sctp_bindx_rem() on the sk.
805  * This is used for tunneling the sctp_bindx() request through sctp_setsockopt() * from userspace.
806  *
807  * We don't use copy_from_user() for optimization: we first do the
808  * sanity checks (buffer size -fast- and access check-healthy
809  * pointer); if all of those succeed, then we can alloc the memory
810  * (expensive operation) needed to copy the data to kernel. Then we do
811  * the copying without checking the user space area
812  * (__copy_from_user()).
813  *
814  * On exit there is no need to do sockfd_put(), sys_setsockopt() does
815  * it.
816  *
817  * sk        The sk of the socket
818  * addrs     The pointer to the addresses in user land
819  * addrssize Size of the addrs buffer
820  * op        Operation to perform (add or remove, see the flags of
821  *           sctp_bindx)
822  *
823  * Returns 0 if ok, <0 errno code on error.
824  */
825 SCTP_STATIC int sctp_setsockopt_bindx(struct sock* sk,
826                                       struct sockaddr __user *addrs,
827                                       int addrs_size, int op)
828 {
829         struct sockaddr *kaddrs;
830         int err;
831         int addrcnt = 0;
832         int walk_size = 0;
833         struct sockaddr *sa_addr;
834         void *addr_buf;
835         struct sctp_af *af;
836
837         SCTP_DEBUG_PRINTK("sctp_setsocktopt_bindx: sk %p addrs %p"
838                           " addrs_size %d opt %d\n", sk, addrs, addrs_size, op);
839
840         if (unlikely(addrs_size <= 0))
841                 return -EINVAL;
842
843         /* Check the user passed a healthy pointer.  */
844         if (unlikely(!access_ok(VERIFY_READ, addrs, addrs_size)))
845                 return -EFAULT;
846
847         /* Alloc space for the address array in kernel memory.  */
848         kaddrs = (struct sockaddr *)kmalloc(addrs_size, GFP_KERNEL);
849         if (unlikely(!kaddrs))
850                 return -ENOMEM;
851
852         if (__copy_from_user(kaddrs, addrs, addrs_size)) {
853                 kfree(kaddrs);
854                 return -EFAULT;
855         }
856
857         /* Walk through the addrs buffer and count the number of addresses. */ 
858         addr_buf = kaddrs;
859         while (walk_size < addrs_size) {
860                 sa_addr = (struct sockaddr *)addr_buf;
861                 af = sctp_get_af_specific(sa_addr->sa_family);
862
863                 /* If the address family is not supported or if this address
864                  * causes the address buffer to overflow return EINVAL.
865                  */ 
866                 if (!af || (walk_size + af->sockaddr_len) > addrs_size) {
867                         kfree(kaddrs);
868                         return -EINVAL;
869                 }
870                 addrcnt++;
871                 addr_buf += af->sockaddr_len;
872                 walk_size += af->sockaddr_len;
873         }
874
875         /* Do the work. */
876         switch (op) {
877         case SCTP_BINDX_ADD_ADDR:
878                 err = sctp_bindx_add(sk, kaddrs, addrcnt);
879                 if (err)
880                         goto out;
881                 err = sctp_send_asconf_add_ip(sk, kaddrs, addrcnt);
882                 break;
883
884         case SCTP_BINDX_REM_ADDR:
885                 err = sctp_bindx_rem(sk, kaddrs, addrcnt);
886                 if (err)
887                         goto out;
888                 err = sctp_send_asconf_del_ip(sk, kaddrs, addrcnt);
889                 break;
890
891         default:
892                 err = -EINVAL;
893                 break;
894         };
895
896 out:
897         kfree(kaddrs);
898
899         return err;
900 }
901
902 /* API 3.1.4 close() - UDP Style Syntax
903  * Applications use close() to perform graceful shutdown (as described in
904  * Section 10.1 of [SCTP]) on ALL the associations currently represented
905  * by a UDP-style socket.
906  *
907  * The syntax is
908  *
909  *   ret = close(int sd);
910  *
911  *   sd      - the socket descriptor of the associations to be closed.
912  *
913  * To gracefully shutdown a specific association represented by the
914  * UDP-style socket, an application should use the sendmsg() call,
915  * passing no user data, but including the appropriate flag in the
916  * ancillary data (see Section xxxx).
917  *
918  * If sd in the close() call is a branched-off socket representing only
919  * one association, the shutdown is performed on that association only.
920  *
921  * 4.1.6 close() - TCP Style Syntax
922  *
923  * Applications use close() to gracefully close down an association.
924  *
925  * The syntax is:
926  *
927  *    int close(int sd);
928  *
929  *      sd      - the socket descriptor of the association to be closed.
930  *
931  * After an application calls close() on a socket descriptor, no further
932  * socket operations will succeed on that descriptor.
933  *
934  * API 7.1.4 SO_LINGER
935  *
936  * An application using the TCP-style socket can use this option to
937  * perform the SCTP ABORT primitive.  The linger option structure is:
938  *
939  *  struct  linger {
940  *     int     l_onoff;                // option on/off
941  *     int     l_linger;               // linger time
942  * };
943  *
944  * To enable the option, set l_onoff to 1.  If the l_linger value is set
945  * to 0, calling close() is the same as the ABORT primitive.  If the
946  * value is set to a negative value, the setsockopt() call will return
947  * an error.  If the value is set to a positive value linger_time, the
948  * close() can be blocked for at most linger_time ms.  If the graceful
949  * shutdown phase does not finish during this period, close() will
950  * return but the graceful shutdown phase continues in the system.
951  */
952 SCTP_STATIC void sctp_close(struct sock *sk, long timeout)
953 {
954         struct sctp_endpoint *ep;
955         struct sctp_association *asoc;
956         struct list_head *pos, *temp;
957
958         SCTP_DEBUG_PRINTK("sctp_close(sk: 0x%p, timeout:%ld)\n", sk, timeout);
959
960         sctp_lock_sock(sk);
961         sk->sk_shutdown = SHUTDOWN_MASK;
962
963         ep = sctp_sk(sk)->ep;
964
965         /* Walk all associations on a socket, not on an endpoint.  */
966         list_for_each_safe(pos, temp, &ep->asocs) {
967                 asoc = list_entry(pos, struct sctp_association, asocs);
968
969                 if (sctp_style(sk, TCP)) {
970                         /* A closed association can still be in the list if
971                          * it belongs to a TCP-style listening socket that is
972                          * not yet accepted. If so, free it. If not, send an
973                          * ABORT or SHUTDOWN based on the linger options.
974                          */
975                         if (sctp_state(asoc, CLOSED)) {
976                                 sctp_unhash_established(asoc);
977                                 sctp_association_free(asoc);
978
979                         } else if (sock_flag(sk, SOCK_LINGER) &&
980                                    !sk->sk_lingertime)
981                                 sctp_primitive_ABORT(asoc, NULL);
982                         else
983                                 sctp_primitive_SHUTDOWN(asoc, NULL);
984                 } else
985                         sctp_primitive_SHUTDOWN(asoc, NULL);
986         }
987
988         /* Clean up any skbs sitting on the receive queue.  */
989         sctp_queue_purge_ulpevents(&sk->sk_receive_queue);
990         sctp_queue_purge_ulpevents(&sctp_sk(sk)->pd_lobby);
991
992         /* On a TCP-style socket, block for at most linger_time if set. */
993         if (sctp_style(sk, TCP) && timeout)
994                 sctp_wait_for_close(sk, timeout);
995
996         /* This will run the backlog queue.  */
997         sctp_release_sock(sk);
998
999         /* Supposedly, no process has access to the socket, but
1000          * the net layers still may.
1001          */
1002         sctp_local_bh_disable();
1003         sctp_bh_lock_sock(sk);
1004
1005         /* Hold the sock, since sk_common_release() will put sock_put()
1006          * and we have just a little more cleanup.
1007          */
1008         sock_hold(sk);
1009         sk_common_release(sk);
1010
1011         sctp_bh_unlock_sock(sk);
1012         sctp_local_bh_enable();
1013
1014         sock_put(sk);
1015
1016         SCTP_DBG_OBJCNT_DEC(sock);
1017 }
1018
1019 /* Handle EPIPE error. */
1020 static int sctp_error(struct sock *sk, int flags, int err)
1021 {
1022         if (err == -EPIPE)
1023                 err = sock_error(sk) ? : -EPIPE;
1024         if (err == -EPIPE && !(flags & MSG_NOSIGNAL))
1025                 send_sig(SIGPIPE, current, 0);
1026         return err;
1027 }
1028
1029 /* API 3.1.3 sendmsg() - UDP Style Syntax
1030  *
1031  * An application uses sendmsg() and recvmsg() calls to transmit data to
1032  * and receive data from its peer.
1033  *
1034  *  ssize_t sendmsg(int socket, const struct msghdr *message,
1035  *                  int flags);
1036  *
1037  *  socket  - the socket descriptor of the endpoint.
1038  *  message - pointer to the msghdr structure which contains a single
1039  *            user message and possibly some ancillary data.
1040  *
1041  *            See Section 5 for complete description of the data
1042  *            structures.
1043  *
1044  *  flags   - flags sent or received with the user message, see Section
1045  *            5 for complete description of the flags.
1046  *
1047  * Note:  This function could use a rewrite especially when explicit
1048  * connect support comes in.
1049  */
1050 /* BUG:  We do not implement the equivalent of sk_stream_wait_memory(). */
1051
1052 SCTP_STATIC int sctp_msghdr_parse(const struct msghdr *, sctp_cmsgs_t *);
1053
1054 SCTP_STATIC int sctp_sendmsg(struct kiocb *iocb, struct sock *sk,
1055                              struct msghdr *msg, size_t msg_len)
1056 {
1057         struct sctp_opt *sp;
1058         struct sctp_endpoint *ep;
1059         struct sctp_association *new_asoc=NULL, *asoc=NULL;
1060         struct sctp_transport *transport, *chunk_tp;
1061         struct sctp_chunk *chunk;
1062         union sctp_addr to;
1063         struct sockaddr *msg_name = NULL;
1064         struct sctp_sndrcvinfo default_sinfo = { 0 };
1065         struct sctp_sndrcvinfo *sinfo;
1066         struct sctp_initmsg *sinit;
1067         sctp_assoc_t associd = NULL;
1068         sctp_cmsgs_t cmsgs = { NULL };
1069         int err;
1070         sctp_scope_t scope;
1071         long timeo;
1072         __u16 sinfo_flags = 0;
1073         struct sctp_datamsg *datamsg;
1074         struct list_head *pos;
1075         int msg_flags = msg->msg_flags;
1076
1077         SCTP_DEBUG_PRINTK("sctp_sendmsg(sk: %p, msg: %p, msg_len: %zu)\n",
1078                           sk, msg, msg_len);
1079
1080         err = 0;
1081         sp = sctp_sk(sk);
1082         ep = sp->ep;
1083
1084         SCTP_DEBUG_PRINTK("Using endpoint: %s.\n", ep->debug_name);
1085
1086         /* We cannot send a message over a TCP-style listening socket. */
1087         if (sctp_style(sk, TCP) && sctp_sstate(sk, LISTENING)) {
1088                 err = -EPIPE;
1089                 goto out_nounlock;
1090         }
1091
1092         /* Parse out the SCTP CMSGs.  */
1093         err = sctp_msghdr_parse(msg, &cmsgs);
1094
1095         if (err) {
1096                 SCTP_DEBUG_PRINTK("msghdr parse err = %x\n", err);
1097                 goto out_nounlock;
1098         }
1099
1100         /* Fetch the destination address for this packet.  This
1101          * address only selects the association--it is not necessarily
1102          * the address we will send to.
1103          * For a peeled-off socket, msg_name is ignored.
1104          */
1105         if (!sctp_style(sk, UDP_HIGH_BANDWIDTH) && msg->msg_name) {
1106                 int msg_namelen = msg->msg_namelen;
1107
1108                 err = sctp_verify_addr(sk, (union sctp_addr *)msg->msg_name,
1109                                        msg_namelen);
1110                 if (err)
1111                         return err;
1112
1113                 if (msg_namelen > sizeof(to))
1114                         msg_namelen = sizeof(to);
1115                 memcpy(&to, msg->msg_name, msg_namelen);
1116                 SCTP_DEBUG_PRINTK("Just memcpy'd. msg_name is "
1117                                   "0x%x:%u.\n",
1118                                   to.v4.sin_addr.s_addr, to.v4.sin_port);
1119
1120                 to.v4.sin_port = ntohs(to.v4.sin_port);
1121                 msg_name = msg->msg_name;
1122         }
1123
1124         sinfo = cmsgs.info;
1125         sinit = cmsgs.init;
1126
1127         /* Did the user specify SNDRCVINFO?  */
1128         if (sinfo) {
1129                 sinfo_flags = sinfo->sinfo_flags;
1130                 associd = sinfo->sinfo_assoc_id;
1131         }
1132
1133         SCTP_DEBUG_PRINTK("msg_len: %zu, sinfo_flags: 0x%x\n",
1134                           msg_len, sinfo_flags);
1135
1136         /* MSG_EOF or MSG_ABORT cannot be set on a TCP-style socket. */
1137         if (sctp_style(sk, TCP) && (sinfo_flags & (MSG_EOF | MSG_ABORT))) {
1138                 err = -EINVAL;
1139                 goto out_nounlock;
1140         }
1141
1142         /* If MSG_EOF is set, no data can be sent. Disallow sending zero
1143          * length messages when MSG_EOF|MSG_ABORT is not set.
1144          * If MSG_ABORT is set, the message length could be non zero with
1145          * the msg_iov set to the user abort reason.
1146          */
1147         if (((sinfo_flags & MSG_EOF) && (msg_len > 0)) ||
1148             (!(sinfo_flags & (MSG_EOF|MSG_ABORT)) && (msg_len == 0))) {
1149                 err = -EINVAL;
1150                 goto out_nounlock;
1151         }
1152
1153         /* If MSG_ADDR_OVER is set, there must be an address
1154          * specified in msg_name.
1155          */
1156         if ((sinfo_flags & MSG_ADDR_OVER) && (!msg->msg_name)) {
1157                 err = -EINVAL;
1158                 goto out_nounlock;
1159         }
1160
1161         transport = NULL;
1162
1163         SCTP_DEBUG_PRINTK("About to look up association.\n");
1164
1165         sctp_lock_sock(sk);
1166
1167         /* If a msg_name has been specified, assume this is to be used.  */
1168         if (msg_name) {
1169                 /* Look for a matching association on the endpoint. */
1170                 asoc = sctp_endpoint_lookup_assoc(ep, &to, &transport);
1171                 if (!asoc) {
1172                         /* If we could not find a matching association on the
1173                          * endpoint, make sure that it is not a TCP-style
1174                          * socket that already has an association or there is
1175                          * no peeled-off association on another socket.
1176                          */
1177                         if ((sctp_style(sk, TCP) &&
1178                              sctp_sstate(sk, ESTABLISHED)) ||
1179                             sctp_endpoint_is_peeled_off(ep, &to)) {
1180                                 err = -EADDRNOTAVAIL;
1181                                 goto out_unlock;
1182                         }
1183                 }
1184         } else {
1185                 asoc = sctp_id2assoc(sk, associd);
1186                 if (!asoc) {
1187                         err = -EPIPE;
1188                         goto out_unlock;
1189                 }
1190         }
1191
1192         if (asoc) {
1193                 SCTP_DEBUG_PRINTK("Just looked up association: %p.\n", asoc);
1194
1195                 /* We cannot send a message on a TCP-style SCTP_SS_ESTABLISHED
1196                  * socket that has an association in CLOSED state. This can
1197                  * happen when an accepted socket has an association that is
1198                  * already CLOSED.
1199                  */
1200                 if (sctp_state(asoc, CLOSED) && sctp_style(sk, TCP)) {
1201                         err = -EPIPE;
1202                         goto out_unlock;
1203                 }
1204
1205                 if (sinfo_flags & MSG_EOF) {
1206                         SCTP_DEBUG_PRINTK("Shutting down association: %p\n",
1207                                           asoc);
1208                         sctp_primitive_SHUTDOWN(asoc, NULL);
1209                         err = 0;
1210                         goto out_unlock;
1211                 }
1212                 if (sinfo_flags & MSG_ABORT) {
1213                         SCTP_DEBUG_PRINTK("Aborting association: %p\n", asoc);
1214                         sctp_primitive_ABORT(asoc, msg);
1215                         err = 0;
1216                         goto out_unlock;
1217                 }
1218         }
1219
1220         /* Do we need to create the association?  */
1221         if (!asoc) {
1222                 SCTP_DEBUG_PRINTK("There is no association yet.\n");
1223
1224                 if (sinfo_flags & (MSG_EOF | MSG_ABORT)) {
1225                         err = -EINVAL;
1226                         goto out_unlock;
1227                 }
1228
1229                 /* Check for invalid stream against the stream counts,
1230                  * either the default or the user specified stream counts.
1231                  */
1232                 if (sinfo) {
1233                         if (!sinit || (sinit && !sinit->sinit_num_ostreams)) {
1234                                 /* Check against the defaults. */
1235                                 if (sinfo->sinfo_stream >=
1236                                     sp->initmsg.sinit_num_ostreams) {
1237                                         err = -EINVAL;
1238                                         goto out_unlock;
1239                                 }
1240                         } else {
1241                                 /* Check against the requested.  */
1242                                 if (sinfo->sinfo_stream >=
1243                                     sinit->sinit_num_ostreams) {
1244                                         err = -EINVAL;
1245                                         goto out_unlock;
1246                                 }
1247                         }
1248                 }
1249
1250                 /*
1251                  * API 3.1.2 bind() - UDP Style Syntax
1252                  * If a bind() or sctp_bindx() is not called prior to a
1253                  * sendmsg() call that initiates a new association, the
1254                  * system picks an ephemeral port and will choose an address
1255                  * set equivalent to binding with a wildcard address.
1256                  */
1257                 if (!ep->base.bind_addr.port) {
1258                         if (sctp_autobind(sk)) {
1259                                 err = -EAGAIN;
1260                                 goto out_unlock;
1261                         }
1262                 }
1263
1264                 scope = sctp_scope(&to);
1265                 new_asoc = sctp_association_new(ep, sk, scope, GFP_KERNEL);
1266                 if (!new_asoc) {
1267                         err = -ENOMEM;
1268                         goto out_unlock;
1269                 }
1270                 asoc = new_asoc;
1271
1272                 /* If the SCTP_INIT ancillary data is specified, set all
1273                  * the association init values accordingly.
1274                  */
1275                 if (sinit) {
1276                         if (sinit->sinit_num_ostreams) {
1277                                 asoc->c.sinit_num_ostreams =
1278                                         sinit->sinit_num_ostreams;
1279                         }
1280                         if (sinit->sinit_max_instreams) {
1281                                 asoc->c.sinit_max_instreams =
1282                                         sinit->sinit_max_instreams;
1283                         }
1284                         if (sinit->sinit_max_attempts) {
1285                                 asoc->max_init_attempts
1286                                         = sinit->sinit_max_attempts;
1287                         }
1288                         if (sinit->sinit_max_init_timeo) {
1289                                 asoc->max_init_timeo = 
1290                                  msecs_to_jiffies(sinit->sinit_max_init_timeo);
1291                         }
1292                 }
1293
1294                 /* Prime the peer's transport structures.  */
1295                 transport = sctp_assoc_add_peer(asoc, &to, GFP_KERNEL);
1296                 if (!transport) {
1297                         err = -ENOMEM;
1298                         goto out_free;
1299                 }
1300                 err = sctp_assoc_set_bind_addr_from_ep(asoc, GFP_KERNEL);
1301                 if (err < 0) {
1302                         err = -ENOMEM;
1303                         goto out_free;
1304                 }
1305         }
1306
1307         /* ASSERT: we have a valid association at this point.  */
1308         SCTP_DEBUG_PRINTK("We have a valid association.\n");
1309
1310         if (!sinfo) {
1311                 /* If the user didn't specify SNDRCVINFO, make up one with
1312                  * some defaults.
1313                  */
1314                 default_sinfo.sinfo_stream = asoc->default_stream;
1315                 default_sinfo.sinfo_flags = asoc->default_flags;
1316                 default_sinfo.sinfo_ppid = asoc->default_ppid;
1317                 default_sinfo.sinfo_context = asoc->default_context;
1318                 default_sinfo.sinfo_timetolive = asoc->default_timetolive;
1319                 default_sinfo.sinfo_assoc_id = sctp_assoc2id(asoc);
1320                 sinfo = &default_sinfo;
1321         }
1322
1323         /* API 7.1.7, the sndbuf size per association bounds the
1324          * maximum size of data that can be sent in a single send call.
1325          */
1326         if (msg_len > sk->sk_sndbuf) {
1327                 err = -EMSGSIZE;
1328                 goto out_free;
1329         }
1330
1331         /* If fragmentation is disabled and the message length exceeds the
1332          * association fragmentation point, return EMSGSIZE.  The I-D
1333          * does not specify what this error is, but this looks like
1334          * a great fit.
1335          */
1336         if (sctp_sk(sk)->disable_fragments && (msg_len > asoc->frag_point)) {
1337                 err = -EMSGSIZE;
1338                 goto out_free;
1339         }
1340
1341         if (sinfo) {
1342                 /* Check for invalid stream. */
1343                 if (sinfo->sinfo_stream >= asoc->c.sinit_num_ostreams) {
1344                         err = -EINVAL;
1345                         goto out_free;
1346                 }
1347         }
1348
1349         timeo = sock_sndtimeo(sk, msg->msg_flags & MSG_DONTWAIT);
1350         if (!sctp_wspace(asoc)) {
1351                 err = sctp_wait_for_sndbuf(asoc, &timeo, msg_len);
1352                 if (err)
1353                         goto out_free;
1354         }
1355
1356         /* If an address is passed with the sendto/sendmsg call, it is used
1357          * to override the primary destination address in the TCP model, or
1358          * when MSG_ADDR_OVER flag is set in the UDP model.
1359          */
1360         if ((sctp_style(sk, TCP) && msg_name) ||
1361             (sinfo_flags & MSG_ADDR_OVER)) {
1362                 chunk_tp = sctp_assoc_lookup_paddr(asoc, &to);
1363                 if (!chunk_tp) {
1364                         err = -EINVAL;
1365                         goto out_free;
1366                 }
1367         } else
1368                 chunk_tp = NULL;
1369
1370         /* Auto-connect, if we aren't connected already. */
1371         if (sctp_state(asoc, CLOSED)) {
1372                 err = sctp_primitive_ASSOCIATE(asoc, NULL);
1373                 if (err < 0)
1374                         goto out_free;
1375                 SCTP_DEBUG_PRINTK("We associated primitively.\n");
1376         }
1377
1378         /* Break the message into multiple chunks of maximum size. */
1379         datamsg = sctp_datamsg_from_user(asoc, sinfo, msg, msg_len);
1380         if (!datamsg) {
1381                 err = -ENOMEM;
1382                 goto out_free;
1383         }
1384
1385         /* Now send the (possibly) fragmented message. */
1386         list_for_each(pos, &datamsg->chunks) {
1387                 chunk = list_entry(pos, struct sctp_chunk, frag_list);
1388                 sctp_datamsg_track(chunk);
1389
1390                 /* Do accounting for the write space.  */
1391                 sctp_set_owner_w(chunk);
1392
1393                 chunk->transport = chunk_tp;
1394
1395                 /* Send it to the lower layers.  Note:  all chunks
1396                  * must either fail or succeed.   The lower layer
1397                  * works that way today.  Keep it that way or this
1398                  * breaks.
1399                  */
1400                 err = sctp_primitive_SEND(asoc, chunk);
1401                 /* Did the lower layer accept the chunk? */
1402                 if (err)
1403                         sctp_chunk_free(chunk);
1404                 SCTP_DEBUG_PRINTK("We sent primitively.\n");
1405         }
1406
1407         sctp_datamsg_free(datamsg);
1408         if (err)
1409                 goto out_free;
1410         else
1411                 err = msg_len;
1412
1413         /* If we are already past ASSOCIATE, the lower
1414          * layers are responsible for association cleanup.
1415          */
1416         goto out_unlock;
1417
1418 out_free:
1419         if (new_asoc)
1420                 sctp_association_free(asoc);
1421 out_unlock:
1422         sctp_release_sock(sk);
1423
1424 out_nounlock:
1425         return sctp_error(sk, msg_flags, err);
1426
1427 #if 0
1428 do_sock_err:
1429         if (msg_len)
1430                 err = msg_len;
1431         else
1432                 err = sock_error(sk);
1433         goto out;
1434
1435 do_interrupted:
1436         if (msg_len)
1437                 err = msg_len;
1438         goto out;
1439 #endif /* 0 */
1440 }
1441
1442 /* This is an extended version of skb_pull() that removes the data from the
1443  * start of a skb even when data is spread across the list of skb's in the
1444  * frag_list. len specifies the total amount of data that needs to be removed.
1445  * when 'len' bytes could be removed from the skb, it returns 0.
1446  * If 'len' exceeds the total skb length,  it returns the no. of bytes that
1447  * could not be removed.
1448  */
1449 static int sctp_skb_pull(struct sk_buff *skb, int len)
1450 {
1451         struct sk_buff *list;
1452         int skb_len = skb_headlen(skb);
1453         int rlen;
1454
1455         if (len <= skb_len) {
1456                 __skb_pull(skb, len);
1457                 return 0;
1458         }
1459         len -= skb_len;
1460         __skb_pull(skb, skb_len);
1461
1462         for (list = skb_shinfo(skb)->frag_list; list; list = list->next) {
1463                 rlen = sctp_skb_pull(list, len);
1464                 skb->len -= (len-rlen);
1465                 skb->data_len -= (len-rlen);
1466
1467                 if (!rlen)
1468                         return 0;
1469
1470                 len = rlen;
1471         }
1472
1473         return len;
1474 }
1475
1476 /* API 3.1.3  recvmsg() - UDP Style Syntax
1477  *
1478  *  ssize_t recvmsg(int socket, struct msghdr *message,
1479  *                    int flags);
1480  *
1481  *  socket  - the socket descriptor of the endpoint.
1482  *  message - pointer to the msghdr structure which contains a single
1483  *            user message and possibly some ancillary data.
1484  *
1485  *            See Section 5 for complete description of the data
1486  *            structures.
1487  *
1488  *  flags   - flags sent or received with the user message, see Section
1489  *            5 for complete description of the flags.
1490  */
1491 static struct sk_buff *sctp_skb_recv_datagram(struct sock *, int, int, int *);
1492
1493 SCTP_STATIC int sctp_recvmsg(struct kiocb *iocb, struct sock *sk,
1494                              struct msghdr *msg, size_t len, int noblock,
1495                              int flags, int *addr_len)
1496 {
1497         struct sctp_ulpevent *event = NULL;
1498         struct sctp_opt *sp = sctp_sk(sk);
1499         struct sk_buff *skb;
1500         int copied;
1501         int err = 0;
1502         int skb_len;
1503
1504         SCTP_DEBUG_PRINTK("sctp_recvmsg(%s: %p, %s: %p, %s: %zd, %s: %d, %s: "
1505                           "0x%x, %s: %p)\n", "sk", sk, "msghdr", msg,
1506                           "len", len, "knoblauch", noblock,
1507                           "flags", flags, "addr_len", addr_len);
1508
1509         sctp_lock_sock(sk);
1510
1511         if (sctp_style(sk, TCP) && !sctp_sstate(sk, ESTABLISHED)) {
1512                 err = -ENOTCONN;
1513                 goto out;
1514         }
1515
1516         skb = sctp_skb_recv_datagram(sk, flags, noblock, &err);
1517         if (!skb)
1518                 goto out;
1519
1520         /* Get the total length of the skb including any skb's in the
1521          * frag_list.
1522          */
1523         skb_len = skb->len;
1524
1525         copied = skb_len;
1526         if (copied > len)
1527                 copied = len;
1528
1529         err = skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied);
1530
1531         event = sctp_skb2event(skb);
1532
1533         if (err)
1534                 goto out_free;
1535
1536         sock_recv_timestamp(msg, sk, skb);
1537         if (sctp_ulpevent_is_notification(event)) {
1538                 msg->msg_flags |= MSG_NOTIFICATION;
1539                 sp->pf->event_msgname(event, msg->msg_name, addr_len);
1540         } else {
1541                 sp->pf->skb_msgname(skb, msg->msg_name, addr_len);
1542         }
1543
1544         /* Check if we allow SCTP_SNDRCVINFO. */
1545         if (sp->subscribe.sctp_data_io_event)
1546                 sctp_ulpevent_read_sndrcvinfo(event, msg);
1547 #if 0
1548         /* FIXME: we should be calling IP/IPv6 layers.  */
1549         if (sk->sk_protinfo.af_inet.cmsg_flags)
1550                 ip_cmsg_recv(msg, skb);
1551 #endif
1552
1553         err = copied;
1554
1555         /* If skb's length exceeds the user's buffer, update the skb and
1556          * push it back to the receive_queue so that the next call to
1557          * recvmsg() will return the remaining data. Don't set MSG_EOR.
1558          */
1559         if (skb_len > copied) {
1560                 msg->msg_flags &= ~MSG_EOR;
1561                 if (flags & MSG_PEEK)
1562                         goto out_free;
1563                 sctp_skb_pull(skb, copied);
1564                 skb_queue_head(&sk->sk_receive_queue, skb);
1565
1566                 /* When only partial message is copied to the user, increase
1567                  * rwnd by that amount. If all the data in the skb is read,
1568                  * rwnd is updated when the event is freed.
1569                  */
1570                 sctp_assoc_rwnd_increase(event->asoc, copied);
1571                 goto out;
1572         } else if ((event->msg_flags & MSG_NOTIFICATION) ||
1573                    (event->msg_flags & MSG_EOR))
1574                 msg->msg_flags |= MSG_EOR;
1575         else
1576                 msg->msg_flags &= ~MSG_EOR;
1577
1578 out_free:
1579         if (flags & MSG_PEEK) {
1580                 /* Release the skb reference acquired after peeking the skb in
1581                  * sctp_skb_recv_datagram().
1582                  */
1583                 kfree_skb(skb);
1584         } else {
1585                 /* Free the event which includes releasing the reference to
1586                  * the owner of the skb, freeing the skb and updating the
1587                  * rwnd.
1588                  */
1589                 sctp_ulpevent_free(event);
1590         }
1591 out:
1592         sctp_release_sock(sk);
1593         return err;
1594 }
1595
1596 /* 7.1.12 Enable/Disable message fragmentation (SCTP_DISABLE_FRAGMENTS)
1597  *
1598  * This option is a on/off flag.  If enabled no SCTP message
1599  * fragmentation will be performed.  Instead if a message being sent
1600  * exceeds the current PMTU size, the message will NOT be sent and
1601  * instead a error will be indicated to the user.
1602  */
1603 static int sctp_setsockopt_disable_fragments(struct sock *sk,
1604                                             char __user *optval, int optlen)
1605 {
1606         int val;
1607
1608         if (optlen < sizeof(int))
1609                 return -EINVAL;
1610
1611         if (get_user(val, (int __user *)optval))
1612                 return -EFAULT;
1613
1614         sctp_sk(sk)->disable_fragments = (val == 0) ? 0 : 1;
1615
1616         return 0;
1617 }
1618
1619 static int sctp_setsockopt_events(struct sock *sk, char __user *optval,
1620                                         int optlen)
1621 {
1622         if (optlen != sizeof(struct sctp_event_subscribe))
1623                 return -EINVAL;
1624         if (copy_from_user(&sctp_sk(sk)->subscribe, optval, optlen))
1625                 return -EFAULT;
1626         return 0;
1627 }
1628
1629 /* 7.1.8 Automatic Close of associations (SCTP_AUTOCLOSE)
1630  *
1631  * This socket option is applicable to the UDP-style socket only.  When
1632  * set it will cause associations that are idle for more than the
1633  * specified number of seconds to automatically close.  An association
1634  * being idle is defined an association that has NOT sent or received
1635  * user data.  The special value of '0' indicates that no automatic
1636  * close of any associations should be performed.  The option expects an
1637  * integer defining the number of seconds of idle time before an
1638  * association is closed.
1639  */
1640 static int sctp_setsockopt_autoclose(struct sock *sk, char __user *optval,
1641                                             int optlen)
1642 {
1643         struct sctp_opt *sp = sctp_sk(sk);
1644
1645         /* Applicable to UDP-style socket only */
1646         if (sctp_style(sk, TCP))
1647                 return -EOPNOTSUPP;
1648         if (optlen != sizeof(int))
1649                 return -EINVAL;
1650         if (copy_from_user(&sp->autoclose, optval, optlen))
1651                 return -EFAULT;
1652
1653         sp->ep->timeouts[SCTP_EVENT_TIMEOUT_AUTOCLOSE] = sp->autoclose * HZ;
1654         return 0;
1655 }
1656
1657 /* 7.1.13 Peer Address Parameters (SCTP_PEER_ADDR_PARAMS)
1658  *
1659  * Applications can enable or disable heartbeats for any peer address of
1660  * an association, modify an address's heartbeat interval, force a
1661  * heartbeat to be sent immediately, and adjust the address's maximum
1662  * number of retransmissions sent before an address is considered
1663  * unreachable.  The following structure is used to access and modify an
1664  * address's parameters:
1665  *
1666  *  struct sctp_paddrparams {
1667  *      sctp_assoc_t            spp_assoc_id;
1668  *      struct sockaddr_storage spp_address;
1669  *      uint32_t                spp_hbinterval;
1670  *      uint16_t                spp_pathmaxrxt;
1671  *  };
1672  *
1673  *   spp_assoc_id    - (UDP style socket) This is filled in the application,
1674  *                     and identifies the association for this query.
1675  *   spp_address     - This specifies which address is of interest.
1676  *   spp_hbinterval  - This contains the value of the heartbeat interval,
1677  *                     in milliseconds.  A value of 0, when modifying the
1678  *                     parameter, specifies that the heartbeat on this
1679  *                     address should be disabled. A value of UINT32_MAX
1680  *                     (4294967295), when modifying the parameter,
1681  *                     specifies that a heartbeat should be sent
1682  *                     immediately to the peer address, and the current
1683  *                     interval should remain unchanged.
1684  *   spp_pathmaxrxt  - This contains the maximum number of
1685  *                     retransmissions before this address shall be
1686  *                     considered unreachable.
1687  */
1688 static int sctp_setsockopt_peer_addr_params(struct sock *sk,
1689                                             char __user *optval, int optlen)
1690 {
1691         struct sctp_paddrparams params;
1692         struct sctp_transport *trans;
1693         int error;
1694
1695         if (optlen != sizeof(struct sctp_paddrparams))
1696                 return -EINVAL;
1697         if (copy_from_user(&params, optval, optlen))
1698                 return -EFAULT;
1699
1700         trans = sctp_addr_id2transport(sk, &params.spp_address,
1701                                        params.spp_assoc_id);
1702         if (!trans)
1703                 return -EINVAL;
1704
1705         /* Applications can enable or disable heartbeats for any peer address
1706          * of an association, modify an address's heartbeat interval, force a
1707          * heartbeat to be sent immediately, and adjust the address's maximum
1708          * number of retransmissions sent before an address is considered
1709          * unreachable.
1710          *
1711          * The value of the heartbeat interval, in milliseconds. A value of
1712          * UINT32_MAX (4294967295), when modifying the parameter, specifies
1713          * that a heartbeat should be sent immediately to the peer address,
1714          * and the current interval should remain unchanged.
1715          */
1716         if (0xffffffff == params.spp_hbinterval) {
1717                 error = sctp_primitive_REQUESTHEARTBEAT (trans->asoc, trans);
1718                 if (error)
1719                         return error;
1720         } else {
1721         /* The value of the heartbeat interval, in milliseconds. A value of 0,
1722          * when modifying the parameter, specifies that the heartbeat on this
1723          * address should be disabled.
1724          */
1725                 if (params.spp_hbinterval) {
1726                         trans->hb_allowed = 1;
1727                         trans->hb_interval = 
1728                                 msecs_to_jiffies(params.spp_hbinterval);
1729                 } else
1730                         trans->hb_allowed = 0;
1731         }
1732
1733         /* spp_pathmaxrxt contains the maximum number of retransmissions
1734          * before this address shall be considered unreachable.
1735          */
1736         trans->error_threshold = params.spp_pathmaxrxt;
1737
1738         return 0;
1739 }
1740
1741 /* 7.1.3 Initialization Parameters (SCTP_INITMSG)
1742  *
1743  * Applications can specify protocol parameters for the default association
1744  * initialization.  The option name argument to setsockopt() and getsockopt()
1745  * is SCTP_INITMSG.
1746  *
1747  * Setting initialization parameters is effective only on an unconnected
1748  * socket (for UDP-style sockets only future associations are effected
1749  * by the change).  With TCP-style sockets, this option is inherited by
1750  * sockets derived from a listener socket.
1751  */
1752 static int sctp_setsockopt_initmsg(struct sock *sk, char __user *optval, int optlen)
1753 {
1754         struct sctp_initmsg sinit;
1755         struct sctp_opt *sp = sctp_sk(sk);
1756
1757         if (optlen != sizeof(struct sctp_initmsg))
1758                 return -EINVAL;
1759         if (copy_from_user(&sinit, optval, optlen))
1760                 return -EFAULT;
1761
1762         if (sinit.sinit_num_ostreams)
1763                 sp->initmsg.sinit_num_ostreams = sinit.sinit_num_ostreams;      
1764         if (sinit.sinit_max_instreams)
1765                 sp->initmsg.sinit_max_instreams = sinit.sinit_max_instreams;    
1766         if (sinit.sinit_max_attempts)
1767                 sp->initmsg.sinit_max_attempts = sinit.sinit_max_attempts;      
1768         if (sinit.sinit_max_init_timeo)
1769                 sp->initmsg.sinit_max_init_timeo = sinit.sinit_max_init_timeo;  
1770
1771         return 0;
1772 }
1773
1774 /*
1775  * 7.1.14 Set default send parameters (SCTP_DEFAULT_SEND_PARAM)
1776  *
1777  *   Applications that wish to use the sendto() system call may wish to
1778  *   specify a default set of parameters that would normally be supplied
1779  *   through the inclusion of ancillary data.  This socket option allows
1780  *   such an application to set the default sctp_sndrcvinfo structure.
1781  *   The application that wishes to use this socket option simply passes
1782  *   in to this call the sctp_sndrcvinfo structure defined in Section
1783  *   5.2.2) The input parameters accepted by this call include
1784  *   sinfo_stream, sinfo_flags, sinfo_ppid, sinfo_context,
1785  *   sinfo_timetolive.  The user must provide the sinfo_assoc_id field in
1786  *   to this call if the caller is using the UDP model.
1787  */
1788 static int sctp_setsockopt_default_send_param(struct sock *sk,
1789                                                 char __user *optval, int optlen)
1790 {
1791         struct sctp_sndrcvinfo info;
1792         struct sctp_association *asoc;
1793         struct sctp_opt *sp = sctp_sk(sk);
1794
1795         if (optlen != sizeof(struct sctp_sndrcvinfo))
1796                 return -EINVAL;
1797         if (copy_from_user(&info, optval, optlen))
1798                 return -EFAULT;
1799
1800         asoc = sctp_id2assoc(sk, info.sinfo_assoc_id);
1801         if (!asoc && info.sinfo_assoc_id && sctp_style(sk, UDP))
1802                 return -EINVAL;
1803
1804         if (asoc) {
1805                 asoc->default_stream = info.sinfo_stream;
1806                 asoc->default_flags = info.sinfo_flags;
1807                 asoc->default_ppid = info.sinfo_ppid;
1808                 asoc->default_context = info.sinfo_context;
1809                 asoc->default_timetolive = info.sinfo_timetolive;
1810         } else {
1811                 sp->default_stream = info.sinfo_stream;
1812                 sp->default_flags = info.sinfo_flags;
1813                 sp->default_ppid = info.sinfo_ppid;
1814                 sp->default_context = info.sinfo_context;
1815                 sp->default_timetolive = info.sinfo_timetolive;
1816         }
1817
1818         return 0;
1819 }
1820
1821 /* 7.1.10 Set Primary Address (SCTP_PRIMARY_ADDR)
1822  *
1823  * Requests that the local SCTP stack use the enclosed peer address as
1824  * the association primary.  The enclosed address must be one of the
1825  * association peer's addresses.
1826  */
1827 static int sctp_setsockopt_primary_addr(struct sock *sk, char __user *optval,
1828                                         int optlen)
1829 {
1830         struct sctp_prim prim;
1831         struct sctp_transport *trans;
1832
1833         if (optlen != sizeof(struct sctp_prim))
1834                 return -EINVAL;
1835
1836         if (copy_from_user(&prim, optval, sizeof(struct sctp_prim)))
1837                 return -EFAULT;
1838
1839         trans = sctp_addr_id2transport(sk, &prim.ssp_addr, prim.ssp_assoc_id);
1840         if (!trans)
1841                 return -EINVAL;
1842
1843         sctp_assoc_set_primary(trans->asoc, trans);
1844
1845         return 0;
1846 }
1847
1848 /*
1849  * 7.1.5 SCTP_NODELAY
1850  *
1851  * Turn on/off any Nagle-like algorithm.  This means that packets are
1852  * generally sent as soon as possible and no unnecessary delays are
1853  * introduced, at the cost of more packets in the network.  Expects an
1854  *  integer boolean flag.
1855  */
1856 static int sctp_setsockopt_nodelay(struct sock *sk, char __user *optval,
1857                                         int optlen)
1858 {
1859         int val;
1860
1861         if (optlen < sizeof(int))
1862                 return -EINVAL;
1863         if (get_user(val, (int __user *)optval))
1864                 return -EFAULT;
1865
1866         sctp_sk(sk)->nodelay = (val == 0) ? 0 : 1;
1867         return 0;
1868 }
1869
1870 /*
1871  *
1872  * 7.1.1 SCTP_RTOINFO
1873  *
1874  * The protocol parameters used to initialize and bound retransmission
1875  * timeout (RTO) are tunable. sctp_rtoinfo structure is used to access
1876  * and modify these parameters.
1877  * All parameters are time values, in milliseconds.  A value of 0, when
1878  * modifying the parameters, indicates that the current value should not
1879  * be changed.
1880  *
1881  */
1882 static int sctp_setsockopt_rtoinfo(struct sock *sk, char __user *optval, int optlen) {
1883         struct sctp_rtoinfo rtoinfo;
1884         struct sctp_association *asoc;
1885
1886         if (optlen != sizeof (struct sctp_rtoinfo))
1887                 return -EINVAL;
1888
1889         if (copy_from_user(&rtoinfo, optval, optlen))
1890                 return -EFAULT;
1891
1892         asoc = sctp_id2assoc(sk, rtoinfo.srto_assoc_id);
1893
1894         /* Set the values to the specific association */
1895         if (!asoc && rtoinfo.srto_assoc_id && sctp_style(sk, UDP))
1896                 return -EINVAL;
1897
1898         if (asoc) {
1899                 if (rtoinfo.srto_initial != 0)
1900                         asoc->rto_initial = 
1901                                 msecs_to_jiffies(rtoinfo.srto_initial);
1902                 if (rtoinfo.srto_max != 0)
1903                         asoc->rto_max = msecs_to_jiffies(rtoinfo.srto_max);
1904                 if (rtoinfo.srto_min != 0)
1905                         asoc->rto_min = msecs_to_jiffies(rtoinfo.srto_min);
1906         } else {
1907                 /* If there is no association or the association-id = 0
1908                  * set the values to the endpoint.
1909                  */
1910                 struct sctp_opt *sp = sctp_sk(sk);
1911
1912                 if (rtoinfo.srto_initial != 0)
1913                         sp->rtoinfo.srto_initial = rtoinfo.srto_initial;
1914                 if (rtoinfo.srto_max != 0)
1915                         sp->rtoinfo.srto_max = rtoinfo.srto_max;
1916                 if (rtoinfo.srto_min != 0)
1917                         sp->rtoinfo.srto_min = rtoinfo.srto_min;
1918         }
1919
1920         return 0;
1921 }
1922
1923 /*
1924  *
1925  * 7.1.2 SCTP_ASSOCINFO
1926  *
1927  * This option is used to tune the the maximum retransmission attempts
1928  * of the association.
1929  * Returns an error if the new association retransmission value is
1930  * greater than the sum of the retransmission value  of the peer.
1931  * See [SCTP] for more information.
1932  *
1933  */
1934 static int sctp_setsockopt_associnfo(struct sock *sk, char __user *optval, int optlen)
1935 {
1936
1937         struct sctp_assocparams assocparams;
1938         struct sctp_association *asoc;
1939
1940         if (optlen != sizeof(struct sctp_assocparams))
1941                 return -EINVAL;
1942         if (copy_from_user(&assocparams, optval, optlen))
1943                 return -EFAULT;
1944
1945         asoc = sctp_id2assoc(sk, assocparams.sasoc_assoc_id);
1946
1947         if (!asoc && assocparams.sasoc_assoc_id && sctp_style(sk, UDP))
1948                 return -EINVAL;
1949
1950         /* Set the values to the specific association */
1951         if (asoc) {
1952                 if (assocparams.sasoc_asocmaxrxt != 0)
1953                         asoc->max_retrans = assocparams.sasoc_asocmaxrxt;
1954                 if (assocparams.sasoc_cookie_life != 0) {
1955                         asoc->cookie_life.tv_sec =
1956                                         assocparams.sasoc_cookie_life / 1000;
1957                         asoc->cookie_life.tv_usec =
1958                                         (assocparams.sasoc_cookie_life % 1000)
1959                                         * 1000;
1960                 }
1961         } else {
1962                 /* Set the values to the endpoint */
1963                 struct sctp_opt *sp = sctp_sk(sk);
1964
1965                 if (assocparams.sasoc_asocmaxrxt != 0)
1966                         sp->assocparams.sasoc_asocmaxrxt =
1967                                                 assocparams.sasoc_asocmaxrxt;
1968                 if (assocparams.sasoc_cookie_life != 0)
1969                         sp->assocparams.sasoc_cookie_life =
1970                                                 assocparams.sasoc_cookie_life;
1971         }
1972         return 0;
1973 }
1974
1975 /*
1976  * 7.1.16 Set/clear IPv4 mapped addresses (SCTP_I_WANT_MAPPED_V4_ADDR)
1977  *
1978  * This socket option is a boolean flag which turns on or off mapped V4
1979  * addresses.  If this option is turned on and the socket is type
1980  * PF_INET6, then IPv4 addresses will be mapped to V6 representation.
1981  * If this option is turned off, then no mapping will be done of V4
1982  * addresses and a user will receive both PF_INET6 and PF_INET type
1983  * addresses on the socket.
1984  */
1985 static int sctp_setsockopt_mappedv4(struct sock *sk, char __user *optval, int optlen)
1986 {
1987         int val;
1988         struct sctp_opt *sp = sctp_sk(sk);
1989
1990         if (optlen < sizeof(int))
1991                 return -EINVAL;
1992         if (get_user(val, (int __user *)optval))
1993                 return -EFAULT;
1994         if (val)
1995                 sp->v4mapped = 1;
1996         else
1997                 sp->v4mapped = 0;
1998
1999         return 0;
2000 }
2001
2002 /*
2003  * 7.1.17 Set the maximum fragrmentation size (SCTP_MAXSEG)
2004  *
2005  * This socket option specifies the maximum size to put in any outgoing
2006  * SCTP chunk.  If a message is larger than this size it will be
2007  * fragmented by SCTP into the specified size.  Note that the underlying
2008  * SCTP implementation may fragment into smaller sized chunks when the
2009  * PMTU of the underlying association is smaller than the value set by
2010  * the user.
2011  */
2012 static int sctp_setsockopt_maxseg(struct sock *sk, char __user *optval, int optlen)
2013 {
2014         struct sctp_association *asoc;
2015         struct list_head *pos;
2016         struct sctp_opt *sp = sctp_sk(sk);
2017         int val;
2018
2019         if (optlen < sizeof(int))
2020                 return -EINVAL;
2021         if (get_user(val, (int __user *)optval))
2022                 return -EFAULT;
2023         if ((val < 8) || (val > SCTP_MAX_CHUNK_LEN))
2024                 return -EINVAL;
2025         sp->user_frag = val;
2026
2027         if (val) {
2028                 /* Update the frag_point of the existing associations. */
2029                 list_for_each(pos, &(sp->ep->asocs)) {
2030                         asoc = list_entry(pos, struct sctp_association, asocs);
2031                         asoc->frag_point = sctp_frag_point(sp, asoc->pmtu); 
2032                 }
2033         }
2034
2035         return 0;
2036 }
2037
2038
2039 /*
2040  *  7.1.9 Set Peer Primary Address (SCTP_SET_PEER_PRIMARY_ADDR)
2041  *
2042  *   Requests that the peer mark the enclosed address as the association
2043  *   primary. The enclosed address must be one of the association's
2044  *   locally bound addresses. The following structure is used to make a
2045  *   set primary request:
2046  */
2047 static int sctp_setsockopt_peer_primary_addr(struct sock *sk, char __user *optval,
2048                                              int optlen)
2049 {
2050         struct sctp_opt         *sp;
2051         struct sctp_endpoint    *ep;
2052         struct sctp_association *asoc = NULL;
2053         struct sctp_setpeerprim prim;
2054         struct sctp_chunk       *chunk;
2055         int                     err;
2056
2057         sp = sctp_sk(sk);
2058         ep = sp->ep;
2059
2060         if (!sctp_addip_enable)
2061                 return -EPERM;
2062
2063         if (optlen != sizeof(struct sctp_setpeerprim))
2064                 return -EINVAL;
2065
2066         if (copy_from_user(&prim, optval, optlen))
2067                 return -EFAULT;
2068
2069         asoc = sctp_id2assoc(sk, prim.sspp_assoc_id);
2070         if (!asoc) 
2071                 return -EINVAL;
2072
2073         if (!asoc->peer.asconf_capable)
2074                 return -EPERM;
2075
2076         if (asoc->peer.addip_disabled_mask & SCTP_PARAM_SET_PRIMARY)
2077                 return -EPERM;
2078
2079         if (!sctp_state(asoc, ESTABLISHED))
2080                 return -ENOTCONN;
2081
2082         if (!sctp_assoc_lookup_laddr(asoc, (union sctp_addr *)&prim.sspp_addr))
2083                 return -EADDRNOTAVAIL;
2084
2085         /* Create an ASCONF chunk with SET_PRIMARY parameter    */
2086         chunk = sctp_make_asconf_set_prim(asoc,
2087                                           (union sctp_addr *)&prim.sspp_addr);
2088         if (!chunk)
2089                 return -ENOMEM;
2090
2091         err = sctp_send_asconf(asoc, chunk);
2092
2093         SCTP_DEBUG_PRINTK("We set peer primary addr primitively.\n");
2094
2095         return err;
2096 }
2097
2098
2099 /* API 6.2 setsockopt(), getsockopt()
2100  *
2101  * Applications use setsockopt() and getsockopt() to set or retrieve
2102  * socket options.  Socket options are used to change the default
2103  * behavior of sockets calls.  They are described in Section 7.
2104  *
2105  * The syntax is:
2106  *
2107  *   ret = getsockopt(int sd, int level, int optname, void __user *optval,
2108  *                    int __user *optlen);
2109  *   ret = setsockopt(int sd, int level, int optname, const void __user *optval,
2110  *                    int optlen);
2111  *
2112  *   sd      - the socket descript.
2113  *   level   - set to IPPROTO_SCTP for all SCTP options.
2114  *   optname - the option name.
2115  *   optval  - the buffer to store the value of the option.
2116  *   optlen  - the size of the buffer.
2117  */
2118 SCTP_STATIC int sctp_setsockopt(struct sock *sk, int level, int optname,
2119                                 char __user *optval, int optlen)
2120 {
2121         int retval = 0;
2122
2123         SCTP_DEBUG_PRINTK("sctp_setsockopt(sk: %p... optname: %d)\n",
2124                           sk, optname);
2125
2126         /* I can hardly begin to describe how wrong this is.  This is
2127          * so broken as to be worse than useless.  The API draft
2128          * REALLY is NOT helpful here...  I am not convinced that the
2129          * semantics of setsockopt() with a level OTHER THAN SOL_SCTP
2130          * are at all well-founded.
2131          */
2132         if (level != SOL_SCTP) {
2133                 struct sctp_af *af = sctp_sk(sk)->pf->af;
2134                 retval = af->setsockopt(sk, level, optname, optval, optlen);
2135                 goto out_nounlock;
2136         }
2137
2138         sctp_lock_sock(sk);
2139
2140         switch (optname) {
2141         case SCTP_SOCKOPT_BINDX_ADD:
2142                 /* 'optlen' is the size of the addresses buffer. */
2143                 retval = sctp_setsockopt_bindx(sk, (struct sockaddr __user *)optval,
2144                                                optlen, SCTP_BINDX_ADD_ADDR);
2145                 break;
2146
2147         case SCTP_SOCKOPT_BINDX_REM:
2148                 /* 'optlen' is the size of the addresses buffer. */
2149                 retval = sctp_setsockopt_bindx(sk, (struct sockaddr __user *)optval,
2150                                                optlen, SCTP_BINDX_REM_ADDR);
2151                 break;
2152
2153         case SCTP_DISABLE_FRAGMENTS:
2154                 retval = sctp_setsockopt_disable_fragments(sk, optval, optlen);
2155                 break;
2156
2157         case SCTP_EVENTS:
2158                 retval = sctp_setsockopt_events(sk, optval, optlen);
2159                 break;
2160
2161         case SCTP_AUTOCLOSE:
2162                 retval = sctp_setsockopt_autoclose(sk, optval, optlen);
2163                 break;
2164
2165         case SCTP_PEER_ADDR_PARAMS:
2166                 retval = sctp_setsockopt_peer_addr_params(sk, optval, optlen);
2167                 break;
2168
2169         case SCTP_INITMSG:
2170                 retval = sctp_setsockopt_initmsg(sk, optval, optlen);
2171                 break;
2172         case SCTP_DEFAULT_SEND_PARAM:
2173                 retval = sctp_setsockopt_default_send_param(sk, optval,
2174                                                             optlen);
2175                 break;
2176         case SCTP_PRIMARY_ADDR:
2177                 retval = sctp_setsockopt_primary_addr(sk, optval, optlen);
2178                 break;
2179         case SCTP_SET_PEER_PRIMARY_ADDR:
2180                 retval = sctp_setsockopt_peer_primary_addr(sk, optval, optlen);
2181                 break;
2182         case SCTP_NODELAY:
2183                 retval = sctp_setsockopt_nodelay(sk, optval, optlen);
2184                 break;
2185         case SCTP_RTOINFO:
2186                 retval = sctp_setsockopt_rtoinfo(sk, optval, optlen);
2187                 break;
2188         case SCTP_ASSOCINFO:
2189                 retval = sctp_setsockopt_associnfo(sk, optval, optlen);
2190                 break;
2191         case SCTP_I_WANT_MAPPED_V4_ADDR:
2192                 retval = sctp_setsockopt_mappedv4(sk, optval, optlen);
2193                 break;
2194         case SCTP_MAXSEG:
2195                 retval = sctp_setsockopt_maxseg(sk, optval, optlen);
2196                 break;
2197         default:
2198                 retval = -ENOPROTOOPT;
2199                 break;
2200         };
2201
2202         sctp_release_sock(sk);
2203
2204 out_nounlock:
2205         return retval;
2206 }
2207
2208 /* API 3.1.6 connect() - UDP Style Syntax
2209  *
2210  * An application may use the connect() call in the UDP model to initiate an
2211  * association without sending data.
2212  *
2213  * The syntax is:
2214  *
2215  * ret = connect(int sd, const struct sockaddr *nam, socklen_t len);
2216  *
2217  * sd: the socket descriptor to have a new association added to.
2218  *
2219  * nam: the address structure (either struct sockaddr_in or struct
2220  *    sockaddr_in6 defined in RFC2553 [7]).
2221  *
2222  * len: the size of the address.
2223  */
2224 SCTP_STATIC int sctp_connect(struct sock *sk, struct sockaddr *uaddr,
2225                              int addr_len)
2226 {
2227         struct sctp_opt *sp;
2228         struct sctp_endpoint *ep;
2229         struct sctp_association *asoc;
2230         struct sctp_transport *transport;
2231         union sctp_addr to;
2232         struct sctp_af *af;
2233         sctp_scope_t scope;
2234         long timeo;
2235         int err = 0;
2236
2237         sctp_lock_sock(sk);
2238
2239         SCTP_DEBUG_PRINTK("%s - sk: %p, sockaddr: %p, addr_len: %d)\n",
2240                           __FUNCTION__, sk, uaddr, addr_len);
2241
2242         sp = sctp_sk(sk);
2243         ep = sp->ep;
2244
2245         /* connect() cannot be done on a socket that is already in ESTABLISHED
2246          * state - UDP-style peeled off socket or a TCP-style socket that
2247          * is already connected.
2248          * It cannot be done even on a TCP-style listening socket.
2249          */
2250         if (sctp_sstate(sk, ESTABLISHED) ||
2251             (sctp_style(sk, TCP) && sctp_sstate(sk, LISTENING))) {
2252                 err = -EISCONN;
2253                 goto out_unlock;
2254         }
2255
2256         err = sctp_verify_addr(sk, (union sctp_addr *)uaddr, addr_len);
2257         if (err)
2258                 goto out_unlock;
2259
2260         if (addr_len > sizeof(to))
2261                 addr_len = sizeof(to);
2262         memcpy(&to, uaddr, addr_len);
2263         to.v4.sin_port = ntohs(to.v4.sin_port);
2264
2265         asoc = sctp_endpoint_lookup_assoc(ep, &to, &transport);
2266         if (asoc) {
2267                 if (asoc->state >= SCTP_STATE_ESTABLISHED)
2268                         err = -EISCONN;
2269                 else
2270                         err = -EALREADY;
2271                 goto out_unlock;
2272         }
2273
2274         /* If we could not find a matching association on the endpoint,
2275          * make sure that there is no peeled-off association matching the
2276          * peer address even on another socket.
2277          */
2278         if (sctp_endpoint_is_peeled_off(ep, &to)) {
2279                 err = -EADDRNOTAVAIL;
2280                 goto out_unlock;
2281         }
2282
2283         /* If a bind() or sctp_bindx() is not called prior to a connect()
2284          * call, the system picks an ephemeral port and will choose an address
2285          * set equivalent to binding with a wildcard address.
2286          */
2287         if (!ep->base.bind_addr.port) {
2288                 if (sctp_autobind(sk)) {
2289                         err = -EAGAIN;
2290                         goto out_unlock;
2291                 }
2292         }
2293
2294         scope = sctp_scope(&to);
2295         asoc = sctp_association_new(ep, sk, scope, GFP_KERNEL);
2296         if (!asoc) {
2297                 err = -ENOMEM;
2298                 goto out_unlock;
2299         }
2300
2301         /* Prime the peer's transport structures.  */
2302         transport = sctp_assoc_add_peer(asoc, &to, GFP_KERNEL);
2303         if (!transport) {
2304                 sctp_association_free(asoc);
2305                 goto out_unlock;
2306         }
2307         err = sctp_assoc_set_bind_addr_from_ep(asoc, GFP_KERNEL);
2308         if (err < 0) {
2309                 sctp_association_free(asoc);
2310                 goto out_unlock;
2311         }
2312
2313         err = sctp_primitive_ASSOCIATE(asoc, NULL);
2314         if (err < 0) {
2315                 sctp_association_free(asoc);
2316                 goto out_unlock;
2317         }
2318
2319         /* Initialize sk's dport and daddr for getpeername() */
2320         inet_sk(sk)->dport = htons(asoc->peer.port);
2321         af = sctp_get_af_specific(to.sa.sa_family);
2322         af->to_sk_daddr(&to, sk);
2323
2324         timeo = sock_sndtimeo(sk, sk->sk_socket->file->f_flags & O_NONBLOCK);
2325         err = sctp_wait_for_connect(asoc, &timeo);
2326
2327 out_unlock:
2328         sctp_release_sock(sk);
2329
2330         return err;
2331 }
2332
2333 /* FIXME: Write comments. */
2334 SCTP_STATIC int sctp_disconnect(struct sock *sk, int flags)
2335 {
2336         return -EOPNOTSUPP; /* STUB */
2337 }
2338
2339 /* 4.1.4 accept() - TCP Style Syntax
2340  *
2341  * Applications use accept() call to remove an established SCTP
2342  * association from the accept queue of the endpoint.  A new socket
2343  * descriptor will be returned from accept() to represent the newly
2344  * formed association.
2345  */
2346 SCTP_STATIC struct sock *sctp_accept(struct sock *sk, int flags, int *err)
2347 {
2348         struct sctp_opt *sp;
2349         struct sctp_endpoint *ep;
2350         struct sock *newsk = NULL;
2351         struct sctp_association *asoc;
2352         long timeo;
2353         int error = 0;
2354
2355         sctp_lock_sock(sk);
2356
2357         sp = sctp_sk(sk);
2358         ep = sp->ep;
2359
2360         if (!sctp_style(sk, TCP)) {
2361                 error = -EOPNOTSUPP;
2362                 goto out;
2363         }
2364
2365         if (!sctp_sstate(sk, LISTENING)) {
2366                 error = -EINVAL;
2367                 goto out;
2368         }
2369
2370         timeo = sock_rcvtimeo(sk, sk->sk_socket->file->f_flags & O_NONBLOCK);
2371
2372         error = sctp_wait_for_accept(sk, timeo);
2373         if (error)
2374                 goto out;
2375
2376         /* We treat the list of associations on the endpoint as the accept
2377          * queue and pick the first association on the list.
2378          */
2379         asoc = list_entry(ep->asocs.next, struct sctp_association, asocs);
2380
2381         newsk = sp->pf->create_accept_sk(sk, asoc);
2382         if (!newsk) {
2383                 error = -ENOMEM;
2384                 goto out;
2385         }
2386
2387         /* Populate the fields of the newsk from the oldsk and migrate the
2388          * asoc to the newsk.
2389          */
2390         sctp_sock_migrate(sk, newsk, asoc, SCTP_SOCKET_TCP);
2391
2392 out:
2393         sctp_release_sock(sk);
2394         *err = error;
2395         return newsk;
2396 }
2397
2398 /* The SCTP ioctl handler. */
2399 SCTP_STATIC int sctp_ioctl(struct sock *sk, int cmd, unsigned long arg)
2400 {
2401         return -ENOIOCTLCMD;
2402 }
2403
2404 /* This is the function which gets called during socket creation to
2405  * initialized the SCTP-specific portion of the sock.
2406  * The sock structure should already be zero-filled memory.
2407  */
2408 SCTP_STATIC int sctp_init_sock(struct sock *sk)
2409 {
2410         struct sctp_endpoint *ep;
2411         struct sctp_opt *sp;
2412
2413         SCTP_DEBUG_PRINTK("sctp_init_sock(sk: %p)\n", sk);
2414
2415         sp = sctp_sk(sk);
2416
2417         /* Initialize the SCTP per socket area.  */
2418         switch (sk->sk_type) {
2419         case SOCK_SEQPACKET:
2420                 sp->type = SCTP_SOCKET_UDP;
2421                 break;
2422         case SOCK_STREAM:
2423                 sp->type = SCTP_SOCKET_TCP;
2424                 break;
2425         default:
2426                 return -ESOCKTNOSUPPORT;
2427         }
2428
2429         /* Initialize default send parameters. These parameters can be
2430          * modified with the SCTP_DEFAULT_SEND_PARAM socket option.
2431          */
2432         sp->default_stream = 0;
2433         sp->default_ppid = 0;
2434         sp->default_flags = 0;
2435         sp->default_context = 0;
2436         sp->default_timetolive = 0;
2437
2438         /* Initialize default setup parameters. These parameters
2439          * can be modified with the SCTP_INITMSG socket option or
2440          * overridden by the SCTP_INIT CMSG.
2441          */
2442         sp->initmsg.sinit_num_ostreams   = sctp_max_outstreams;
2443         sp->initmsg.sinit_max_instreams  = sctp_max_instreams;
2444         sp->initmsg.sinit_max_attempts   = sctp_max_retrans_init;
2445         sp->initmsg.sinit_max_init_timeo = jiffies_to_msecs(sctp_rto_max);
2446
2447         /* Initialize default RTO related parameters.  These parameters can
2448          * be modified for with the SCTP_RTOINFO socket option.
2449          */
2450         sp->rtoinfo.srto_initial = jiffies_to_msecs(sctp_rto_initial);
2451         sp->rtoinfo.srto_max     = jiffies_to_msecs(sctp_rto_max);
2452         sp->rtoinfo.srto_min     = jiffies_to_msecs(sctp_rto_min);
2453
2454         /* Initialize default association related parameters. These parameters
2455          * can be modified with the SCTP_ASSOCINFO socket option.
2456          */
2457         sp->assocparams.sasoc_asocmaxrxt = sctp_max_retrans_association;
2458         sp->assocparams.sasoc_number_peer_destinations = 0;
2459         sp->assocparams.sasoc_peer_rwnd = 0;
2460         sp->assocparams.sasoc_local_rwnd = 0;
2461         sp->assocparams.sasoc_cookie_life = 
2462                 jiffies_to_msecs(sctp_valid_cookie_life);
2463
2464         /* Initialize default event subscriptions. By default, all the
2465          * options are off. 
2466          */
2467         memset(&sp->subscribe, 0, sizeof(struct sctp_event_subscribe));
2468
2469         /* Default Peer Address Parameters.  These defaults can
2470          * be modified via SCTP_PEER_ADDR_PARAMS
2471          */
2472         sp->paddrparam.spp_hbinterval = jiffies_to_msecs(sctp_hb_interval);
2473         sp->paddrparam.spp_pathmaxrxt = sctp_max_retrans_path;
2474
2475         /* If enabled no SCTP message fragmentation will be performed.
2476          * Configure through SCTP_DISABLE_FRAGMENTS socket option.
2477          */
2478         sp->disable_fragments = 0;
2479
2480         /* Turn on/off any Nagle-like algorithm.  */
2481         sp->nodelay           = 1;
2482
2483         /* Enable by default. */
2484         sp->v4mapped          = 1;
2485
2486         /* Auto-close idle associations after the configured
2487          * number of seconds.  A value of 0 disables this
2488          * feature.  Configure through the SCTP_AUTOCLOSE socket option,
2489          * for UDP-style sockets only.
2490          */
2491         sp->autoclose         = 0;
2492
2493         /* User specified fragmentation limit. */
2494         sp->user_frag         = 0;
2495
2496         sp->pf = sctp_get_pf_specific(sk->sk_family);
2497
2498         /* Control variables for partial data delivery. */
2499         sp->pd_mode           = 0;
2500         skb_queue_head_init(&sp->pd_lobby);
2501
2502         /* Create a per socket endpoint structure.  Even if we
2503          * change the data structure relationships, this may still
2504          * be useful for storing pre-connect address information.
2505          */
2506         ep = sctp_endpoint_new(sk, GFP_KERNEL);
2507         if (!ep)
2508                 return -ENOMEM;
2509
2510         sp->ep = ep;
2511         sp->hmac = NULL;
2512
2513         SCTP_DBG_OBJCNT_INC(sock);
2514         return 0;
2515 }
2516
2517 /* Cleanup any SCTP per socket resources.  */
2518 SCTP_STATIC int sctp_destroy_sock(struct sock *sk)
2519 {
2520         struct sctp_endpoint *ep;
2521
2522         SCTP_DEBUG_PRINTK("sctp_destroy_sock(sk: %p)\n", sk);
2523
2524         /* Release our hold on the endpoint. */
2525         ep = sctp_sk(sk)->ep;
2526         sctp_endpoint_free(ep);
2527
2528         return 0;
2529 }
2530
2531 /* API 4.1.7 shutdown() - TCP Style Syntax
2532  *     int shutdown(int socket, int how);
2533  *
2534  *     sd      - the socket descriptor of the association to be closed.
2535  *     how     - Specifies the type of shutdown.  The  values  are
2536  *               as follows:
2537  *               SHUT_RD
2538  *                     Disables further receive operations. No SCTP
2539  *                     protocol action is taken.
2540  *               SHUT_WR
2541  *                     Disables further send operations, and initiates
2542  *                     the SCTP shutdown sequence.
2543  *               SHUT_RDWR
2544  *                     Disables further send  and  receive  operations
2545  *                     and initiates the SCTP shutdown sequence.
2546  */
2547 SCTP_STATIC void sctp_shutdown(struct sock *sk, int how)
2548 {
2549         struct sctp_endpoint *ep;
2550         struct sctp_association *asoc;
2551
2552         if (!sctp_style(sk, TCP))
2553                 return;
2554
2555         if (how & SEND_SHUTDOWN) {
2556                 ep = sctp_sk(sk)->ep;
2557                 if (!list_empty(&ep->asocs)) {
2558                         asoc = list_entry(ep->asocs.next,
2559                                           struct sctp_association, asocs);
2560                         sctp_primitive_SHUTDOWN(asoc, NULL);
2561                 }
2562         }
2563 }
2564
2565 /* 7.2.1 Association Status (SCTP_STATUS)
2566
2567  * Applications can retrieve current status information about an
2568  * association, including association state, peer receiver window size,
2569  * number of unacked data chunks, and number of data chunks pending
2570  * receipt.  This information is read-only.
2571  */
2572 static int sctp_getsockopt_sctp_status(struct sock *sk, int len,
2573                                        char __user *optval,
2574                                        int __user *optlen)
2575 {
2576         struct sctp_status status;
2577         struct sctp_association *asoc = NULL;
2578         struct sctp_transport *transport;
2579         sctp_assoc_t associd;
2580         int retval = 0;
2581
2582         if (len != sizeof(status)) {
2583                 retval = -EINVAL;
2584                 goto out;
2585         }
2586
2587         if (copy_from_user(&status, optval, sizeof(status))) {
2588                 retval = -EFAULT;
2589                 goto out;
2590         }
2591
2592         associd = status.sstat_assoc_id;
2593         asoc = sctp_id2assoc(sk, associd);
2594         if (!asoc) {
2595                 retval = -EINVAL;
2596                 goto out;
2597         }
2598
2599         transport = asoc->peer.primary_path;
2600
2601         status.sstat_assoc_id = sctp_assoc2id(asoc);
2602         status.sstat_state = asoc->state;
2603         status.sstat_rwnd =  asoc->peer.rwnd;
2604         status.sstat_unackdata = asoc->unack_data;
2605
2606         status.sstat_penddata = sctp_tsnmap_pending(&asoc->peer.tsn_map);
2607         status.sstat_instrms = asoc->c.sinit_max_instreams;
2608         status.sstat_outstrms = asoc->c.sinit_num_ostreams;
2609         status.sstat_fragmentation_point = asoc->frag_point;
2610         status.sstat_primary.spinfo_assoc_id = sctp_assoc2id(transport->asoc);
2611         memcpy(&status.sstat_primary.spinfo_address,
2612                &(transport->ipaddr), sizeof(union sctp_addr));
2613         /* Map ipv4 address into v4-mapped-on-v6 address.  */
2614         sctp_get_pf_specific(sk->sk_family)->addr_v4map(sctp_sk(sk),
2615                 (union sctp_addr *)&status.sstat_primary.spinfo_address);
2616         status.sstat_primary.spinfo_state = transport->active;
2617         status.sstat_primary.spinfo_cwnd = transport->cwnd;
2618         status.sstat_primary.spinfo_srtt = transport->srtt;
2619         status.sstat_primary.spinfo_rto = jiffies_to_msecs(transport->rto);
2620         status.sstat_primary.spinfo_mtu = transport->pmtu;
2621
2622         if (put_user(len, optlen)) {
2623                 retval = -EFAULT;
2624                 goto out;
2625         }
2626
2627         SCTP_DEBUG_PRINTK("sctp_getsockopt_sctp_status(%d): %d %d %p\n",
2628                           len, status.sstat_state, status.sstat_rwnd,
2629                           status.sstat_assoc_id);
2630
2631         if (copy_to_user(optval, &status, len)) {
2632                 retval = -EFAULT;
2633                 goto out;
2634         }
2635
2636 out:
2637         return (retval);
2638 }
2639
2640
2641 /* 7.2.2 Peer Address Information (SCTP_GET_PEER_ADDR_INFO)
2642  *
2643  * Applications can retrieve information about a specific peer address
2644  * of an association, including its reachability state, congestion
2645  * window, and retransmission timer values.  This information is
2646  * read-only.
2647  */
2648 static int sctp_getsockopt_peer_addr_info(struct sock *sk, int len,
2649                                           char __user *optval,
2650                                           int __user *optlen)
2651 {
2652         struct sctp_paddrinfo pinfo;
2653         struct sctp_transport *transport;
2654         int retval = 0;
2655
2656         if (len != sizeof(pinfo)) {
2657                 retval = -EINVAL;
2658                 goto out;
2659         }
2660
2661         if (copy_from_user(&pinfo, optval, sizeof(pinfo))) {
2662                 retval = -EFAULT;
2663                 goto out;
2664         }
2665
2666         transport = sctp_addr_id2transport(sk, &pinfo.spinfo_address,
2667                                            pinfo.spinfo_assoc_id);
2668         if (!transport)
2669                 return -EINVAL;
2670
2671         pinfo.spinfo_assoc_id = sctp_assoc2id(transport->asoc);
2672         pinfo.spinfo_state = transport->active;
2673         pinfo.spinfo_cwnd = transport->cwnd;
2674         pinfo.spinfo_srtt = transport->srtt;
2675         pinfo.spinfo_rto = jiffies_to_msecs(transport->rto);
2676         pinfo.spinfo_mtu = transport->pmtu;
2677
2678         if (put_user(len, optlen)) {
2679                 retval = -EFAULT;
2680                 goto out;
2681         }
2682
2683         if (copy_to_user(optval, &pinfo, len)) {
2684                 retval = -EFAULT;
2685                 goto out;
2686         }
2687
2688 out:
2689         return (retval);
2690 }
2691
2692 /* 7.1.12 Enable/Disable message fragmentation (SCTP_DISABLE_FRAGMENTS)
2693  *
2694  * This option is a on/off flag.  If enabled no SCTP message
2695  * fragmentation will be performed.  Instead if a message being sent
2696  * exceeds the current PMTU size, the message will NOT be sent and
2697  * instead a error will be indicated to the user.
2698  */
2699 static int sctp_getsockopt_disable_fragments(struct sock *sk, int len,
2700                                         char __user *optval, int __user *optlen)
2701 {
2702         int val;
2703
2704         if (len < sizeof(int))
2705                 return -EINVAL;
2706
2707         len = sizeof(int);
2708         val = (sctp_sk(sk)->disable_fragments == 1);
2709         if (put_user(len, optlen))
2710                 return -EFAULT;
2711         if (copy_to_user(optval, &val, len))
2712                 return -EFAULT;
2713         return 0;
2714 }
2715
2716 /* 7.1.15 Set notification and ancillary events (SCTP_EVENTS)
2717  *
2718  * This socket option is used to specify various notifications and
2719  * ancillary data the user wishes to receive.
2720  */
2721 static int sctp_getsockopt_events(struct sock *sk, int len, char __user *optval,
2722                                   int __user *optlen)
2723 {
2724         if (len != sizeof(struct sctp_event_subscribe))
2725                 return -EINVAL;
2726         if (copy_to_user(optval, &sctp_sk(sk)->subscribe, len))
2727                 return -EFAULT;
2728         return 0;
2729 }
2730
2731 /* 7.1.8 Automatic Close of associations (SCTP_AUTOCLOSE)
2732  *
2733  * This socket option is applicable to the UDP-style socket only.  When
2734  * set it will cause associations that are idle for more than the
2735  * specified number of seconds to automatically close.  An association
2736  * being idle is defined an association that has NOT sent or received
2737  * user data.  The special value of '0' indicates that no automatic
2738  * close of any associations should be performed.  The option expects an
2739  * integer defining the number of seconds of idle time before an
2740  * association is closed.
2741  */
2742 static int sctp_getsockopt_autoclose(struct sock *sk, int len, char __user *optval, int __user *optlen)
2743 {
2744         /* Applicable to UDP-style socket only */
2745         if (sctp_style(sk, TCP))
2746                 return -EOPNOTSUPP;
2747         if (len != sizeof(int))
2748                 return -EINVAL;
2749         if (copy_to_user(optval, &sctp_sk(sk)->autoclose, len))
2750                 return -EFAULT;
2751         return 0;
2752 }
2753
2754 /* Helper routine to branch off an association to a new socket.  */
2755 SCTP_STATIC int sctp_do_peeloff(struct sctp_association *asoc,
2756                                 struct socket **sockp)
2757 {
2758         struct sock *sk = asoc->base.sk;
2759         struct socket *sock;
2760         int err = 0;
2761
2762         /* An association cannot be branched off from an already peeled-off
2763          * socket, nor is this supported for tcp style sockets.
2764          */
2765         if (!sctp_style(sk, UDP))
2766                 return -EINVAL;
2767
2768         /* Create a new socket.  */
2769         err = sock_create(sk->sk_family, SOCK_SEQPACKET, IPPROTO_SCTP, &sock);
2770         if (err < 0)
2771                 return err;
2772
2773         /* Populate the fields of the newsk from the oldsk and migrate the
2774          * asoc to the newsk.
2775          */
2776         sctp_sock_migrate(sk, sock->sk, asoc, SCTP_SOCKET_UDP_HIGH_BANDWIDTH);
2777         *sockp = sock;
2778
2779         return err;
2780 }
2781
2782 static int sctp_getsockopt_peeloff(struct sock *sk, int len, char __user *optval, int __user *optlen)
2783 {
2784         sctp_peeloff_arg_t peeloff;
2785         struct socket *newsock;
2786         int retval = 0;
2787         struct sctp_association *asoc;
2788
2789         if (len != sizeof(sctp_peeloff_arg_t))
2790                 return -EINVAL;
2791         if (copy_from_user(&peeloff, optval, len))
2792                 return -EFAULT;
2793
2794         asoc = sctp_id2assoc(sk, peeloff.associd);
2795         if (!asoc) {
2796                 retval = -EINVAL;
2797                 goto out;
2798         }
2799
2800         SCTP_DEBUG_PRINTK("%s: sk: %p asoc: %p\n", __FUNCTION__, sk, asoc);
2801
2802         retval = sctp_do_peeloff(asoc, &newsock);
2803         if (retval < 0)
2804                 goto out;
2805
2806         /* Map the socket to an unused fd that can be returned to the user.  */
2807         retval = sock_map_fd(newsock);
2808         if (retval < 0) {
2809                 sock_release(newsock);
2810                 goto out;
2811         }
2812
2813         SCTP_DEBUG_PRINTK("%s: sk: %p asoc: %p newsk: %p sd: %d\n",
2814                           __FUNCTION__, sk, asoc, newsock->sk, retval);
2815
2816         /* Return the fd mapped to the new socket.  */
2817         peeloff.sd = retval;
2818         if (copy_to_user(optval, &peeloff, len))
2819                 retval = -EFAULT;
2820
2821 out:
2822         return retval;
2823 }
2824
2825 /* 7.1.13 Peer Address Parameters (SCTP_PEER_ADDR_PARAMS)
2826  *
2827  * Applications can enable or disable heartbeats for any peer address of
2828  * an association, modify an address's heartbeat interval, force a
2829  * heartbeat to be sent immediately, and adjust the address's maximum
2830  * number of retransmissions sent before an address is considered
2831  * unreachable.  The following structure is used to access and modify an
2832  * address's parameters:
2833  *
2834  *  struct sctp_paddrparams {
2835  *      sctp_assoc_t            spp_assoc_id;
2836  *      struct sockaddr_storage spp_address;
2837  *      uint32_t                spp_hbinterval;
2838  *      uint16_t                spp_pathmaxrxt;
2839  *  };
2840  *
2841  *   spp_assoc_id    - (UDP style socket) This is filled in the application,
2842  *                     and identifies the association for this query.
2843  *   spp_address     - This specifies which address is of interest.
2844  *   spp_hbinterval  - This contains the value of the heartbeat interval,
2845  *                     in milliseconds.  A value of 0, when modifying the
2846  *                     parameter, specifies that the heartbeat on this
2847  *                     address should be disabled. A value of UINT32_MAX
2848  *                     (4294967295), when modifying the parameter,
2849  *                     specifies that a heartbeat should be sent
2850  *                     immediately to the peer address, and the current
2851  *                     interval should remain unchanged.
2852  *   spp_pathmaxrxt  - This contains the maximum number of
2853  *                     retransmissions before this address shall be
2854  *                     considered unreachable.
2855  */
2856 static int sctp_getsockopt_peer_addr_params(struct sock *sk, int len,
2857                                                 char __user *optval, int __user *optlen)
2858 {
2859         struct sctp_paddrparams params;
2860         struct sctp_transport *trans;
2861
2862         if (len != sizeof(struct sctp_paddrparams))
2863                 return -EINVAL;
2864         if (copy_from_user(&params, optval, len))
2865                 return -EFAULT;
2866
2867         trans = sctp_addr_id2transport(sk, &params.spp_address,
2868                                        params.spp_assoc_id);
2869         if (!trans)
2870                 return -EINVAL;
2871
2872         /* The value of the heartbeat interval, in milliseconds. A value of 0,
2873          * when modifying the parameter, specifies that the heartbeat on this
2874          * address should be disabled.
2875          */
2876         if (!trans->hb_allowed)
2877                 params.spp_hbinterval = 0;
2878         else
2879                 params.spp_hbinterval = jiffies_to_msecs(trans->hb_interval);
2880
2881         /* spp_pathmaxrxt contains the maximum number of retransmissions
2882          * before this address shall be considered unreachable.
2883          */
2884         params.spp_pathmaxrxt = trans->error_threshold;
2885
2886         if (copy_to_user(optval, &params, len))
2887                 return -EFAULT;
2888
2889         if (put_user(len, optlen))
2890                 return -EFAULT;
2891
2892         return 0;
2893 }
2894
2895 /* 7.1.3 Initialization Parameters (SCTP_INITMSG)
2896  *
2897  * Applications can specify protocol parameters for the default association
2898  * initialization.  The option name argument to setsockopt() and getsockopt()
2899  * is SCTP_INITMSG.
2900  *
2901  * Setting initialization parameters is effective only on an unconnected
2902  * socket (for UDP-style sockets only future associations are effected
2903  * by the change).  With TCP-style sockets, this option is inherited by
2904  * sockets derived from a listener socket.
2905  */
2906 static int sctp_getsockopt_initmsg(struct sock *sk, int len, char __user *optval, int __user *optlen)
2907 {
2908         if (len != sizeof(struct sctp_initmsg))
2909                 return -EINVAL;
2910         if (copy_to_user(optval, &sctp_sk(sk)->initmsg, len))
2911                 return -EFAULT;
2912         return 0;
2913 }
2914
2915 static int sctp_getsockopt_peer_addrs_num(struct sock *sk, int len,
2916                                           char __user *optval, int __user *optlen)
2917 {
2918         sctp_assoc_t id;
2919         struct sctp_association *asoc;
2920         struct list_head *pos;
2921         int cnt = 0;
2922
2923         if (len != sizeof(sctp_assoc_t))
2924                 return -EINVAL;
2925
2926         if (copy_from_user(&id, optval, sizeof(sctp_assoc_t)))
2927                 return -EFAULT;
2928
2929         /* For UDP-style sockets, id specifies the association to query.  */
2930         asoc = sctp_id2assoc(sk, id);
2931         if (!asoc)
2932                 return -EINVAL;
2933
2934         list_for_each(pos, &asoc->peer.transport_addr_list) {
2935                 cnt ++;
2936         }
2937
2938         return cnt;
2939 }
2940
2941 static int sctp_getsockopt_peer_addrs(struct sock *sk, int len,
2942                                       char __user *optval, int __user *optlen)
2943 {
2944         struct sctp_association *asoc;
2945         struct list_head *pos;
2946         int cnt = 0;
2947         struct sctp_getaddrs getaddrs;
2948         struct sctp_transport *from;
2949         void __user *to;
2950         union sctp_addr temp;
2951         struct sctp_opt *sp = sctp_sk(sk);
2952         int addrlen;
2953
2954         if (len != sizeof(struct sctp_getaddrs))
2955                 return -EINVAL;
2956
2957         if (copy_from_user(&getaddrs, optval, sizeof(struct sctp_getaddrs)))
2958                 return -EFAULT;
2959
2960         if (getaddrs.addr_num <= 0) return -EINVAL;
2961
2962         /* For UDP-style sockets, id specifies the association to query.  */
2963         asoc = sctp_id2assoc(sk, getaddrs.assoc_id);
2964         if (!asoc)
2965                 return -EINVAL;
2966
2967         to = (void __user *)getaddrs.addrs;
2968         list_for_each(pos, &asoc->peer.transport_addr_list) {
2969                 from = list_entry(pos, struct sctp_transport, transports);
2970                 memcpy(&temp, &from->ipaddr, sizeof(temp));
2971                 sctp_get_pf_specific(sk->sk_family)->addr_v4map(sp, &temp);
2972                 addrlen = sctp_get_af_specific(sk->sk_family)->sockaddr_len;
2973                 temp.v4.sin_port = htons(temp.v4.sin_port);
2974                 if (copy_to_user(to, &temp, addrlen))
2975                         return -EFAULT;
2976                 to += addrlen ;
2977                 cnt ++;
2978                 if (cnt >= getaddrs.addr_num) break;
2979         }
2980         getaddrs.addr_num = cnt;
2981         if (copy_to_user(optval, &getaddrs, sizeof(struct sctp_getaddrs)))
2982                 return -EFAULT;
2983
2984         return 0;
2985 }
2986
2987 static int sctp_getsockopt_local_addrs_num(struct sock *sk, int len,
2988                                                 char __user *optval,
2989                                                 int __user *optlen)
2990 {
2991         sctp_assoc_t id;
2992         struct sctp_bind_addr *bp;
2993         struct sctp_association *asoc;
2994         struct list_head *pos;
2995         int cnt = 0;
2996
2997         if (len != sizeof(sctp_assoc_t))
2998                 return -EINVAL;
2999
3000         if (copy_from_user(&id, optval, sizeof(sctp_assoc_t)))
3001                 return -EFAULT;
3002
3003         /*
3004          *  For UDP-style sockets, id specifies the association to query.
3005          *  If the id field is set to the value '0' then the locally bound
3006          *  addresses are returned without regard to any particular
3007          *  association.
3008          */
3009         if (0 == id) {
3010                 bp = &sctp_sk(sk)->ep->base.bind_addr;
3011         } else {
3012                 asoc = sctp_id2assoc(sk, id);
3013                 if (!asoc)
3014                         return -EINVAL;
3015                 bp = &asoc->base.bind_addr;
3016         }
3017
3018         list_for_each(pos, &bp->address_list) {
3019                 cnt ++;
3020         }
3021
3022         return cnt;
3023 }
3024
3025 static int sctp_getsockopt_local_addrs(struct sock *sk, int len,
3026                                         char __user *optval, int __user *optlen)
3027 {
3028         struct sctp_bind_addr *bp;
3029         struct sctp_association *asoc;
3030         struct list_head *pos;
3031         int cnt = 0;
3032         struct sctp_getaddrs getaddrs;
3033         struct sctp_sockaddr_entry *from;
3034         void __user *to;
3035         union sctp_addr temp;
3036         struct sctp_opt *sp = sctp_sk(sk);
3037         int addrlen;
3038
3039         if (len != sizeof(struct sctp_getaddrs))
3040                 return -EINVAL;
3041
3042         if (copy_from_user(&getaddrs, optval, sizeof(struct sctp_getaddrs)))
3043                 return -EFAULT;
3044
3045         if (getaddrs.addr_num <= 0) return -EINVAL;
3046         /*
3047          *  For UDP-style sockets, id specifies the association to query.
3048          *  If the id field is set to the value '0' then the locally bound
3049          *  addresses are returned without regard to any particular
3050          *  association.
3051          */
3052         if (0 == getaddrs.assoc_id) {
3053                 bp = &sctp_sk(sk)->ep->base.bind_addr;
3054         } else {
3055                 asoc = sctp_id2assoc(sk, getaddrs.assoc_id);
3056                 if (!asoc)
3057                         return -EINVAL;
3058                 bp = &asoc->base.bind_addr;
3059         }
3060
3061         to = getaddrs.addrs;
3062         list_for_each(pos, &bp->address_list) {
3063                 from = list_entry(pos,
3064                                 struct sctp_sockaddr_entry,
3065                                 list);
3066                 memcpy(&temp, &from->a, sizeof(temp));
3067                 sctp_get_pf_specific(sk->sk_family)->addr_v4map(sp, &temp);
3068                 addrlen = sctp_get_af_specific(temp.sa.sa_family)->sockaddr_len;
3069                 temp.v4.sin_port = htons(temp.v4.sin_port);
3070                 if (copy_to_user(to, &temp, addrlen))
3071                         return -EFAULT;
3072                 to += addrlen;
3073                 cnt ++;
3074                 if (cnt >= getaddrs.addr_num) break;
3075         }
3076         getaddrs.addr_num = cnt;
3077         if (copy_to_user(optval, &getaddrs, sizeof(struct sctp_getaddrs)))
3078                 return -EFAULT;
3079
3080         return 0;
3081 }
3082
3083 /* 7.1.10 Set Primary Address (SCTP_PRIMARY_ADDR)
3084  *
3085  * Requests that the local SCTP stack use the enclosed peer address as
3086  * the association primary.  The enclosed address must be one of the
3087  * association peer's addresses.
3088  */
3089 static int sctp_getsockopt_primary_addr(struct sock *sk, int len,
3090                                         char __user *optval, int __user *optlen)
3091 {
3092         struct sctp_prim prim;
3093         struct sctp_association *asoc;
3094         struct sctp_opt *sp = sctp_sk(sk);
3095
3096         if (len != sizeof(struct sctp_prim))
3097                 return -EINVAL;
3098
3099         if (copy_from_user(&prim, optval, sizeof(struct sctp_prim)))
3100                 return -EFAULT;
3101
3102         asoc = sctp_id2assoc(sk, prim.ssp_assoc_id);
3103         if (!asoc)
3104                 return -EINVAL;
3105
3106         if (!asoc->peer.primary_path)
3107                 return -ENOTCONN;
3108         
3109         asoc->peer.primary_path->ipaddr.v4.sin_port =
3110                 htons(asoc->peer.primary_path->ipaddr.v4.sin_port);
3111         memcpy(&prim.ssp_addr, &asoc->peer.primary_path->ipaddr,
3112                sizeof(union sctp_addr));
3113         asoc->peer.primary_path->ipaddr.v4.sin_port =
3114                 ntohs(asoc->peer.primary_path->ipaddr.v4.sin_port);
3115
3116         sctp_get_pf_specific(sk->sk_family)->addr_v4map(sp,
3117                         (union sctp_addr *)&prim.ssp_addr);
3118
3119         if (copy_to_user(optval, &prim, sizeof(struct sctp_prim)))
3120                 return -EFAULT;
3121
3122         return 0;
3123 }
3124
3125 /*
3126  *
3127  * 7.1.14 Set default send parameters (SCTP_DEFAULT_SEND_PARAM)
3128  *
3129  *   Applications that wish to use the sendto() system call may wish to
3130  *   specify a default set of parameters that would normally be supplied
3131  *   through the inclusion of ancillary data.  This socket option allows
3132  *   such an application to set the default sctp_sndrcvinfo structure.
3133
3134
3135  *   The application that wishes to use this socket option simply passes
3136  *   in to this call the sctp_sndrcvinfo structure defined in Section
3137  *   5.2.2) The input parameters accepted by this call include
3138  *   sinfo_stream, sinfo_flags, sinfo_ppid, sinfo_context,
3139  *   sinfo_timetolive.  The user must provide the sinfo_assoc_id field in
3140  *   to this call if the caller is using the UDP model.
3141  *
3142  *   For getsockopt, it get the default sctp_sndrcvinfo structure.
3143  */
3144 static int sctp_getsockopt_default_send_param(struct sock *sk,
3145                                         int len, char __user *optval,
3146                                         int __user *optlen)
3147 {
3148         struct sctp_sndrcvinfo info;
3149         struct sctp_association *asoc;
3150         struct sctp_opt *sp = sctp_sk(sk);
3151
3152         if (len != sizeof(struct sctp_sndrcvinfo))
3153                 return -EINVAL;
3154         if (copy_from_user(&info, optval, sizeof(struct sctp_sndrcvinfo)))
3155                 return -EFAULT;
3156
3157         asoc = sctp_id2assoc(sk, info.sinfo_assoc_id);
3158         if (!asoc && info.sinfo_assoc_id && sctp_style(sk, UDP))
3159                 return -EINVAL;
3160
3161         if (asoc) {
3162                 info.sinfo_stream = asoc->default_stream;
3163                 info.sinfo_flags = asoc->default_flags;
3164                 info.sinfo_ppid = asoc->default_ppid;
3165                 info.sinfo_context = asoc->default_context;
3166                 info.sinfo_timetolive = asoc->default_timetolive;
3167         } else {
3168                 info.sinfo_stream = sp->default_stream;
3169                 info.sinfo_flags = sp->default_flags;
3170                 info.sinfo_ppid = sp->default_ppid;
3171                 info.sinfo_context = sp->default_context;
3172                 info.sinfo_timetolive = sp->default_timetolive;
3173         }
3174
3175         if (copy_to_user(optval, &info, sizeof(struct sctp_sndrcvinfo)))
3176                 return -EFAULT;
3177
3178         return 0;
3179 }
3180
3181 /*
3182  *
3183  * 7.1.5 SCTP_NODELAY
3184  *
3185  * Turn on/off any Nagle-like algorithm.  This means that packets are
3186  * generally sent as soon as possible and no unnecessary delays are
3187  * introduced, at the cost of more packets in the network.  Expects an
3188  * integer boolean flag.
3189  */
3190
3191 static int sctp_getsockopt_nodelay(struct sock *sk, int len,
3192                                    char __user *optval, int __user *optlen)
3193 {
3194         int val;
3195
3196         if (len < sizeof(int))
3197                 return -EINVAL;
3198
3199         len = sizeof(int);
3200         val = (sctp_sk(sk)->nodelay == 1);
3201         if (put_user(len, optlen))
3202                 return -EFAULT;
3203         if (copy_to_user(optval, &val, len))
3204                 return -EFAULT;
3205         return 0;
3206 }
3207
3208 /*
3209  *
3210  * 7.1.1 SCTP_RTOINFO
3211  *
3212  * The protocol parameters used to initialize and bound retransmission
3213  * timeout (RTO) are tunable. sctp_rtoinfo structure is used to access
3214  * and modify these parameters.
3215  * All parameters are time values, in milliseconds.  A value of 0, when
3216  * modifying the parameters, indicates that the current value should not
3217  * be changed.
3218  *
3219  */
3220 static int sctp_getsockopt_rtoinfo(struct sock *sk, int len,
3221                                 char __user *optval,
3222                                 int __user *optlen) {
3223         struct sctp_rtoinfo rtoinfo;
3224         struct sctp_association *asoc;
3225
3226         if (len != sizeof (struct sctp_rtoinfo))
3227                 return -EINVAL;
3228
3229         if (copy_from_user(&rtoinfo, optval, sizeof (struct sctp_rtoinfo)))
3230                 return -EFAULT;
3231
3232         asoc = sctp_id2assoc(sk, rtoinfo.srto_assoc_id);
3233
3234         if (!asoc && rtoinfo.srto_assoc_id && sctp_style(sk, UDP))
3235                 return -EINVAL;
3236
3237         /* Values corresponding to the specific association. */
3238         if (asoc) {
3239                 rtoinfo.srto_initial = jiffies_to_msecs(asoc->rto_initial);
3240                 rtoinfo.srto_max = jiffies_to_msecs(asoc->rto_max);
3241                 rtoinfo.srto_min = jiffies_to_msecs(asoc->rto_min);
3242         } else {
3243                 /* Values corresponding to the endpoint. */
3244                 struct sctp_opt *sp = sctp_sk(sk);
3245
3246                 rtoinfo.srto_initial = sp->rtoinfo.srto_initial;
3247                 rtoinfo.srto_max = sp->rtoinfo.srto_max;
3248                 rtoinfo.srto_min = sp->rtoinfo.srto_min;
3249         }
3250
3251         if (put_user(len, optlen))
3252                 return -EFAULT;
3253
3254         if (copy_to_user(optval, &rtoinfo, len))
3255                 return -EFAULT;
3256
3257         return 0;
3258 }
3259
3260 /*
3261  *
3262  * 7.1.2 SCTP_ASSOCINFO
3263  *
3264  * This option is used to tune the the maximum retransmission attempts
3265  * of the association.
3266  * Returns an error if the new association retransmission value is
3267  * greater than the sum of the retransmission value  of the peer.
3268  * See [SCTP] for more information.
3269  *
3270  */
3271 static int sctp_getsockopt_associnfo(struct sock *sk, int len,
3272                                      char __user *optval,
3273                                      int __user *optlen)
3274 {
3275
3276         struct sctp_assocparams assocparams;
3277         struct sctp_association *asoc;
3278         struct list_head *pos;
3279         int cnt = 0;
3280
3281         if (len != sizeof (struct sctp_assocparams))
3282                 return -EINVAL;
3283
3284         if (copy_from_user(&assocparams, optval,
3285                         sizeof (struct sctp_assocparams)))
3286                 return -EFAULT;
3287
3288         asoc = sctp_id2assoc(sk, assocparams.sasoc_assoc_id);
3289
3290         if (!asoc && assocparams.sasoc_assoc_id && sctp_style(sk, UDP))
3291                 return -EINVAL;
3292
3293         /* Values correspoinding to the specific association */
3294         if (assocparams.sasoc_assoc_id != 0) {
3295                 assocparams.sasoc_asocmaxrxt = asoc->max_retrans;
3296                 assocparams.sasoc_peer_rwnd = asoc->peer.rwnd;
3297                 assocparams.sasoc_local_rwnd = asoc->a_rwnd;
3298                 assocparams.sasoc_cookie_life = (asoc->cookie_life.tv_sec
3299                                                 * 1000) +
3300                                                 (asoc->cookie_life.tv_usec
3301                                                 / 1000);
3302
3303                 list_for_each(pos, &asoc->peer.transport_addr_list) {
3304                         cnt ++;
3305                 }
3306
3307                 assocparams.sasoc_number_peer_destinations = cnt;
3308         } else {
3309                 /* Values corresponding to the endpoint */
3310                 struct sctp_opt *sp = sctp_sk(sk);
3311
3312                 assocparams.sasoc_asocmaxrxt = sp->assocparams.sasoc_asocmaxrxt;
3313                 assocparams.sasoc_peer_rwnd = sp->assocparams.sasoc_peer_rwnd;
3314                 assocparams.sasoc_local_rwnd = sp->assocparams.sasoc_local_rwnd;
3315                 assocparams.sasoc_cookie_life =
3316                                         sp->assocparams.sasoc_cookie_life;
3317                 assocparams.sasoc_number_peer_destinations =
3318                                         sp->assocparams.
3319                                         sasoc_number_peer_destinations;
3320         }
3321
3322         if (put_user(len, optlen))
3323                 return -EFAULT;
3324
3325         if (copy_to_user(optval, &assocparams, len))
3326                 return -EFAULT;
3327
3328         return 0;
3329 }
3330
3331 /*
3332  * 7.1.16 Set/clear IPv4 mapped addresses (SCTP_I_WANT_MAPPED_V4_ADDR)
3333  *
3334  * This socket option is a boolean flag which turns on or off mapped V4
3335  * addresses.  If this option is turned on and the socket is type
3336  * PF_INET6, then IPv4 addresses will be mapped to V6 representation.
3337  * If this option is turned off, then no mapping will be done of V4
3338  * addresses and a user will receive both PF_INET6 and PF_INET type
3339  * addresses on the socket.
3340  */
3341 static int sctp_getsockopt_mappedv4(struct sock *sk, int len,
3342                                     char __user *optval, int __user *optlen)
3343 {
3344         int val;
3345         struct sctp_opt *sp = sctp_sk(sk);
3346
3347         if (len < sizeof(int))
3348                 return -EINVAL;
3349
3350         len = sizeof(int);
3351         val = sp->v4mapped;
3352         if (put_user(len, optlen))
3353                 return -EFAULT;
3354         if (copy_to_user(optval, &val, len))
3355                 return -EFAULT;
3356
3357         return 0;
3358 }
3359
3360 /*
3361  * 7.1.17 Set the maximum fragrmentation size (SCTP_MAXSEG)
3362  *
3363  * This socket option specifies the maximum size to put in any outgoing
3364  * SCTP chunk.  If a message is larger than this size it will be
3365  * fragmented by SCTP into the specified size.  Note that the underlying
3366  * SCTP implementation may fragment into smaller sized chunks when the
3367  * PMTU of the underlying association is smaller than the value set by
3368  * the user.
3369  */
3370 static int sctp_getsockopt_maxseg(struct sock *sk, int len,
3371                                   char __user *optval, int __user *optlen)
3372 {
3373         int val;
3374
3375         if (len < sizeof(int))
3376                 return -EINVAL;
3377
3378         len = sizeof(int);
3379
3380         val = sctp_sk(sk)->user_frag;
3381         if (put_user(len, optlen))
3382                 return -EFAULT;
3383         if (copy_to_user(optval, &val, len))
3384                 return -EFAULT;
3385
3386         return 0;
3387 }
3388
3389 SCTP_STATIC int sctp_getsockopt(struct sock *sk, int level, int optname,
3390                                 char __user *optval, int __user *optlen)
3391 {
3392         int retval = 0;
3393         int len;
3394
3395         SCTP_DEBUG_PRINTK("sctp_getsockopt(sk: %p, ...)\n", sk);
3396
3397         /* I can hardly begin to describe how wrong this is.  This is
3398          * so broken as to be worse than useless.  The API draft
3399          * REALLY is NOT helpful here...  I am not convinced that the
3400          * semantics of getsockopt() with a level OTHER THAN SOL_SCTP
3401          * are at all well-founded.
3402          */
3403         if (level != SOL_SCTP) {
3404                 struct sctp_af *af = sctp_sk(sk)->pf->af;
3405
3406                 retval = af->getsockopt(sk, level, optname, optval, optlen);
3407                 return retval;
3408         }
3409
3410         if (get_user(len, optlen))
3411                 return -EFAULT;
3412
3413         sctp_lock_sock(sk);
3414
3415         switch (optname) {
3416         case SCTP_STATUS:
3417                 retval = sctp_getsockopt_sctp_status(sk, len, optval, optlen);
3418                 break;
3419         case SCTP_DISABLE_FRAGMENTS:
3420                 retval = sctp_getsockopt_disable_fragments(sk, len, optval,
3421                                                            optlen);
3422                 break;
3423         case SCTP_EVENTS:
3424                 retval = sctp_getsockopt_events(sk, len, optval, optlen);
3425                 break;
3426         case SCTP_AUTOCLOSE:
3427                 retval = sctp_getsockopt_autoclose(sk, len, optval, optlen);
3428                 break;
3429         case SCTP_SOCKOPT_PEELOFF:
3430                 retval = sctp_getsockopt_peeloff(sk, len, optval, optlen);
3431                 break;
3432         case SCTP_PEER_ADDR_PARAMS:
3433                 retval = sctp_getsockopt_peer_addr_params(sk, len, optval,
3434                                                           optlen);
3435                 break;
3436         case SCTP_INITMSG:
3437                 retval = sctp_getsockopt_initmsg(sk, len, optval, optlen);
3438                 break;
3439         case SCTP_GET_PEER_ADDRS_NUM:
3440                 retval = sctp_getsockopt_peer_addrs_num(sk, len, optval,
3441                                                         optlen);
3442                 break;
3443         case SCTP_GET_LOCAL_ADDRS_NUM:
3444                 retval = sctp_getsockopt_local_addrs_num(sk, len, optval,
3445                                                          optlen);
3446                 break;
3447         case SCTP_GET_PEER_ADDRS:
3448                 retval = sctp_getsockopt_peer_addrs(sk, len, optval,
3449                                                     optlen);
3450                 break;
3451         case SCTP_GET_LOCAL_ADDRS:
3452                 retval = sctp_getsockopt_local_addrs(sk, len, optval,
3453                                                      optlen);
3454                 break;
3455         case SCTP_DEFAULT_SEND_PARAM:
3456                 retval = sctp_getsockopt_default_send_param(sk, len,
3457                                                             optval, optlen);
3458                 break;
3459         case SCTP_PRIMARY_ADDR:
3460                 retval = sctp_getsockopt_primary_addr(sk, len, optval, optlen);
3461                 break;
3462         case SCTP_NODELAY:
3463                 retval = sctp_getsockopt_nodelay(sk, len, optval, optlen);
3464                 break;
3465         case SCTP_RTOINFO:
3466                 retval = sctp_getsockopt_rtoinfo(sk, len, optval, optlen);
3467                 break;
3468         case SCTP_ASSOCINFO:
3469                 retval = sctp_getsockopt_associnfo(sk, len, optval, optlen);
3470                 break;
3471         case SCTP_I_WANT_MAPPED_V4_ADDR:
3472                 retval = sctp_getsockopt_mappedv4(sk, len, optval, optlen);
3473                 break;
3474         case SCTP_MAXSEG:
3475                 retval = sctp_getsockopt_maxseg(sk, len, optval, optlen);
3476                 break;
3477         case SCTP_GET_PEER_ADDR_INFO:
3478                 retval = sctp_getsockopt_peer_addr_info(sk, len, optval,
3479                                                         optlen);
3480                 break;
3481         default:
3482                 retval = -ENOPROTOOPT;
3483                 break;
3484         };
3485
3486         sctp_release_sock(sk);
3487         return retval;
3488 }
3489
3490 static void sctp_hash(struct sock *sk)
3491 {
3492         /* STUB */
3493 }
3494
3495 static void sctp_unhash(struct sock *sk)
3496 {
3497         /* STUB */
3498 }
3499
3500 /* Check if port is acceptable.  Possibly find first available port.
3501  *
3502  * The port hash table (contained in the 'global' SCTP protocol storage
3503  * returned by struct sctp_protocol *sctp_get_protocol()). The hash
3504  * table is an array of 4096 lists (sctp_bind_hashbucket). Each
3505  * list (the list number is the port number hashed out, so as you
3506  * would expect from a hash function, all the ports in a given list have
3507  * such a number that hashes out to the same list number; you were
3508  * expecting that, right?); so each list has a set of ports, with a
3509  * link to the socket (struct sock) that uses it, the port number and
3510  * a fastreuse flag (FIXME: NPI ipg).
3511  */
3512 static struct sctp_bind_bucket *sctp_bucket_create(
3513         struct sctp_bind_hashbucket *head, unsigned short snum);
3514
3515 static long sctp_get_port_local(struct sock *sk, union sctp_addr *addr)
3516 {
3517         struct sctp_bind_hashbucket *head; /* hash list */
3518         struct sctp_bind_bucket *pp; /* hash list port iterator */
3519         unsigned short snum;
3520         int ret;
3521
3522         /* NOTE:  Remember to put this back to net order. */
3523         addr->v4.sin_port = ntohs(addr->v4.sin_port);
3524         snum = addr->v4.sin_port;
3525
3526         SCTP_DEBUG_PRINTK("sctp_get_port() begins, snum=%d\n", snum);
3527         sctp_local_bh_disable();
3528
3529         if (snum == 0) {
3530                 /* Search for an available port.
3531                  *
3532                  * 'sctp_port_rover' was the last port assigned, so
3533                  * we start to search from 'sctp_port_rover +
3534                  * 1'. What we do is first check if port 'rover' is
3535                  * already in the hash table; if not, we use that; if
3536                  * it is, we try next.
3537                  */
3538                 int low = sysctl_local_port_range[0];
3539                 int high = sysctl_local_port_range[1];
3540                 int remaining = (high - low) + 1;
3541                 int rover;
3542                 int index;
3543
3544                 sctp_spin_lock(&sctp_port_alloc_lock);
3545                 rover = sctp_port_rover;
3546                 do {
3547                         rover++;
3548                         if ((rover < low) || (rover > high))
3549                                 rover = low;
3550                         index = sctp_phashfn(rover);
3551                         head = &sctp_port_hashtable[index];
3552                         sctp_spin_lock(&head->lock);
3553                         for (pp = head->chain; pp; pp = pp->next)
3554                                 if (pp->port == rover)
3555                                         goto next;
3556                         break;
3557                 next:
3558                         sctp_spin_unlock(&head->lock);
3559                 } while (--remaining > 0);
3560                 sctp_port_rover = rover;
3561                 sctp_spin_unlock(&sctp_port_alloc_lock);
3562
3563                 /* Exhausted local port range during search? */
3564                 ret = 1;
3565                 if (remaining <= 0)
3566                         goto fail;
3567
3568                 /* OK, here is the one we will use.  HEAD (the port
3569                  * hash table list entry) is non-NULL and we hold it's
3570                  * mutex.
3571                  */
3572                 snum = rover;
3573         } else {
3574                 /* We are given an specific port number; we verify
3575                  * that it is not being used. If it is used, we will
3576                  * exahust the search in the hash list corresponding
3577                  * to the port number (snum) - we detect that with the
3578                  * port iterator, pp being NULL.
3579                  */
3580                 head = &sctp_port_hashtable[sctp_phashfn(snum)];
3581                 sctp_spin_lock(&head->lock);
3582                 for (pp = head->chain; pp; pp = pp->next) {
3583                         if (pp->port == snum)
3584                                 goto pp_found;
3585                 }
3586         }
3587         pp = NULL;
3588         goto pp_not_found;
3589 pp_found:
3590         if (!hlist_empty(&pp->owner)) {
3591                 /* We had a port hash table hit - there is an
3592                  * available port (pp != NULL) and it is being
3593                  * used by other socket (pp->owner not empty); that other
3594                  * socket is going to be sk2.
3595                  */
3596                 int reuse = sk->sk_reuse;
3597                 struct sock *sk2;
3598                 struct hlist_node *node;
3599
3600                 SCTP_DEBUG_PRINTK("sctp_get_port() found a possible match\n");
3601                 if (pp->fastreuse && sk->sk_reuse)
3602                         goto success;
3603
3604                 /* Run through the list of sockets bound to the port
3605                  * (pp->port) [via the pointers bind_next and
3606                  * bind_pprev in the struct sock *sk2 (pp->sk)]. On each one,
3607                  * we get the endpoint they describe and run through
3608                  * the endpoint's list of IP (v4 or v6) addresses,
3609                  * comparing each of the addresses with the address of
3610                  * the socket sk. If we find a match, then that means
3611                  * that this port/socket (sk) combination are already
3612                  * in an endpoint.
3613                  */
3614                 sk_for_each_bound(sk2, node, &pp->owner) {
3615                         struct sctp_endpoint *ep2;
3616                         ep2 = sctp_sk(sk2)->ep;
3617
3618                         if (reuse && sk2->sk_reuse)
3619                                 continue;
3620
3621                         if (sctp_bind_addr_match(&ep2->base.bind_addr, addr,
3622                                                  sctp_sk(sk))) {
3623                                 ret = (long)sk2;
3624                                 goto fail_unlock;
3625                         }
3626                 }
3627                 SCTP_DEBUG_PRINTK("sctp_get_port(): Found a match\n");
3628         }
3629 pp_not_found:
3630         /* If there was a hash table miss, create a new port.  */
3631         ret = 1;
3632         if (!pp && !(pp = sctp_bucket_create(head, snum)))
3633                 goto fail_unlock;
3634
3635         /* In either case (hit or miss), make sure fastreuse is 1 only
3636          * if sk->sk_reuse is too (that is, if the caller requested
3637          * SO_REUSEADDR on this socket -sk-).
3638          */
3639         if (hlist_empty(&pp->owner))
3640                 pp->fastreuse = sk->sk_reuse ? 1 : 0;
3641         else if (pp->fastreuse && !sk->sk_reuse)
3642                 pp->fastreuse = 0;
3643
3644         /* We are set, so fill up all the data in the hash table
3645          * entry, tie the socket list information with the rest of the
3646          * sockets FIXME: Blurry, NPI (ipg).
3647          */
3648 success:
3649         inet_sk(sk)->num = snum;
3650         if (!sctp_sk(sk)->bind_hash) {
3651                 sk_add_bind_node(sk, &pp->owner);
3652                 sctp_sk(sk)->bind_hash = pp;
3653         }
3654         ret = 0;
3655
3656 fail_unlock:
3657         sctp_spin_unlock(&head->lock);
3658
3659 fail:
3660         sctp_local_bh_enable();
3661         addr->v4.sin_port = htons(addr->v4.sin_port);
3662         return ret;
3663 }
3664
3665 /* Assign a 'snum' port to the socket.  If snum == 0, an ephemeral
3666  * port is requested.
3667  */
3668 static int sctp_get_port(struct sock *sk, unsigned short snum)
3669 {
3670         long ret;
3671         union sctp_addr addr;
3672         struct sctp_af *af = sctp_sk(sk)->pf->af;
3673
3674         /* Set up a dummy address struct from the sk. */
3675         af->from_sk(&addr, sk);
3676         addr.v4.sin_port = htons(snum);
3677
3678         /* Note: sk->sk_num gets filled in if ephemeral port request. */
3679         ret = sctp_get_port_local(sk, &addr);
3680
3681         return (ret ? 1 : 0);
3682 }
3683
3684 /*
3685  * 3.1.3 listen() - UDP Style Syntax
3686  *
3687  *   By default, new associations are not accepted for UDP style sockets.
3688  *   An application uses listen() to mark a socket as being able to
3689  *   accept new associations.
3690  */
3691 SCTP_STATIC int sctp_seqpacket_listen(struct sock *sk, int backlog)
3692 {
3693         struct sctp_opt *sp = sctp_sk(sk);
3694         struct sctp_endpoint *ep = sp->ep;
3695
3696         /* Only UDP style sockets that are not peeled off are allowed to
3697          * listen().
3698          */
3699         if (!sctp_style(sk, UDP))
3700                 return -EINVAL;
3701
3702         /* If backlog is zero, disable listening. */
3703         if (!backlog) {
3704                 if (sctp_sstate(sk, CLOSED))
3705                         return 0;
3706                 
3707                 sctp_unhash_endpoint(ep);
3708                 sk->sk_state = SCTP_SS_CLOSED;
3709         }
3710
3711         /* Return if we are already listening. */
3712         if (sctp_sstate(sk, LISTENING))
3713                 return 0;
3714                 
3715         /*
3716          * If a bind() or sctp_bindx() is not called prior to a listen()
3717          * call that allows new associations to be accepted, the system
3718          * picks an ephemeral port and will choose an address set equivalent
3719          * to binding with a wildcard address.
3720          *
3721          * This is not currently spelled out in the SCTP sockets
3722          * extensions draft, but follows the practice as seen in TCP
3723          * sockets.
3724          */
3725         if (!ep->base.bind_addr.port) {
3726                 if (sctp_autobind(sk))
3727                         return -EAGAIN;
3728         }
3729         sk->sk_state = SCTP_SS_LISTENING;
3730         sctp_hash_endpoint(ep);
3731         return 0;
3732 }
3733
3734 /*
3735  * 4.1.3 listen() - TCP Style Syntax
3736  *
3737  *   Applications uses listen() to ready the SCTP endpoint for accepting
3738  *   inbound associations.
3739  */
3740 SCTP_STATIC int sctp_stream_listen(struct sock *sk, int backlog)
3741 {
3742         struct sctp_opt *sp = sctp_sk(sk);
3743         struct sctp_endpoint *ep = sp->ep;
3744
3745         /* If backlog is zero, disable listening. */
3746         if (!backlog) {
3747                 if (sctp_sstate(sk, CLOSED))
3748                         return 0;
3749                 
3750                 sctp_unhash_endpoint(ep);
3751                 sk->sk_state = SCTP_SS_CLOSED;
3752         }
3753
3754         if (sctp_sstate(sk, LISTENING))
3755                 return 0;
3756
3757         /*
3758          * If a bind() or sctp_bindx() is not called prior to a listen()
3759          * call that allows new associations to be accepted, the system
3760          * picks an ephemeral port and will choose an address set equivalent
3761          * to binding with a wildcard address.
3762          *
3763          * This is not currently spelled out in the SCTP sockets
3764          * extensions draft, but follows the practice as seen in TCP
3765          * sockets.
3766          */
3767         if (!ep->base.bind_addr.port) {
3768                 if (sctp_autobind(sk))
3769                         return -EAGAIN;
3770         }
3771         sk->sk_state = SCTP_SS_LISTENING;
3772         sk->sk_max_ack_backlog = backlog;
3773         sctp_hash_endpoint(ep);
3774         return 0;
3775 }
3776
3777 /*
3778  *  Move a socket to LISTENING state.
3779  */
3780 int sctp_inet_listen(struct socket *sock, int backlog)
3781 {
3782         struct sock *sk = sock->sk;
3783         struct crypto_tfm *tfm=NULL;
3784         int err = -EINVAL;
3785
3786         if (unlikely(backlog < 0))
3787                 goto out;
3788
3789         sctp_lock_sock(sk);
3790
3791         if (sock->state != SS_UNCONNECTED)
3792                 goto out;
3793
3794         /* Allocate HMAC for generating cookie. */
3795         if (sctp_hmac_alg) {
3796                 tfm = sctp_crypto_alloc_tfm(sctp_hmac_alg, 0);
3797                 if (!tfm) {
3798                         err = -ENOSYS;
3799                         goto out;
3800                 }
3801         }
3802
3803         switch (sock->type) {
3804         case SOCK_SEQPACKET:
3805                 err = sctp_seqpacket_listen(sk, backlog);
3806                 break;
3807         case SOCK_STREAM:
3808                 err = sctp_stream_listen(sk, backlog);
3809                 break;
3810         default:
3811                 break;
3812         };
3813         if (err)
3814                 goto cleanup;
3815
3816         /* Store away the transform reference. */
3817         sctp_sk(sk)->hmac = tfm;
3818 out:
3819         sctp_release_sock(sk);
3820         return err;
3821 cleanup:
3822         if (tfm)
3823                 sctp_crypto_free_tfm(tfm);
3824         goto out;
3825 }
3826
3827 /*
3828  * This function is done by modeling the current datagram_poll() and the
3829  * tcp_poll().  Note that, based on these implementations, we don't
3830  * lock the socket in this function, even though it seems that,
3831  * ideally, locking or some other mechanisms can be used to ensure
3832  * the integrity of the counters (sndbuf and wmem_queued) used
3833  * in this place.  We assume that we don't need locks either until proven
3834  * otherwise.
3835  *
3836  * Another thing to note is that we include the Async I/O support
3837  * here, again, by modeling the current TCP/UDP code.  We don't have
3838  * a good way to test with it yet.
3839  */
3840 unsigned int sctp_poll(struct file *file, struct socket *sock, poll_table *wait)
3841 {
3842         struct sock *sk = sock->sk;
3843         struct sctp_opt *sp = sctp_sk(sk);
3844         unsigned int mask;
3845
3846         poll_wait(file, sk->sk_sleep, wait);
3847
3848         /* A TCP-style listening socket becomes readable when the accept queue
3849          * is not empty.
3850          */
3851         if (sctp_style(sk, TCP) && sctp_sstate(sk, LISTENING))
3852                 return (!list_empty(&sp->ep->asocs)) ?
3853                         (POLLIN | POLLRDNORM) : 0;
3854
3855         mask = 0;
3856
3857         /* Is there any exceptional events?  */
3858         if (sk->sk_err || !skb_queue_empty(&sk->sk_error_queue))
3859                 mask |= POLLERR;
3860         if (sk->sk_shutdown == SHUTDOWN_MASK)
3861                 mask |= POLLHUP;
3862
3863         /* Is it readable?  Reconsider this code with TCP-style support.  */
3864         if (!skb_queue_empty(&sk->sk_receive_queue) ||
3865             (sk->sk_shutdown & RCV_SHUTDOWN))
3866                 mask |= POLLIN | POLLRDNORM;
3867
3868         /* The association is either gone or not ready.  */
3869         if (!sctp_style(sk, UDP) && sctp_sstate(sk, CLOSED))
3870                 return mask;
3871
3872         /* Is it writable?  */
3873         if (sctp_writeable(sk)) {
3874                 mask |= POLLOUT | POLLWRNORM;
3875         } else {
3876                 set_bit(SOCK_ASYNC_NOSPACE, &sk->sk_socket->flags);
3877                 /*
3878                  * Since the socket is not locked, the buffer
3879                  * might be made available after the writeable check and
3880                  * before the bit is set.  This could cause a lost I/O
3881                  * signal.  tcp_poll() has a race breaker for this race
3882                  * condition.  Based on their implementation, we put
3883                  * in the following code to cover it as well.
3884                  */
3885                 if (sctp_writeable(sk))
3886                         mask |= POLLOUT | POLLWRNORM;
3887         }
3888         return mask;
3889 }
3890
3891 /********************************************************************
3892  * 2nd Level Abstractions
3893  ********************************************************************/
3894
3895 static struct sctp_bind_bucket *sctp_bucket_create(
3896         struct sctp_bind_hashbucket *head, unsigned short snum)
3897 {
3898         struct sctp_bind_bucket *pp;
3899
3900         pp = kmem_cache_alloc(sctp_bucket_cachep, SLAB_ATOMIC);
3901         SCTP_DBG_OBJCNT_INC(bind_bucket);
3902         if (pp) {
3903                 pp->port = snum;
3904                 pp->fastreuse = 0;
3905                 INIT_HLIST_HEAD(&pp->owner);
3906                 if ((pp->next = head->chain) != NULL)
3907                         pp->next->pprev = &pp->next;
3908                 head->chain = pp;
3909                 pp->pprev = &head->chain;
3910         }
3911         return pp;
3912 }
3913
3914 /* Caller must hold hashbucket lock for this tb with local BH disabled */
3915 static void sctp_bucket_destroy(struct sctp_bind_bucket *pp)
3916 {
3917         if (hlist_empty(&pp->owner)) {
3918                 if (pp->next)
3919                         pp->next->pprev = pp->pprev;
3920                 *(pp->pprev) = pp->next;
3921                 kmem_cache_free(sctp_bucket_cachep, pp);
3922                 SCTP_DBG_OBJCNT_DEC(bind_bucket);
3923         }
3924 }
3925
3926 /* Release this socket's reference to a local port.  */
3927 static inline void __sctp_put_port(struct sock *sk)
3928 {
3929         struct sctp_bind_hashbucket *head =
3930                 &sctp_port_hashtable[sctp_phashfn(inet_sk(sk)->num)];
3931         struct sctp_bind_bucket *pp;
3932
3933         sctp_spin_lock(&head->lock);
3934         pp = sctp_sk(sk)->bind_hash;
3935         __sk_del_bind_node(sk);
3936         sctp_sk(sk)->bind_hash = NULL;
3937         inet_sk(sk)->num = 0;
3938         sctp_bucket_destroy(pp);
3939         sctp_spin_unlock(&head->lock);
3940 }
3941
3942 void sctp_put_port(struct sock *sk)
3943 {
3944         sctp_local_bh_disable();
3945         __sctp_put_port(sk);
3946         sctp_local_bh_enable();
3947 }
3948
3949 /*
3950  * The system picks an ephemeral port and choose an address set equivalent
3951  * to binding with a wildcard address.
3952  * One of those addresses will be the primary address for the association.
3953  * This automatically enables the multihoming capability of SCTP.
3954  */
3955 static int sctp_autobind(struct sock *sk)
3956 {
3957         union sctp_addr autoaddr;
3958         struct sctp_af *af;
3959         unsigned short port;
3960
3961         /* Initialize a local sockaddr structure to INADDR_ANY. */
3962         af = sctp_sk(sk)->pf->af;
3963
3964         port = htons(inet_sk(sk)->num);
3965         af->inaddr_any(&autoaddr, port);
3966
3967         return sctp_do_bind(sk, &autoaddr, af->sockaddr_len);
3968 }
3969
3970 /* Parse out IPPROTO_SCTP CMSG headers.  Perform only minimal validation.
3971  *
3972  * From RFC 2292
3973  * 4.2 The cmsghdr Structure *
3974  *
3975  * When ancillary data is sent or received, any number of ancillary data
3976  * objects can be specified by the msg_control and msg_controllen members of
3977  * the msghdr structure, because each object is preceded by
3978  * a cmsghdr structure defining the object's length (the cmsg_len member).
3979  * Historically Berkeley-derived implementations have passed only one object
3980  * at a time, but this API allows multiple objects to be
3981  * passed in a single call to sendmsg() or recvmsg(). The following example
3982  * shows two ancillary data objects in a control buffer.
3983  *
3984  *   |<--------------------------- msg_controllen -------------------------->|
3985  *   |                                                                       |
3986  *
3987  *   |<----- ancillary data object ----->|<----- ancillary data object ----->|
3988  *
3989  *   |<---------- CMSG_SPACE() --------->|<---------- CMSG_SPACE() --------->|
3990  *   |                                   |                                   |
3991  *
3992  *   |<---------- cmsg_len ---------->|  |<--------- cmsg_len ----------->|  |
3993  *
3994  *   |<--------- CMSG_LEN() --------->|  |<-------- CMSG_LEN() ---------->|  |
3995  *   |                                |  |                                |  |
3996  *
3997  *   +-----+-----+-----+--+-----------+--+-----+-----+-----+--+-----------+--+
3998  *   |cmsg_|cmsg_|cmsg_|XX|           |XX|cmsg_|cmsg_|cmsg_|XX|           |XX|
3999  *
4000  *   |len  |level|type |XX|cmsg_data[]|XX|len  |level|type |XX|cmsg_data[]|XX|
4001  *
4002  *   +-----+-----+-----+--+-----------+--+-----+-----+-----+--+-----------+--+
4003  *    ^
4004  *    |
4005  *
4006  * msg_control
4007  * points here
4008  */
4009 SCTP_STATIC int sctp_msghdr_parse(const struct msghdr *msg,
4010                                   sctp_cmsgs_t *cmsgs)
4011 {
4012         struct cmsghdr *cmsg;
4013
4014         for (cmsg = CMSG_FIRSTHDR(msg);
4015              cmsg != NULL;
4016              cmsg = CMSG_NXTHDR((struct msghdr*)msg, cmsg)) {
4017                 /* Check for minimum length.  The SCM code has this check.  */
4018                 if (cmsg->cmsg_len < sizeof(struct cmsghdr) ||
4019                     (unsigned long)(((char*)cmsg - (char*)msg->msg_control)
4020                                     + cmsg->cmsg_len) > msg->msg_controllen) {
4021                         return -EINVAL;
4022                 }
4023
4024                 /* Should we parse this header or ignore?  */
4025                 if (cmsg->cmsg_level != IPPROTO_SCTP)
4026                         continue;
4027
4028                 /* Strictly check lengths following example in SCM code.  */
4029                 switch (cmsg->cmsg_type) {
4030                 case SCTP_INIT:
4031                         /* SCTP Socket API Extension
4032                          * 5.2.1 SCTP Initiation Structure (SCTP_INIT)
4033                          *
4034                          * This cmsghdr structure provides information for
4035                          * initializing new SCTP associations with sendmsg().
4036                          * The SCTP_INITMSG socket option uses this same data
4037                          * structure.  This structure is not used for
4038                          * recvmsg().
4039                          *
4040                          * cmsg_level    cmsg_type      cmsg_data[]
4041                          * ------------  ------------   ----------------------
4042                          * IPPROTO_SCTP  SCTP_INIT      struct sctp_initmsg
4043                          */
4044                         if (cmsg->cmsg_len !=
4045                             CMSG_LEN(sizeof(struct sctp_initmsg)))
4046                                 return -EINVAL;
4047                         cmsgs->init = (struct sctp_initmsg *)CMSG_DATA(cmsg);
4048                         break;
4049
4050                 case SCTP_SNDRCV:
4051                         /* SCTP Socket API Extension
4052                          * 5.2.2 SCTP Header Information Structure(SCTP_SNDRCV)
4053                          *
4054                          * This cmsghdr structure specifies SCTP options for
4055                          * sendmsg() and describes SCTP header information
4056                          * about a received message through recvmsg().
4057                          *
4058                          * cmsg_level    cmsg_type      cmsg_data[]
4059                          * ------------  ------------   ----------------------
4060                          * IPPROTO_SCTP  SCTP_SNDRCV    struct sctp_sndrcvinfo
4061                          */
4062                         if (cmsg->cmsg_len !=
4063                             CMSG_LEN(sizeof(struct sctp_sndrcvinfo)))
4064                                 return -EINVAL;
4065
4066                         cmsgs->info =
4067                                 (struct sctp_sndrcvinfo *)CMSG_DATA(cmsg);
4068
4069                         /* Minimally, validate the sinfo_flags. */
4070                         if (cmsgs->info->sinfo_flags &
4071                             ~(MSG_UNORDERED | MSG_ADDR_OVER |
4072                               MSG_ABORT | MSG_EOF))
4073                                 return -EINVAL;
4074                         break;
4075
4076                 default:
4077                         return -EINVAL;
4078                 };
4079         }
4080         return 0;
4081 }
4082
4083 /*
4084  * Wait for a packet..
4085  * Note: This function is the same function as in core/datagram.c
4086  * with a few modifications to make lksctp work.
4087  */
4088 static int sctp_wait_for_packet(struct sock * sk, int *err, long *timeo_p)
4089 {
4090         int error;
4091         DEFINE_WAIT(wait);
4092
4093         prepare_to_wait_exclusive(sk->sk_sleep, &wait, TASK_INTERRUPTIBLE);
4094
4095         /* Socket errors? */
4096         error = sock_error(sk);
4097         if (error)
4098                 goto out;
4099
4100         if (!skb_queue_empty(&sk->sk_receive_queue))
4101                 goto ready;
4102
4103         /* Socket shut down?  */
4104         if (sk->sk_shutdown & RCV_SHUTDOWN)
4105                 goto out;
4106
4107         /* Sequenced packets can come disconnected.  If so we report the
4108          * problem.
4109          */
4110         error = -ENOTCONN;
4111
4112         /* Is there a good reason to think that we may receive some data?  */
4113         if (list_empty(&sctp_sk(sk)->ep->asocs) && !sctp_sstate(sk, LISTENING))
4114                 goto out;
4115
4116         /* Handle signals.  */
4117         if (signal_pending(current))
4118                 goto interrupted;
4119
4120         /* Let another process have a go.  Since we are going to sleep
4121          * anyway.  Note: This may cause odd behaviors if the message
4122          * does not fit in the user's buffer, but this seems to be the
4123          * only way to honor MSG_DONTWAIT realistically.
4124          */
4125         sctp_release_sock(sk);
4126         *timeo_p = schedule_timeout(*timeo_p);
4127         sctp_lock_sock(sk);
4128
4129 ready:
4130         finish_wait(sk->sk_sleep, &wait);
4131         return 0;
4132
4133 interrupted:
4134         error = sock_intr_errno(*timeo_p);
4135
4136 out:
4137         finish_wait(sk->sk_sleep, &wait);
4138         *err = error;
4139         return error;
4140 }
4141
4142 /* Receive a datagram.
4143  * Note: This is pretty much the same routine as in core/datagram.c
4144  * with a few changes to make lksctp work.
4145  */
4146 static struct sk_buff *sctp_skb_recv_datagram(struct sock *sk, int flags,
4147                                               int noblock, int *err)
4148 {
4149         int error;
4150         struct sk_buff *skb;
4151         long timeo;
4152
4153         /* Caller is allowed not to check sk->sk_err before calling.  */
4154         error = sock_error(sk);
4155         if (error)
4156                 goto no_packet;
4157
4158         timeo = sock_rcvtimeo(sk, noblock);
4159
4160         SCTP_DEBUG_PRINTK("Timeout: timeo: %ld, MAX: %ld.\n",
4161                           timeo, MAX_SCHEDULE_TIMEOUT);
4162
4163         do {
4164                 /* Again only user level code calls this function,
4165                  * so nothing interrupt level
4166                  * will suddenly eat the receive_queue.
4167                  *
4168                  *  Look at current nfs client by the way...
4169                  *  However, this function was corrent in any case. 8)
4170                  */
4171                 if (flags & MSG_PEEK) {
4172                         unsigned long cpu_flags;
4173
4174                         sctp_spin_lock_irqsave(&sk->sk_receive_queue.lock,
4175                                                cpu_flags);
4176                         skb = skb_peek(&sk->sk_receive_queue);
4177                         if (skb)
4178                                 atomic_inc(&skb->users);
4179                         sctp_spin_unlock_irqrestore(&sk->sk_receive_queue.lock,
4180                                                     cpu_flags);
4181                 } else {
4182                         skb = skb_dequeue(&sk->sk_receive_queue);
4183                 }
4184
4185                 if (skb)
4186                         return skb;
4187
4188                 if (sk->sk_shutdown & RCV_SHUTDOWN)
4189                         break;
4190
4191                 /* User doesn't want to wait.  */
4192                 error = -EAGAIN;
4193                 if (!timeo)
4194                         goto no_packet;
4195         } while (sctp_wait_for_packet(sk, err, &timeo) == 0);
4196
4197         return NULL;
4198
4199 no_packet:
4200         *err = error;
4201         return NULL;
4202 }
4203
4204 /* If sndbuf has changed, wake up per association sndbuf waiters.  */
4205 static void __sctp_write_space(struct sctp_association *asoc)
4206 {
4207         struct sock *sk = asoc->base.sk;
4208         struct socket *sock = sk->sk_socket;
4209
4210         if ((sctp_wspace(asoc) > 0) && sock) {
4211                 if (waitqueue_active(&asoc->wait))
4212                         wake_up_interruptible(&asoc->wait);
4213
4214                 if (sctp_writeable(sk)) {
4215                         if (sk->sk_sleep && waitqueue_active(sk->sk_sleep))
4216                                 wake_up_interruptible(sk->sk_sleep);
4217
4218                         /* Note that we try to include the Async I/O support
4219                          * here by modeling from the current TCP/UDP code.
4220                          * We have not tested with it yet.
4221                          */
4222                         if (sock->fasync_list &&
4223                             !(sk->sk_shutdown & SEND_SHUTDOWN))
4224                                 sock_wake_async(sock, 2, POLL_OUT);
4225                 }
4226         }
4227 }
4228
4229 /* Do accounting for the sndbuf space.
4230  * Decrement the used sndbuf space of the corresponding association by the
4231  * data size which was just transmitted(freed).
4232  */
4233 static void sctp_wfree(struct sk_buff *skb)
4234 {
4235         struct sctp_association *asoc;
4236         struct sctp_chunk *chunk;
4237         struct sock *sk;
4238
4239         /* Get the saved chunk pointer.  */
4240         chunk = *((struct sctp_chunk **)(skb->cb));
4241         asoc = chunk->asoc;
4242         sk = asoc->base.sk;
4243         asoc->sndbuf_used -= SCTP_DATA_SNDSIZE(chunk);
4244         sk->sk_wmem_queued -= SCTP_DATA_SNDSIZE(chunk);
4245         __sctp_write_space(asoc);
4246
4247         sctp_association_put(asoc);
4248 }
4249
4250 /* Helper function to wait for space in the sndbuf.  */
4251 static int sctp_wait_for_sndbuf(struct sctp_association *asoc, long *timeo_p,
4252                                 size_t msg_len)
4253 {
4254         struct sock *sk = asoc->base.sk;
4255         int err = 0;
4256         long current_timeo = *timeo_p;
4257         DEFINE_WAIT(wait);
4258
4259         SCTP_DEBUG_PRINTK("wait_for_sndbuf: asoc=%p, timeo=%ld, msg_len=%zu\n",
4260                           asoc, (long)(*timeo_p), msg_len);
4261
4262         /* Increment the association's refcnt.  */
4263         sctp_association_hold(asoc);
4264
4265         /* Wait on the association specific sndbuf space. */
4266         for (;;) {
4267                 prepare_to_wait_exclusive(&asoc->wait, &wait,
4268                                           TASK_INTERRUPTIBLE);
4269                 if (!*timeo_p)
4270                         goto do_nonblock;
4271                 if (sk->sk_err || asoc->state >= SCTP_STATE_SHUTDOWN_PENDING ||
4272                     asoc->base.dead)
4273                         goto do_error;
4274                 if (signal_pending(current))
4275                         goto do_interrupted;
4276                 if (msg_len <= sctp_wspace(asoc))
4277                         break;
4278
4279                 /* Let another process have a go.  Since we are going
4280                  * to sleep anyway.
4281                  */
4282                 sctp_release_sock(sk);
4283                 current_timeo = schedule_timeout(current_timeo);
4284                 sctp_lock_sock(sk);
4285
4286                 *timeo_p = current_timeo;
4287         }
4288
4289 out:
4290         finish_wait(&asoc->wait, &wait);
4291
4292         /* Release the association's refcnt.  */
4293         sctp_association_put(asoc);
4294
4295         return err;
4296
4297 do_error:
4298         err = -EPIPE;
4299         goto out;
4300
4301 do_interrupted:
4302         err = sock_intr_errno(*timeo_p);
4303         goto out;
4304
4305 do_nonblock:
4306         err = -EAGAIN;
4307         goto out;
4308 }
4309
4310 /* If socket sndbuf has changed, wake up all per association waiters.  */
4311 void sctp_write_space(struct sock *sk)
4312 {
4313         struct sctp_association *asoc;
4314         struct list_head *pos;
4315
4316         /* Wake up the tasks in each wait queue.  */
4317         list_for_each(pos, &((sctp_sk(sk))->ep->asocs)) {
4318                 asoc = list_entry(pos, struct sctp_association, asocs);
4319                 __sctp_write_space(asoc);
4320         }
4321 }
4322
4323 /* Is there any sndbuf space available on the socket?
4324  *
4325  * Note that wmem_queued is the sum of the send buffers on all of the
4326  * associations on the same socket.  For a UDP-style socket with
4327  * multiple associations, it is possible for it to be "unwriteable"
4328  * prematurely.  I assume that this is acceptable because
4329  * a premature "unwriteable" is better than an accidental "writeable" which
4330  * would cause an unwanted block under certain circumstances.  For the 1-1
4331  * UDP-style sockets or TCP-style sockets, this code should work.
4332  *  - Daisy
4333  */
4334 static int sctp_writeable(struct sock *sk)
4335 {
4336         int amt = 0;
4337
4338         amt = sk->sk_sndbuf - sk->sk_wmem_queued;
4339         if (amt < 0)
4340                 amt = 0;
4341         return amt;
4342 }
4343
4344 /* Wait for an association to go into ESTABLISHED state. If timeout is 0,
4345  * returns immediately with EINPROGRESS.
4346  */
4347 static int sctp_wait_for_connect(struct sctp_association *asoc, long *timeo_p)
4348 {
4349         struct sock *sk = asoc->base.sk;
4350         int err = 0;
4351         long current_timeo = *timeo_p;
4352         DEFINE_WAIT(wait);
4353
4354         SCTP_DEBUG_PRINTK("%s: asoc=%p, timeo=%ld\n", __FUNCTION__, asoc,
4355                           (long)(*timeo_p));
4356
4357         /* Increment the association's refcnt.  */
4358         sctp_association_hold(asoc);
4359
4360         for (;;) {
4361                 prepare_to_wait_exclusive(&asoc->wait, &wait,
4362                                           TASK_INTERRUPTIBLE);
4363                 if (!*timeo_p)
4364                         goto do_nonblock;
4365                 if (sk->sk_shutdown & RCV_SHUTDOWN)
4366                         break;
4367                 if (sk->sk_err || asoc->state >= SCTP_STATE_SHUTDOWN_PENDING ||
4368                     asoc->base.dead)
4369                         goto do_error;
4370                 if (signal_pending(current))
4371                         goto do_interrupted;
4372
4373                 if (sctp_state(asoc, ESTABLISHED))
4374                         break;
4375
4376                 /* Let another process have a go.  Since we are going
4377                  * to sleep anyway.
4378                  */
4379                 sctp_release_sock(sk);
4380                 current_timeo = schedule_timeout(current_timeo);
4381                 sctp_lock_sock(sk);
4382
4383                 *timeo_p = current_timeo;
4384         }
4385
4386 out:
4387         finish_wait(&asoc->wait, &wait);
4388
4389         /* Release the association's refcnt.  */
4390         sctp_association_put(asoc);
4391
4392         return err;
4393
4394 do_error:
4395         if (asoc->counters[SCTP_COUNTER_INIT_ERROR] + 1 >=
4396                                                 asoc->max_init_attempts)
4397                 err = -ETIMEDOUT;
4398         else
4399                 err = -ECONNREFUSED;
4400         goto out;
4401
4402 do_interrupted:
4403         err = sock_intr_errno(*timeo_p);
4404         goto out;
4405
4406 do_nonblock:
4407         err = -EINPROGRESS;
4408         goto out;
4409 }
4410
4411 static int sctp_wait_for_accept(struct sock *sk, long timeo)
4412 {
4413         struct sctp_endpoint *ep;
4414         int err = 0;
4415         DEFINE_WAIT(wait);
4416
4417         ep = sctp_sk(sk)->ep;
4418
4419
4420         for (;;) {
4421                 prepare_to_wait_exclusive(sk->sk_sleep, &wait,
4422                                           TASK_INTERRUPTIBLE);
4423
4424                 if (list_empty(&ep->asocs)) {
4425                         sctp_release_sock(sk);
4426                         timeo = schedule_timeout(timeo);
4427                         sctp_lock_sock(sk);
4428                 }
4429
4430                 err = -EINVAL;
4431                 if (!sctp_sstate(sk, LISTENING))
4432                         break;
4433
4434                 err = 0;
4435                 if (!list_empty(&ep->asocs))
4436                         break;
4437
4438                 err = sock_intr_errno(timeo);
4439                 if (signal_pending(current))
4440                         break;
4441
4442                 err = -EAGAIN;
4443                 if (!timeo)
4444                         break;
4445         }
4446
4447         finish_wait(sk->sk_sleep, &wait);
4448
4449         return err;
4450 }
4451
4452 void sctp_wait_for_close(struct sock *sk, long timeout)
4453 {
4454         DEFINE_WAIT(wait);
4455
4456         do {
4457                 prepare_to_wait(sk->sk_sleep, &wait, TASK_INTERRUPTIBLE);
4458                 if (list_empty(&sctp_sk(sk)->ep->asocs))
4459                         break;
4460                 sctp_release_sock(sk);
4461                 timeout = schedule_timeout(timeout);
4462                 sctp_lock_sock(sk);
4463         } while (!signal_pending(current) && timeout);
4464
4465         finish_wait(sk->sk_sleep, &wait);
4466 }
4467
4468 /* Populate the fields of the newsk from the oldsk and migrate the assoc
4469  * and its messages to the newsk.
4470  */
4471 static void sctp_sock_migrate(struct sock *oldsk, struct sock *newsk,
4472                               struct sctp_association *assoc,
4473                               sctp_socket_type_t type)
4474 {
4475         struct sctp_opt *oldsp = sctp_sk(oldsk);
4476         struct sctp_opt *newsp = sctp_sk(newsk);
4477         struct sctp_bind_bucket *pp; /* hash list port iterator */
4478         struct sctp_endpoint *newep = newsp->ep;
4479         struct sk_buff *skb, *tmp;
4480         struct sctp_ulpevent *event;
4481
4482         /* Migrate socket buffer sizes and all the socket level options to the
4483          * new socket.
4484          */
4485         newsk->sk_sndbuf = oldsk->sk_sndbuf;
4486         newsk->sk_rcvbuf = oldsk->sk_rcvbuf;
4487         /* Brute force copy old sctp opt. */
4488         memcpy(newsp, oldsp, sizeof(struct sctp_opt));
4489
4490         /* Restore the ep value that was overwritten with the above structure
4491          * copy.
4492          */
4493         newsp->ep = newep;
4494         newsp->hmac = NULL;
4495
4496         /* Hook this new socket in to the bind_hash list. */
4497         pp = sctp_sk(oldsk)->bind_hash;
4498         sk_add_bind_node(newsk, &pp->owner);
4499         sctp_sk(newsk)->bind_hash = pp;
4500         inet_sk(newsk)->num = inet_sk(oldsk)->num;
4501
4502         /* Move any messages in the old socket's receive queue that are for the
4503          * peeled off association to the new socket's receive queue.
4504          */
4505         sctp_skb_for_each(skb, &oldsk->sk_receive_queue, tmp) {
4506                 event = sctp_skb2event(skb);
4507                 if (event->asoc == assoc) {
4508                         __skb_unlink(skb, skb->list);
4509                         __skb_queue_tail(&newsk->sk_receive_queue, skb);
4510                 }
4511         }
4512
4513         /* Clean up any messages pending delivery due to partial
4514          * delivery.   Three cases:
4515          * 1) No partial deliver;  no work.
4516          * 2) Peeling off partial delivery; keep pd_lobby in new pd_lobby.
4517          * 3) Peeling off non-partial delivery; move pd_lobby to recieve_queue.
4518          */
4519         skb_queue_head_init(&newsp->pd_lobby);
4520         sctp_sk(newsk)->pd_mode = assoc->ulpq.pd_mode;
4521
4522         if (sctp_sk(oldsk)->pd_mode) {
4523                 struct sk_buff_head *queue;
4524
4525                 /* Decide which queue to move pd_lobby skbs to. */
4526                 if (assoc->ulpq.pd_mode) {
4527                         queue = &newsp->pd_lobby;
4528                 } else
4529                         queue = &newsk->sk_receive_queue;
4530
4531                 /* Walk through the pd_lobby, looking for skbs that
4532                  * need moved to the new socket.
4533                  */
4534                 sctp_skb_for_each(skb, &oldsp->pd_lobby, tmp) {
4535                         event = sctp_skb2event(skb);
4536                         if (event->asoc == assoc) {
4537                                 __skb_unlink(skb, skb->list);
4538                                 __skb_queue_tail(queue, skb);
4539                         }
4540                 }
4541
4542                 /* Clear up any skbs waiting for the partial
4543                  * delivery to finish.
4544                  */
4545                 if (assoc->ulpq.pd_mode)
4546                         sctp_clear_pd(oldsk);
4547
4548         }
4549
4550         /* Set the type of socket to indicate that it is peeled off from the
4551          * original UDP-style socket or created with the accept() call on a
4552          * TCP-style socket..
4553          */
4554         newsp->type = type;
4555
4556         /* Migrate the association to the new socket. */
4557         sctp_assoc_migrate(assoc, newsk);
4558
4559         /* If the association on the newsk is already closed before accept()
4560          * is called, set RCV_SHUTDOWN flag.
4561          */
4562         if (sctp_state(assoc, CLOSED) && sctp_style(newsk, TCP))
4563                 newsk->sk_shutdown |= RCV_SHUTDOWN;
4564
4565         newsk->sk_state = SCTP_SS_ESTABLISHED;
4566 }
4567
4568 /* This proto struct describes the ULP interface for SCTP.  */
4569 struct proto sctp_prot = {
4570         .name        =  "SCTP",
4571         .close       =  sctp_close,
4572         .connect     =  sctp_connect,
4573         .disconnect  =  sctp_disconnect,
4574         .accept      =  sctp_accept,
4575         .ioctl       =  sctp_ioctl,
4576         .init        =  sctp_init_sock,
4577         .destroy     =  sctp_destroy_sock,
4578         .shutdown    =  sctp_shutdown,
4579         .setsockopt  =  sctp_setsockopt,
4580         .getsockopt  =  sctp_getsockopt,
4581         .sendmsg     =  sctp_sendmsg,
4582         .recvmsg     =  sctp_recvmsg,
4583         .bind        =  sctp_bind,
4584         .backlog_rcv =  sctp_backlog_rcv,
4585         .hash        =  sctp_hash,
4586         .unhash      =  sctp_unhash,
4587         .get_port    =  sctp_get_port,
4588 };