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