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