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