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