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