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