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