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