xref: /linux/net/sctp/socket.c (revision fd639726bf15fca8ee1a00dce8e0096d0ad9bd18)
1 /* SCTP kernel 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 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  * This SCTP 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  * This SCTP 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, see
32  * <http://www.gnu.org/licenses/>.
33  *
34  * Please send any bug reports or fixes you make to the
35  * email address(es):
36  *    lksctp developers <linux-sctp@vger.kernel.org>
37  *
38  * Written or modified by:
39  *    La Monte H.P. Yarroll <piggy@acm.org>
40  *    Narasimha Budihal     <narsi@refcode.org>
41  *    Karl Knutson          <karl@athena.chicago.il.us>
42  *    Jon Grimm             <jgrimm@us.ibm.com>
43  *    Xingang Guo           <xingang.guo@intel.com>
44  *    Daisy Chang           <daisyc@us.ibm.com>
45  *    Sridhar Samudrala     <samudrala@us.ibm.com>
46  *    Inaky Perez-Gonzalez  <inaky.gonzalez@intel.com>
47  *    Ardelle Fan	    <ardelle.fan@intel.com>
48  *    Ryan Layer	    <rmlayer@us.ibm.com>
49  *    Anup Pemmaiah         <pemmaiah@cc.usu.edu>
50  *    Kevin Gao             <kevin.gao@intel.com>
51  */
52 
53 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
54 
55 #include <crypto/hash.h>
56 #include <linux/types.h>
57 #include <linux/kernel.h>
58 #include <linux/wait.h>
59 #include <linux/time.h>
60 #include <linux/sched/signal.h>
61 #include <linux/ip.h>
62 #include <linux/capability.h>
63 #include <linux/fcntl.h>
64 #include <linux/poll.h>
65 #include <linux/init.h>
66 #include <linux/slab.h>
67 #include <linux/file.h>
68 #include <linux/compat.h>
69 
70 #include <net/ip.h>
71 #include <net/icmp.h>
72 #include <net/route.h>
73 #include <net/ipv6.h>
74 #include <net/inet_common.h>
75 #include <net/busy_poll.h>
76 
77 #include <linux/socket.h> /* for sa_family_t */
78 #include <linux/export.h>
79 #include <net/sock.h>
80 #include <net/sctp/sctp.h>
81 #include <net/sctp/sm.h>
82 #include <net/sctp/stream_sched.h>
83 
84 /* Forward declarations for internal helper functions. */
85 static int sctp_writeable(struct sock *sk);
86 static void sctp_wfree(struct sk_buff *skb);
87 static int sctp_wait_for_sndbuf(struct sctp_association *asoc, long *timeo_p,
88 				size_t msg_len, struct sock **orig_sk);
89 static int sctp_wait_for_packet(struct sock *sk, int *err, long *timeo_p);
90 static int sctp_wait_for_connect(struct sctp_association *, long *timeo_p);
91 static int sctp_wait_for_accept(struct sock *sk, long timeo);
92 static void sctp_wait_for_close(struct sock *sk, long timeo);
93 static void sctp_destruct_sock(struct sock *sk);
94 static struct sctp_af *sctp_sockaddr_af(struct sctp_sock *opt,
95 					union sctp_addr *addr, int len);
96 static int sctp_bindx_add(struct sock *, struct sockaddr *, int);
97 static int sctp_bindx_rem(struct sock *, struct sockaddr *, int);
98 static int sctp_send_asconf_add_ip(struct sock *, struct sockaddr *, int);
99 static int sctp_send_asconf_del_ip(struct sock *, struct sockaddr *, int);
100 static int sctp_send_asconf(struct sctp_association *asoc,
101 			    struct sctp_chunk *chunk);
102 static int sctp_do_bind(struct sock *, union sctp_addr *, int);
103 static int sctp_autobind(struct sock *sk);
104 static void sctp_sock_migrate(struct sock *oldsk, struct sock *newsk,
105 			      struct sctp_association *assoc,
106 			      enum sctp_socket_type type);
107 
108 static unsigned long sctp_memory_pressure;
109 static atomic_long_t sctp_memory_allocated;
110 struct percpu_counter sctp_sockets_allocated;
111 
112 static void sctp_enter_memory_pressure(struct sock *sk)
113 {
114 	sctp_memory_pressure = 1;
115 }
116 
117 
118 /* Get the sndbuf space available at the time on the association.  */
119 static inline int sctp_wspace(struct sctp_association *asoc)
120 {
121 	int amt;
122 
123 	if (asoc->ep->sndbuf_policy)
124 		amt = asoc->sndbuf_used;
125 	else
126 		amt = sk_wmem_alloc_get(asoc->base.sk);
127 
128 	if (amt >= asoc->base.sk->sk_sndbuf) {
129 		if (asoc->base.sk->sk_userlocks & SOCK_SNDBUF_LOCK)
130 			amt = 0;
131 		else {
132 			amt = sk_stream_wspace(asoc->base.sk);
133 			if (amt < 0)
134 				amt = 0;
135 		}
136 	} else {
137 		amt = asoc->base.sk->sk_sndbuf - amt;
138 	}
139 	return amt;
140 }
141 
142 /* Increment the used sndbuf space count of the corresponding association by
143  * the size of the outgoing data chunk.
144  * Also, set the skb destructor for sndbuf accounting later.
145  *
146  * Since it is always 1-1 between chunk and skb, and also a new skb is always
147  * allocated for chunk bundling in sctp_packet_transmit(), we can use the
148  * destructor in the data chunk skb for the purpose of the sndbuf space
149  * tracking.
150  */
151 static inline void sctp_set_owner_w(struct sctp_chunk *chunk)
152 {
153 	struct sctp_association *asoc = chunk->asoc;
154 	struct sock *sk = asoc->base.sk;
155 
156 	/* The sndbuf space is tracked per association.  */
157 	sctp_association_hold(asoc);
158 
159 	skb_set_owner_w(chunk->skb, sk);
160 
161 	chunk->skb->destructor = sctp_wfree;
162 	/* Save the chunk pointer in skb for sctp_wfree to use later.  */
163 	skb_shinfo(chunk->skb)->destructor_arg = chunk;
164 
165 	asoc->sndbuf_used += SCTP_DATA_SNDSIZE(chunk) +
166 				sizeof(struct sk_buff) +
167 				sizeof(struct sctp_chunk);
168 
169 	refcount_add(sizeof(struct sctp_chunk), &sk->sk_wmem_alloc);
170 	sk->sk_wmem_queued += chunk->skb->truesize;
171 	sk_mem_charge(sk, chunk->skb->truesize);
172 }
173 
174 static void sctp_clear_owner_w(struct sctp_chunk *chunk)
175 {
176 	skb_orphan(chunk->skb);
177 }
178 
179 static void sctp_for_each_tx_datachunk(struct sctp_association *asoc,
180 				       void (*cb)(struct sctp_chunk *))
181 
182 {
183 	struct sctp_outq *q = &asoc->outqueue;
184 	struct sctp_transport *t;
185 	struct sctp_chunk *chunk;
186 
187 	list_for_each_entry(t, &asoc->peer.transport_addr_list, transports)
188 		list_for_each_entry(chunk, &t->transmitted, transmitted_list)
189 			cb(chunk);
190 
191 	list_for_each_entry(chunk, &q->retransmit, transmitted_list)
192 		cb(chunk);
193 
194 	list_for_each_entry(chunk, &q->sacked, transmitted_list)
195 		cb(chunk);
196 
197 	list_for_each_entry(chunk, &q->abandoned, transmitted_list)
198 		cb(chunk);
199 
200 	list_for_each_entry(chunk, &q->out_chunk_list, list)
201 		cb(chunk);
202 }
203 
204 /* Verify that this is a valid address. */
205 static inline int sctp_verify_addr(struct sock *sk, union sctp_addr *addr,
206 				   int len)
207 {
208 	struct sctp_af *af;
209 
210 	/* Verify basic sockaddr. */
211 	af = sctp_sockaddr_af(sctp_sk(sk), addr, len);
212 	if (!af)
213 		return -EINVAL;
214 
215 	/* Is this a valid SCTP address?  */
216 	if (!af->addr_valid(addr, sctp_sk(sk), NULL))
217 		return -EINVAL;
218 
219 	if (!sctp_sk(sk)->pf->send_verify(sctp_sk(sk), (addr)))
220 		return -EINVAL;
221 
222 	return 0;
223 }
224 
225 /* Look up the association by its id.  If this is not a UDP-style
226  * socket, the ID field is always ignored.
227  */
228 struct sctp_association *sctp_id2assoc(struct sock *sk, sctp_assoc_t id)
229 {
230 	struct sctp_association *asoc = NULL;
231 
232 	/* If this is not a UDP-style socket, assoc id should be ignored. */
233 	if (!sctp_style(sk, UDP)) {
234 		/* Return NULL if the socket state is not ESTABLISHED. It
235 		 * could be a TCP-style listening socket or a socket which
236 		 * hasn't yet called connect() to establish an association.
237 		 */
238 		if (!sctp_sstate(sk, ESTABLISHED) && !sctp_sstate(sk, CLOSING))
239 			return NULL;
240 
241 		/* Get the first and the only association from the list. */
242 		if (!list_empty(&sctp_sk(sk)->ep->asocs))
243 			asoc = list_entry(sctp_sk(sk)->ep->asocs.next,
244 					  struct sctp_association, asocs);
245 		return asoc;
246 	}
247 
248 	/* Otherwise this is a UDP-style socket. */
249 	if (!id || (id == (sctp_assoc_t)-1))
250 		return NULL;
251 
252 	spin_lock_bh(&sctp_assocs_id_lock);
253 	asoc = (struct sctp_association *)idr_find(&sctp_assocs_id, (int)id);
254 	spin_unlock_bh(&sctp_assocs_id_lock);
255 
256 	if (!asoc || (asoc->base.sk != sk) || asoc->base.dead)
257 		return NULL;
258 
259 	return asoc;
260 }
261 
262 /* Look up the transport from an address and an assoc id. If both address and
263  * id are specified, the associations matching the address and the id should be
264  * the same.
265  */
266 static struct sctp_transport *sctp_addr_id2transport(struct sock *sk,
267 					      struct sockaddr_storage *addr,
268 					      sctp_assoc_t id)
269 {
270 	struct sctp_association *addr_asoc = NULL, *id_asoc = NULL;
271 	struct sctp_af *af = sctp_get_af_specific(addr->ss_family);
272 	union sctp_addr *laddr = (union sctp_addr *)addr;
273 	struct sctp_transport *transport;
274 
275 	if (!af || sctp_verify_addr(sk, laddr, af->sockaddr_len))
276 		return NULL;
277 
278 	addr_asoc = sctp_endpoint_lookup_assoc(sctp_sk(sk)->ep,
279 					       laddr,
280 					       &transport);
281 
282 	if (!addr_asoc)
283 		return NULL;
284 
285 	id_asoc = sctp_id2assoc(sk, id);
286 	if (id_asoc && (id_asoc != addr_asoc))
287 		return NULL;
288 
289 	sctp_get_pf_specific(sk->sk_family)->addr_to_user(sctp_sk(sk),
290 						(union sctp_addr *)addr);
291 
292 	return transport;
293 }
294 
295 /* API 3.1.2 bind() - UDP Style Syntax
296  * The syntax of bind() is,
297  *
298  *   ret = bind(int sd, struct sockaddr *addr, int addrlen);
299  *
300  *   sd      - the socket descriptor returned by socket().
301  *   addr    - the address structure (struct sockaddr_in or struct
302  *             sockaddr_in6 [RFC 2553]),
303  *   addr_len - the size of the address structure.
304  */
305 static int sctp_bind(struct sock *sk, struct sockaddr *addr, int addr_len)
306 {
307 	int retval = 0;
308 
309 	lock_sock(sk);
310 
311 	pr_debug("%s: sk:%p, addr:%p, addr_len:%d\n", __func__, sk,
312 		 addr, addr_len);
313 
314 	/* Disallow binding twice. */
315 	if (!sctp_sk(sk)->ep->base.bind_addr.port)
316 		retval = sctp_do_bind(sk, (union sctp_addr *)addr,
317 				      addr_len);
318 	else
319 		retval = -EINVAL;
320 
321 	release_sock(sk);
322 
323 	return retval;
324 }
325 
326 static long sctp_get_port_local(struct sock *, union sctp_addr *);
327 
328 /* Verify this is a valid sockaddr. */
329 static struct sctp_af *sctp_sockaddr_af(struct sctp_sock *opt,
330 					union sctp_addr *addr, int len)
331 {
332 	struct sctp_af *af;
333 
334 	/* Check minimum size.  */
335 	if (len < sizeof (struct sockaddr))
336 		return NULL;
337 
338 	/* V4 mapped address are really of AF_INET family */
339 	if (addr->sa.sa_family == AF_INET6 &&
340 	    ipv6_addr_v4mapped(&addr->v6.sin6_addr)) {
341 		if (!opt->pf->af_supported(AF_INET, opt))
342 			return NULL;
343 	} else {
344 		/* Does this PF support this AF? */
345 		if (!opt->pf->af_supported(addr->sa.sa_family, opt))
346 			return NULL;
347 	}
348 
349 	/* If we get this far, af is valid. */
350 	af = sctp_get_af_specific(addr->sa.sa_family);
351 
352 	if (len < af->sockaddr_len)
353 		return NULL;
354 
355 	return af;
356 }
357 
358 /* Bind a local address either to an endpoint or to an association.  */
359 static int sctp_do_bind(struct sock *sk, union sctp_addr *addr, int len)
360 {
361 	struct net *net = sock_net(sk);
362 	struct sctp_sock *sp = sctp_sk(sk);
363 	struct sctp_endpoint *ep = sp->ep;
364 	struct sctp_bind_addr *bp = &ep->base.bind_addr;
365 	struct sctp_af *af;
366 	unsigned short snum;
367 	int ret = 0;
368 
369 	/* Common sockaddr verification. */
370 	af = sctp_sockaddr_af(sp, addr, len);
371 	if (!af) {
372 		pr_debug("%s: sk:%p, newaddr:%p, len:%d EINVAL\n",
373 			 __func__, sk, addr, len);
374 		return -EINVAL;
375 	}
376 
377 	snum = ntohs(addr->v4.sin_port);
378 
379 	pr_debug("%s: sk:%p, new addr:%pISc, port:%d, new port:%d, len:%d\n",
380 		 __func__, sk, &addr->sa, bp->port, snum, len);
381 
382 	/* PF specific bind() address verification. */
383 	if (!sp->pf->bind_verify(sp, addr))
384 		return -EADDRNOTAVAIL;
385 
386 	/* We must either be unbound, or bind to the same port.
387 	 * It's OK to allow 0 ports if we are already bound.
388 	 * We'll just inhert an already bound port in this case
389 	 */
390 	if (bp->port) {
391 		if (!snum)
392 			snum = bp->port;
393 		else if (snum != bp->port) {
394 			pr_debug("%s: new port %d doesn't match existing port "
395 				 "%d\n", __func__, snum, bp->port);
396 			return -EINVAL;
397 		}
398 	}
399 
400 	if (snum && snum < inet_prot_sock(net) &&
401 	    !ns_capable(net->user_ns, CAP_NET_BIND_SERVICE))
402 		return -EACCES;
403 
404 	/* See if the address matches any of the addresses we may have
405 	 * already bound before checking against other endpoints.
406 	 */
407 	if (sctp_bind_addr_match(bp, addr, sp))
408 		return -EINVAL;
409 
410 	/* Make sure we are allowed to bind here.
411 	 * The function sctp_get_port_local() does duplicate address
412 	 * detection.
413 	 */
414 	addr->v4.sin_port = htons(snum);
415 	if ((ret = sctp_get_port_local(sk, addr))) {
416 		return -EADDRINUSE;
417 	}
418 
419 	/* Refresh ephemeral port.  */
420 	if (!bp->port)
421 		bp->port = inet_sk(sk)->inet_num;
422 
423 	/* Add the address to the bind address list.
424 	 * Use GFP_ATOMIC since BHs will be disabled.
425 	 */
426 	ret = sctp_add_bind_addr(bp, addr, af->sockaddr_len,
427 				 SCTP_ADDR_SRC, GFP_ATOMIC);
428 
429 	/* Copy back into socket for getsockname() use. */
430 	if (!ret) {
431 		inet_sk(sk)->inet_sport = htons(inet_sk(sk)->inet_num);
432 		sp->pf->to_sk_saddr(addr, sk);
433 	}
434 
435 	return ret;
436 }
437 
438  /* ADDIP Section 4.1.1 Congestion Control of ASCONF Chunks
439  *
440  * R1) One and only one ASCONF Chunk MAY be in transit and unacknowledged
441  * at any one time.  If a sender, after sending an ASCONF chunk, decides
442  * it needs to transfer another ASCONF Chunk, it MUST wait until the
443  * ASCONF-ACK Chunk returns from the previous ASCONF Chunk before sending a
444  * subsequent ASCONF. Note this restriction binds each side, so at any
445  * time two ASCONF may be in-transit on any given association (one sent
446  * from each endpoint).
447  */
448 static int sctp_send_asconf(struct sctp_association *asoc,
449 			    struct sctp_chunk *chunk)
450 {
451 	struct net 	*net = sock_net(asoc->base.sk);
452 	int		retval = 0;
453 
454 	/* If there is an outstanding ASCONF chunk, queue it for later
455 	 * transmission.
456 	 */
457 	if (asoc->addip_last_asconf) {
458 		list_add_tail(&chunk->list, &asoc->addip_chunk_list);
459 		goto out;
460 	}
461 
462 	/* Hold the chunk until an ASCONF_ACK is received. */
463 	sctp_chunk_hold(chunk);
464 	retval = sctp_primitive_ASCONF(net, asoc, chunk);
465 	if (retval)
466 		sctp_chunk_free(chunk);
467 	else
468 		asoc->addip_last_asconf = chunk;
469 
470 out:
471 	return retval;
472 }
473 
474 /* Add a list of addresses as bind addresses to local endpoint or
475  * association.
476  *
477  * Basically run through each address specified in the addrs/addrcnt
478  * array/length pair, determine if it is IPv6 or IPv4 and call
479  * sctp_do_bind() on it.
480  *
481  * If any of them fails, then the operation will be reversed and the
482  * ones that were added will be removed.
483  *
484  * Only sctp_setsockopt_bindx() is supposed to call this function.
485  */
486 static int sctp_bindx_add(struct sock *sk, struct sockaddr *addrs, int addrcnt)
487 {
488 	int cnt;
489 	int retval = 0;
490 	void *addr_buf;
491 	struct sockaddr *sa_addr;
492 	struct sctp_af *af;
493 
494 	pr_debug("%s: sk:%p, addrs:%p, addrcnt:%d\n", __func__, sk,
495 		 addrs, addrcnt);
496 
497 	addr_buf = addrs;
498 	for (cnt = 0; cnt < addrcnt; cnt++) {
499 		/* The list may contain either IPv4 or IPv6 address;
500 		 * determine the address length for walking thru the list.
501 		 */
502 		sa_addr = addr_buf;
503 		af = sctp_get_af_specific(sa_addr->sa_family);
504 		if (!af) {
505 			retval = -EINVAL;
506 			goto err_bindx_add;
507 		}
508 
509 		retval = sctp_do_bind(sk, (union sctp_addr *)sa_addr,
510 				      af->sockaddr_len);
511 
512 		addr_buf += af->sockaddr_len;
513 
514 err_bindx_add:
515 		if (retval < 0) {
516 			/* Failed. Cleanup the ones that have been added */
517 			if (cnt > 0)
518 				sctp_bindx_rem(sk, addrs, cnt);
519 			return retval;
520 		}
521 	}
522 
523 	return retval;
524 }
525 
526 /* Send an ASCONF chunk with Add IP address parameters to all the peers of the
527  * associations that are part of the endpoint indicating that a list of local
528  * addresses are added to the endpoint.
529  *
530  * If any of the addresses is already in the bind address list of the
531  * association, we do not send the chunk for that association.  But it will not
532  * affect other associations.
533  *
534  * Only sctp_setsockopt_bindx() is supposed to call this function.
535  */
536 static int sctp_send_asconf_add_ip(struct sock		*sk,
537 				   struct sockaddr	*addrs,
538 				   int 			addrcnt)
539 {
540 	struct net *net = sock_net(sk);
541 	struct sctp_sock		*sp;
542 	struct sctp_endpoint		*ep;
543 	struct sctp_association		*asoc;
544 	struct sctp_bind_addr		*bp;
545 	struct sctp_chunk		*chunk;
546 	struct sctp_sockaddr_entry	*laddr;
547 	union sctp_addr			*addr;
548 	union sctp_addr			saveaddr;
549 	void				*addr_buf;
550 	struct sctp_af			*af;
551 	struct list_head		*p;
552 	int 				i;
553 	int 				retval = 0;
554 
555 	if (!net->sctp.addip_enable)
556 		return retval;
557 
558 	sp = sctp_sk(sk);
559 	ep = sp->ep;
560 
561 	pr_debug("%s: sk:%p, addrs:%p, addrcnt:%d\n",
562 		 __func__, sk, addrs, addrcnt);
563 
564 	list_for_each_entry(asoc, &ep->asocs, asocs) {
565 		if (!asoc->peer.asconf_capable)
566 			continue;
567 
568 		if (asoc->peer.addip_disabled_mask & SCTP_PARAM_ADD_IP)
569 			continue;
570 
571 		if (!sctp_state(asoc, ESTABLISHED))
572 			continue;
573 
574 		/* Check if any address in the packed array of addresses is
575 		 * in the bind address list of the association. If so,
576 		 * do not send the asconf chunk to its peer, but continue with
577 		 * other associations.
578 		 */
579 		addr_buf = addrs;
580 		for (i = 0; i < addrcnt; i++) {
581 			addr = addr_buf;
582 			af = sctp_get_af_specific(addr->v4.sin_family);
583 			if (!af) {
584 				retval = -EINVAL;
585 				goto out;
586 			}
587 
588 			if (sctp_assoc_lookup_laddr(asoc, addr))
589 				break;
590 
591 			addr_buf += af->sockaddr_len;
592 		}
593 		if (i < addrcnt)
594 			continue;
595 
596 		/* Use the first valid address in bind addr list of
597 		 * association as Address Parameter of ASCONF CHUNK.
598 		 */
599 		bp = &asoc->base.bind_addr;
600 		p = bp->address_list.next;
601 		laddr = list_entry(p, struct sctp_sockaddr_entry, list);
602 		chunk = sctp_make_asconf_update_ip(asoc, &laddr->a, addrs,
603 						   addrcnt, SCTP_PARAM_ADD_IP);
604 		if (!chunk) {
605 			retval = -ENOMEM;
606 			goto out;
607 		}
608 
609 		/* Add the new addresses to the bind address list with
610 		 * use_as_src set to 0.
611 		 */
612 		addr_buf = addrs;
613 		for (i = 0; i < addrcnt; i++) {
614 			addr = addr_buf;
615 			af = sctp_get_af_specific(addr->v4.sin_family);
616 			memcpy(&saveaddr, addr, af->sockaddr_len);
617 			retval = sctp_add_bind_addr(bp, &saveaddr,
618 						    sizeof(saveaddr),
619 						    SCTP_ADDR_NEW, GFP_ATOMIC);
620 			addr_buf += af->sockaddr_len;
621 		}
622 		if (asoc->src_out_of_asoc_ok) {
623 			struct sctp_transport *trans;
624 
625 			list_for_each_entry(trans,
626 			    &asoc->peer.transport_addr_list, transports) {
627 				/* Clear the source and route cache */
628 				sctp_transport_dst_release(trans);
629 				trans->cwnd = min(4*asoc->pathmtu, max_t(__u32,
630 				    2*asoc->pathmtu, 4380));
631 				trans->ssthresh = asoc->peer.i.a_rwnd;
632 				trans->rto = asoc->rto_initial;
633 				sctp_max_rto(asoc, trans);
634 				trans->rtt = trans->srtt = trans->rttvar = 0;
635 				sctp_transport_route(trans, NULL,
636 				    sctp_sk(asoc->base.sk));
637 			}
638 		}
639 		retval = sctp_send_asconf(asoc, chunk);
640 	}
641 
642 out:
643 	return retval;
644 }
645 
646 /* Remove a list of addresses from bind addresses list.  Do not remove the
647  * last address.
648  *
649  * Basically run through each address specified in the addrs/addrcnt
650  * array/length pair, determine if it is IPv6 or IPv4 and call
651  * sctp_del_bind() on it.
652  *
653  * If any of them fails, then the operation will be reversed and the
654  * ones that were removed will be added back.
655  *
656  * At least one address has to be left; if only one address is
657  * available, the operation will return -EBUSY.
658  *
659  * Only sctp_setsockopt_bindx() is supposed to call this function.
660  */
661 static int sctp_bindx_rem(struct sock *sk, struct sockaddr *addrs, int addrcnt)
662 {
663 	struct sctp_sock *sp = sctp_sk(sk);
664 	struct sctp_endpoint *ep = sp->ep;
665 	int cnt;
666 	struct sctp_bind_addr *bp = &ep->base.bind_addr;
667 	int retval = 0;
668 	void *addr_buf;
669 	union sctp_addr *sa_addr;
670 	struct sctp_af *af;
671 
672 	pr_debug("%s: sk:%p, addrs:%p, addrcnt:%d\n",
673 		 __func__, sk, addrs, addrcnt);
674 
675 	addr_buf = addrs;
676 	for (cnt = 0; cnt < addrcnt; cnt++) {
677 		/* If the bind address list is empty or if there is only one
678 		 * bind address, there is nothing more to be removed (we need
679 		 * at least one address here).
680 		 */
681 		if (list_empty(&bp->address_list) ||
682 		    (sctp_list_single_entry(&bp->address_list))) {
683 			retval = -EBUSY;
684 			goto err_bindx_rem;
685 		}
686 
687 		sa_addr = addr_buf;
688 		af = sctp_get_af_specific(sa_addr->sa.sa_family);
689 		if (!af) {
690 			retval = -EINVAL;
691 			goto err_bindx_rem;
692 		}
693 
694 		if (!af->addr_valid(sa_addr, sp, NULL)) {
695 			retval = -EADDRNOTAVAIL;
696 			goto err_bindx_rem;
697 		}
698 
699 		if (sa_addr->v4.sin_port &&
700 		    sa_addr->v4.sin_port != htons(bp->port)) {
701 			retval = -EINVAL;
702 			goto err_bindx_rem;
703 		}
704 
705 		if (!sa_addr->v4.sin_port)
706 			sa_addr->v4.sin_port = htons(bp->port);
707 
708 		/* FIXME - There is probably a need to check if sk->sk_saddr and
709 		 * sk->sk_rcv_addr are currently set to one of the addresses to
710 		 * be removed. This is something which needs to be looked into
711 		 * when we are fixing the outstanding issues with multi-homing
712 		 * socket routing and failover schemes. Refer to comments in
713 		 * sctp_do_bind(). -daisy
714 		 */
715 		retval = sctp_del_bind_addr(bp, sa_addr);
716 
717 		addr_buf += af->sockaddr_len;
718 err_bindx_rem:
719 		if (retval < 0) {
720 			/* Failed. Add the ones that has been removed back */
721 			if (cnt > 0)
722 				sctp_bindx_add(sk, addrs, cnt);
723 			return retval;
724 		}
725 	}
726 
727 	return retval;
728 }
729 
730 /* Send an ASCONF chunk with Delete IP address parameters to all the peers of
731  * the associations that are part of the endpoint indicating that a list of
732  * local addresses are removed from the endpoint.
733  *
734  * If any of the addresses is already in the bind address list of the
735  * association, we do not send the chunk for that association.  But it will not
736  * affect other associations.
737  *
738  * Only sctp_setsockopt_bindx() is supposed to call this function.
739  */
740 static int sctp_send_asconf_del_ip(struct sock		*sk,
741 				   struct sockaddr	*addrs,
742 				   int			addrcnt)
743 {
744 	struct net *net = sock_net(sk);
745 	struct sctp_sock	*sp;
746 	struct sctp_endpoint	*ep;
747 	struct sctp_association	*asoc;
748 	struct sctp_transport	*transport;
749 	struct sctp_bind_addr	*bp;
750 	struct sctp_chunk	*chunk;
751 	union sctp_addr		*laddr;
752 	void			*addr_buf;
753 	struct sctp_af		*af;
754 	struct sctp_sockaddr_entry *saddr;
755 	int 			i;
756 	int 			retval = 0;
757 	int			stored = 0;
758 
759 	chunk = NULL;
760 	if (!net->sctp.addip_enable)
761 		return retval;
762 
763 	sp = sctp_sk(sk);
764 	ep = sp->ep;
765 
766 	pr_debug("%s: sk:%p, addrs:%p, addrcnt:%d\n",
767 		 __func__, sk, addrs, addrcnt);
768 
769 	list_for_each_entry(asoc, &ep->asocs, asocs) {
770 
771 		if (!asoc->peer.asconf_capable)
772 			continue;
773 
774 		if (asoc->peer.addip_disabled_mask & SCTP_PARAM_DEL_IP)
775 			continue;
776 
777 		if (!sctp_state(asoc, ESTABLISHED))
778 			continue;
779 
780 		/* Check if any address in the packed array of addresses is
781 		 * not present in the bind address list of the association.
782 		 * If so, do not send the asconf chunk to its peer, but
783 		 * continue with other associations.
784 		 */
785 		addr_buf = addrs;
786 		for (i = 0; i < addrcnt; i++) {
787 			laddr = addr_buf;
788 			af = sctp_get_af_specific(laddr->v4.sin_family);
789 			if (!af) {
790 				retval = -EINVAL;
791 				goto out;
792 			}
793 
794 			if (!sctp_assoc_lookup_laddr(asoc, laddr))
795 				break;
796 
797 			addr_buf += af->sockaddr_len;
798 		}
799 		if (i < addrcnt)
800 			continue;
801 
802 		/* Find one address in the association's bind address list
803 		 * that is not in the packed array of addresses. This is to
804 		 * make sure that we do not delete all the addresses in the
805 		 * association.
806 		 */
807 		bp = &asoc->base.bind_addr;
808 		laddr = sctp_find_unmatch_addr(bp, (union sctp_addr *)addrs,
809 					       addrcnt, sp);
810 		if ((laddr == NULL) && (addrcnt == 1)) {
811 			if (asoc->asconf_addr_del_pending)
812 				continue;
813 			asoc->asconf_addr_del_pending =
814 			    kzalloc(sizeof(union sctp_addr), GFP_ATOMIC);
815 			if (asoc->asconf_addr_del_pending == NULL) {
816 				retval = -ENOMEM;
817 				goto out;
818 			}
819 			asoc->asconf_addr_del_pending->sa.sa_family =
820 				    addrs->sa_family;
821 			asoc->asconf_addr_del_pending->v4.sin_port =
822 				    htons(bp->port);
823 			if (addrs->sa_family == AF_INET) {
824 				struct sockaddr_in *sin;
825 
826 				sin = (struct sockaddr_in *)addrs;
827 				asoc->asconf_addr_del_pending->v4.sin_addr.s_addr = sin->sin_addr.s_addr;
828 			} else if (addrs->sa_family == AF_INET6) {
829 				struct sockaddr_in6 *sin6;
830 
831 				sin6 = (struct sockaddr_in6 *)addrs;
832 				asoc->asconf_addr_del_pending->v6.sin6_addr = sin6->sin6_addr;
833 			}
834 
835 			pr_debug("%s: keep the last address asoc:%p %pISc at %p\n",
836 				 __func__, asoc, &asoc->asconf_addr_del_pending->sa,
837 				 asoc->asconf_addr_del_pending);
838 
839 			asoc->src_out_of_asoc_ok = 1;
840 			stored = 1;
841 			goto skip_mkasconf;
842 		}
843 
844 		if (laddr == NULL)
845 			return -EINVAL;
846 
847 		/* We do not need RCU protection throughout this loop
848 		 * because this is done under a socket lock from the
849 		 * setsockopt call.
850 		 */
851 		chunk = sctp_make_asconf_update_ip(asoc, laddr, addrs, addrcnt,
852 						   SCTP_PARAM_DEL_IP);
853 		if (!chunk) {
854 			retval = -ENOMEM;
855 			goto out;
856 		}
857 
858 skip_mkasconf:
859 		/* Reset use_as_src flag for the addresses in the bind address
860 		 * list that are to be deleted.
861 		 */
862 		addr_buf = addrs;
863 		for (i = 0; i < addrcnt; i++) {
864 			laddr = addr_buf;
865 			af = sctp_get_af_specific(laddr->v4.sin_family);
866 			list_for_each_entry(saddr, &bp->address_list, list) {
867 				if (sctp_cmp_addr_exact(&saddr->a, laddr))
868 					saddr->state = SCTP_ADDR_DEL;
869 			}
870 			addr_buf += af->sockaddr_len;
871 		}
872 
873 		/* Update the route and saddr entries for all the transports
874 		 * as some of the addresses in the bind address list are
875 		 * about to be deleted and cannot be used as source addresses.
876 		 */
877 		list_for_each_entry(transport, &asoc->peer.transport_addr_list,
878 					transports) {
879 			sctp_transport_dst_release(transport);
880 			sctp_transport_route(transport, NULL,
881 					     sctp_sk(asoc->base.sk));
882 		}
883 
884 		if (stored)
885 			/* We don't need to transmit ASCONF */
886 			continue;
887 		retval = sctp_send_asconf(asoc, chunk);
888 	}
889 out:
890 	return retval;
891 }
892 
893 /* set addr events to assocs in the endpoint.  ep and addr_wq must be locked */
894 int sctp_asconf_mgmt(struct sctp_sock *sp, struct sctp_sockaddr_entry *addrw)
895 {
896 	struct sock *sk = sctp_opt2sk(sp);
897 	union sctp_addr *addr;
898 	struct sctp_af *af;
899 
900 	/* It is safe to write port space in caller. */
901 	addr = &addrw->a;
902 	addr->v4.sin_port = htons(sp->ep->base.bind_addr.port);
903 	af = sctp_get_af_specific(addr->sa.sa_family);
904 	if (!af)
905 		return -EINVAL;
906 	if (sctp_verify_addr(sk, addr, af->sockaddr_len))
907 		return -EINVAL;
908 
909 	if (addrw->state == SCTP_ADDR_NEW)
910 		return sctp_send_asconf_add_ip(sk, (struct sockaddr *)addr, 1);
911 	else
912 		return sctp_send_asconf_del_ip(sk, (struct sockaddr *)addr, 1);
913 }
914 
915 /* Helper for tunneling sctp_bindx() requests through sctp_setsockopt()
916  *
917  * API 8.1
918  * int sctp_bindx(int sd, struct sockaddr *addrs, int addrcnt,
919  *                int flags);
920  *
921  * If sd is an IPv4 socket, the addresses passed must be IPv4 addresses.
922  * If the sd is an IPv6 socket, the addresses passed can either be IPv4
923  * or IPv6 addresses.
924  *
925  * A single address may be specified as INADDR_ANY or IN6ADDR_ANY, see
926  * Section 3.1.2 for this usage.
927  *
928  * addrs is a pointer to an array of one or more socket addresses. Each
929  * address is contained in its appropriate structure (i.e. struct
930  * sockaddr_in or struct sockaddr_in6) the family of the address type
931  * must be used to distinguish the address length (note that this
932  * representation is termed a "packed array" of addresses). The caller
933  * specifies the number of addresses in the array with addrcnt.
934  *
935  * On success, sctp_bindx() returns 0. On failure, sctp_bindx() returns
936  * -1, and sets errno to the appropriate error code.
937  *
938  * For SCTP, the port given in each socket address must be the same, or
939  * sctp_bindx() will fail, setting errno to EINVAL.
940  *
941  * The flags parameter is formed from the bitwise OR of zero or more of
942  * the following currently defined flags:
943  *
944  * SCTP_BINDX_ADD_ADDR
945  *
946  * SCTP_BINDX_REM_ADDR
947  *
948  * SCTP_BINDX_ADD_ADDR directs SCTP to add the given addresses to the
949  * association, and SCTP_BINDX_REM_ADDR directs SCTP to remove the given
950  * addresses from the association. The two flags are mutually exclusive;
951  * if both are given, sctp_bindx() will fail with EINVAL. A caller may
952  * not remove all addresses from an association; sctp_bindx() will
953  * reject such an attempt with EINVAL.
954  *
955  * An application can use sctp_bindx(SCTP_BINDX_ADD_ADDR) to associate
956  * additional addresses with an endpoint after calling bind().  Or use
957  * sctp_bindx(SCTP_BINDX_REM_ADDR) to remove some addresses a listening
958  * socket is associated with so that no new association accepted will be
959  * associated with those addresses. If the endpoint supports dynamic
960  * address a SCTP_BINDX_REM_ADDR or SCTP_BINDX_ADD_ADDR may cause a
961  * endpoint to send the appropriate message to the peer to change the
962  * peers address lists.
963  *
964  * Adding and removing addresses from a connected association is
965  * optional functionality. Implementations that do not support this
966  * functionality should return EOPNOTSUPP.
967  *
968  * Basically do nothing but copying the addresses from user to kernel
969  * land and invoking either sctp_bindx_add() or sctp_bindx_rem() on the sk.
970  * This is used for tunneling the sctp_bindx() request through sctp_setsockopt()
971  * from userspace.
972  *
973  * We don't use copy_from_user() for optimization: we first do the
974  * sanity checks (buffer size -fast- and access check-healthy
975  * pointer); if all of those succeed, then we can alloc the memory
976  * (expensive operation) needed to copy the data to kernel. Then we do
977  * the copying without checking the user space area
978  * (__copy_from_user()).
979  *
980  * On exit there is no need to do sockfd_put(), sys_setsockopt() does
981  * it.
982  *
983  * sk        The sk of the socket
984  * addrs     The pointer to the addresses in user land
985  * addrssize Size of the addrs buffer
986  * op        Operation to perform (add or remove, see the flags of
987  *           sctp_bindx)
988  *
989  * Returns 0 if ok, <0 errno code on error.
990  */
991 static int sctp_setsockopt_bindx(struct sock *sk,
992 				 struct sockaddr __user *addrs,
993 				 int addrs_size, int op)
994 {
995 	struct sockaddr *kaddrs;
996 	int err;
997 	int addrcnt = 0;
998 	int walk_size = 0;
999 	struct sockaddr *sa_addr;
1000 	void *addr_buf;
1001 	struct sctp_af *af;
1002 
1003 	pr_debug("%s: sk:%p addrs:%p addrs_size:%d opt:%d\n",
1004 		 __func__, sk, addrs, addrs_size, op);
1005 
1006 	if (unlikely(addrs_size <= 0))
1007 		return -EINVAL;
1008 
1009 	/* Check the user passed a healthy pointer.  */
1010 	if (unlikely(!access_ok(VERIFY_READ, addrs, addrs_size)))
1011 		return -EFAULT;
1012 
1013 	/* Alloc space for the address array in kernel memory.  */
1014 	kaddrs = kmalloc(addrs_size, GFP_USER | __GFP_NOWARN);
1015 	if (unlikely(!kaddrs))
1016 		return -ENOMEM;
1017 
1018 	if (__copy_from_user(kaddrs, addrs, addrs_size)) {
1019 		kfree(kaddrs);
1020 		return -EFAULT;
1021 	}
1022 
1023 	/* Walk through the addrs buffer and count the number of addresses. */
1024 	addr_buf = kaddrs;
1025 	while (walk_size < addrs_size) {
1026 		if (walk_size + sizeof(sa_family_t) > addrs_size) {
1027 			kfree(kaddrs);
1028 			return -EINVAL;
1029 		}
1030 
1031 		sa_addr = addr_buf;
1032 		af = sctp_get_af_specific(sa_addr->sa_family);
1033 
1034 		/* If the address family is not supported or if this address
1035 		 * causes the address buffer to overflow return EINVAL.
1036 		 */
1037 		if (!af || (walk_size + af->sockaddr_len) > addrs_size) {
1038 			kfree(kaddrs);
1039 			return -EINVAL;
1040 		}
1041 		addrcnt++;
1042 		addr_buf += af->sockaddr_len;
1043 		walk_size += af->sockaddr_len;
1044 	}
1045 
1046 	/* Do the work. */
1047 	switch (op) {
1048 	case SCTP_BINDX_ADD_ADDR:
1049 		err = sctp_bindx_add(sk, kaddrs, addrcnt);
1050 		if (err)
1051 			goto out;
1052 		err = sctp_send_asconf_add_ip(sk, kaddrs, addrcnt);
1053 		break;
1054 
1055 	case SCTP_BINDX_REM_ADDR:
1056 		err = sctp_bindx_rem(sk, kaddrs, addrcnt);
1057 		if (err)
1058 			goto out;
1059 		err = sctp_send_asconf_del_ip(sk, kaddrs, addrcnt);
1060 		break;
1061 
1062 	default:
1063 		err = -EINVAL;
1064 		break;
1065 	}
1066 
1067 out:
1068 	kfree(kaddrs);
1069 
1070 	return err;
1071 }
1072 
1073 /* __sctp_connect(struct sock* sk, struct sockaddr *kaddrs, int addrs_size)
1074  *
1075  * Common routine for handling connect() and sctp_connectx().
1076  * Connect will come in with just a single address.
1077  */
1078 static int __sctp_connect(struct sock *sk,
1079 			  struct sockaddr *kaddrs,
1080 			  int addrs_size,
1081 			  sctp_assoc_t *assoc_id)
1082 {
1083 	struct net *net = sock_net(sk);
1084 	struct sctp_sock *sp;
1085 	struct sctp_endpoint *ep;
1086 	struct sctp_association *asoc = NULL;
1087 	struct sctp_association *asoc2;
1088 	struct sctp_transport *transport;
1089 	union sctp_addr to;
1090 	enum sctp_scope scope;
1091 	long timeo;
1092 	int err = 0;
1093 	int addrcnt = 0;
1094 	int walk_size = 0;
1095 	union sctp_addr *sa_addr = NULL;
1096 	void *addr_buf;
1097 	unsigned short port;
1098 	unsigned int f_flags = 0;
1099 
1100 	sp = sctp_sk(sk);
1101 	ep = sp->ep;
1102 
1103 	/* connect() cannot be done on a socket that is already in ESTABLISHED
1104 	 * state - UDP-style peeled off socket or a TCP-style socket that
1105 	 * is already connected.
1106 	 * It cannot be done even on a TCP-style listening socket.
1107 	 */
1108 	if (sctp_sstate(sk, ESTABLISHED) || sctp_sstate(sk, CLOSING) ||
1109 	    (sctp_style(sk, TCP) && sctp_sstate(sk, LISTENING))) {
1110 		err = -EISCONN;
1111 		goto out_free;
1112 	}
1113 
1114 	/* Walk through the addrs buffer and count the number of addresses. */
1115 	addr_buf = kaddrs;
1116 	while (walk_size < addrs_size) {
1117 		struct sctp_af *af;
1118 
1119 		if (walk_size + sizeof(sa_family_t) > addrs_size) {
1120 			err = -EINVAL;
1121 			goto out_free;
1122 		}
1123 
1124 		sa_addr = addr_buf;
1125 		af = sctp_get_af_specific(sa_addr->sa.sa_family);
1126 
1127 		/* If the address family is not supported or if this address
1128 		 * causes the address buffer to overflow return EINVAL.
1129 		 */
1130 		if (!af || (walk_size + af->sockaddr_len) > addrs_size) {
1131 			err = -EINVAL;
1132 			goto out_free;
1133 		}
1134 
1135 		port = ntohs(sa_addr->v4.sin_port);
1136 
1137 		/* Save current address so we can work with it */
1138 		memcpy(&to, sa_addr, af->sockaddr_len);
1139 
1140 		err = sctp_verify_addr(sk, &to, af->sockaddr_len);
1141 		if (err)
1142 			goto out_free;
1143 
1144 		/* Make sure the destination port is correctly set
1145 		 * in all addresses.
1146 		 */
1147 		if (asoc && asoc->peer.port && asoc->peer.port != port) {
1148 			err = -EINVAL;
1149 			goto out_free;
1150 		}
1151 
1152 		/* Check if there already is a matching association on the
1153 		 * endpoint (other than the one created here).
1154 		 */
1155 		asoc2 = sctp_endpoint_lookup_assoc(ep, &to, &transport);
1156 		if (asoc2 && asoc2 != asoc) {
1157 			if (asoc2->state >= SCTP_STATE_ESTABLISHED)
1158 				err = -EISCONN;
1159 			else
1160 				err = -EALREADY;
1161 			goto out_free;
1162 		}
1163 
1164 		/* If we could not find a matching association on the endpoint,
1165 		 * make sure that there is no peeled-off association matching
1166 		 * the peer address even on another socket.
1167 		 */
1168 		if (sctp_endpoint_is_peeled_off(ep, &to)) {
1169 			err = -EADDRNOTAVAIL;
1170 			goto out_free;
1171 		}
1172 
1173 		if (!asoc) {
1174 			/* If a bind() or sctp_bindx() is not called prior to
1175 			 * an sctp_connectx() call, the system picks an
1176 			 * ephemeral port and will choose an address set
1177 			 * equivalent to binding with a wildcard address.
1178 			 */
1179 			if (!ep->base.bind_addr.port) {
1180 				if (sctp_autobind(sk)) {
1181 					err = -EAGAIN;
1182 					goto out_free;
1183 				}
1184 			} else {
1185 				/*
1186 				 * If an unprivileged user inherits a 1-many
1187 				 * style socket with open associations on a
1188 				 * privileged port, it MAY be permitted to
1189 				 * accept new associations, but it SHOULD NOT
1190 				 * be permitted to open new associations.
1191 				 */
1192 				if (ep->base.bind_addr.port <
1193 				    inet_prot_sock(net) &&
1194 				    !ns_capable(net->user_ns,
1195 				    CAP_NET_BIND_SERVICE)) {
1196 					err = -EACCES;
1197 					goto out_free;
1198 				}
1199 			}
1200 
1201 			scope = sctp_scope(&to);
1202 			asoc = sctp_association_new(ep, sk, scope, GFP_KERNEL);
1203 			if (!asoc) {
1204 				err = -ENOMEM;
1205 				goto out_free;
1206 			}
1207 
1208 			err = sctp_assoc_set_bind_addr_from_ep(asoc, scope,
1209 							      GFP_KERNEL);
1210 			if (err < 0) {
1211 				goto out_free;
1212 			}
1213 
1214 		}
1215 
1216 		/* Prime the peer's transport structures.  */
1217 		transport = sctp_assoc_add_peer(asoc, &to, GFP_KERNEL,
1218 						SCTP_UNKNOWN);
1219 		if (!transport) {
1220 			err = -ENOMEM;
1221 			goto out_free;
1222 		}
1223 
1224 		addrcnt++;
1225 		addr_buf += af->sockaddr_len;
1226 		walk_size += af->sockaddr_len;
1227 	}
1228 
1229 	/* In case the user of sctp_connectx() wants an association
1230 	 * id back, assign one now.
1231 	 */
1232 	if (assoc_id) {
1233 		err = sctp_assoc_set_id(asoc, GFP_KERNEL);
1234 		if (err < 0)
1235 			goto out_free;
1236 	}
1237 
1238 	err = sctp_primitive_ASSOCIATE(net, asoc, NULL);
1239 	if (err < 0) {
1240 		goto out_free;
1241 	}
1242 
1243 	/* Initialize sk's dport and daddr for getpeername() */
1244 	inet_sk(sk)->inet_dport = htons(asoc->peer.port);
1245 	sp->pf->to_sk_daddr(sa_addr, sk);
1246 	sk->sk_err = 0;
1247 
1248 	/* in-kernel sockets don't generally have a file allocated to them
1249 	 * if all they do is call sock_create_kern().
1250 	 */
1251 	if (sk->sk_socket->file)
1252 		f_flags = sk->sk_socket->file->f_flags;
1253 
1254 	timeo = sock_sndtimeo(sk, f_flags & O_NONBLOCK);
1255 
1256 	if (assoc_id)
1257 		*assoc_id = asoc->assoc_id;
1258 	err = sctp_wait_for_connect(asoc, &timeo);
1259 	/* Note: the asoc may be freed after the return of
1260 	 * sctp_wait_for_connect.
1261 	 */
1262 
1263 	/* Don't free association on exit. */
1264 	asoc = NULL;
1265 
1266 out_free:
1267 	pr_debug("%s: took out_free path with asoc:%p kaddrs:%p err:%d\n",
1268 		 __func__, asoc, kaddrs, err);
1269 
1270 	if (asoc) {
1271 		/* sctp_primitive_ASSOCIATE may have added this association
1272 		 * To the hash table, try to unhash it, just in case, its a noop
1273 		 * if it wasn't hashed so we're safe
1274 		 */
1275 		sctp_association_free(asoc);
1276 	}
1277 	return err;
1278 }
1279 
1280 /* Helper for tunneling sctp_connectx() requests through sctp_setsockopt()
1281  *
1282  * API 8.9
1283  * int sctp_connectx(int sd, struct sockaddr *addrs, int addrcnt,
1284  * 			sctp_assoc_t *asoc);
1285  *
1286  * If sd is an IPv4 socket, the addresses passed must be IPv4 addresses.
1287  * If the sd is an IPv6 socket, the addresses passed can either be IPv4
1288  * or IPv6 addresses.
1289  *
1290  * A single address may be specified as INADDR_ANY or IN6ADDR_ANY, see
1291  * Section 3.1.2 for this usage.
1292  *
1293  * addrs is a pointer to an array of one or more socket addresses. Each
1294  * address is contained in its appropriate structure (i.e. struct
1295  * sockaddr_in or struct sockaddr_in6) the family of the address type
1296  * must be used to distengish the address length (note that this
1297  * representation is termed a "packed array" of addresses). The caller
1298  * specifies the number of addresses in the array with addrcnt.
1299  *
1300  * On success, sctp_connectx() returns 0. It also sets the assoc_id to
1301  * the association id of the new association.  On failure, sctp_connectx()
1302  * returns -1, and sets errno to the appropriate error code.  The assoc_id
1303  * is not touched by the kernel.
1304  *
1305  * For SCTP, the port given in each socket address must be the same, or
1306  * sctp_connectx() will fail, setting errno to EINVAL.
1307  *
1308  * An application can use sctp_connectx to initiate an association with
1309  * an endpoint that is multi-homed.  Much like sctp_bindx() this call
1310  * allows a caller to specify multiple addresses at which a peer can be
1311  * reached.  The way the SCTP stack uses the list of addresses to set up
1312  * the association is implementation dependent.  This function only
1313  * specifies that the stack will try to make use of all the addresses in
1314  * the list when needed.
1315  *
1316  * Note that the list of addresses passed in is only used for setting up
1317  * the association.  It does not necessarily equal the set of addresses
1318  * the peer uses for the resulting association.  If the caller wants to
1319  * find out the set of peer addresses, it must use sctp_getpaddrs() to
1320  * retrieve them after the association has been set up.
1321  *
1322  * Basically do nothing but copying the addresses from user to kernel
1323  * land and invoking either sctp_connectx(). This is used for tunneling
1324  * the sctp_connectx() request through sctp_setsockopt() from userspace.
1325  *
1326  * We don't use copy_from_user() for optimization: we first do the
1327  * sanity checks (buffer size -fast- and access check-healthy
1328  * pointer); if all of those succeed, then we can alloc the memory
1329  * (expensive operation) needed to copy the data to kernel. Then we do
1330  * the copying without checking the user space area
1331  * (__copy_from_user()).
1332  *
1333  * On exit there is no need to do sockfd_put(), sys_setsockopt() does
1334  * it.
1335  *
1336  * sk        The sk of the socket
1337  * addrs     The pointer to the addresses in user land
1338  * addrssize Size of the addrs buffer
1339  *
1340  * Returns >=0 if ok, <0 errno code on error.
1341  */
1342 static int __sctp_setsockopt_connectx(struct sock *sk,
1343 				      struct sockaddr __user *addrs,
1344 				      int addrs_size,
1345 				      sctp_assoc_t *assoc_id)
1346 {
1347 	struct sockaddr *kaddrs;
1348 	gfp_t gfp = GFP_KERNEL;
1349 	int err = 0;
1350 
1351 	pr_debug("%s: sk:%p addrs:%p addrs_size:%d\n",
1352 		 __func__, sk, addrs, addrs_size);
1353 
1354 	if (unlikely(addrs_size <= 0))
1355 		return -EINVAL;
1356 
1357 	/* Check the user passed a healthy pointer.  */
1358 	if (unlikely(!access_ok(VERIFY_READ, addrs, addrs_size)))
1359 		return -EFAULT;
1360 
1361 	/* Alloc space for the address array in kernel memory.  */
1362 	if (sk->sk_socket->file)
1363 		gfp = GFP_USER | __GFP_NOWARN;
1364 	kaddrs = kmalloc(addrs_size, gfp);
1365 	if (unlikely(!kaddrs))
1366 		return -ENOMEM;
1367 
1368 	if (__copy_from_user(kaddrs, addrs, addrs_size)) {
1369 		err = -EFAULT;
1370 	} else {
1371 		err = __sctp_connect(sk, kaddrs, addrs_size, assoc_id);
1372 	}
1373 
1374 	kfree(kaddrs);
1375 
1376 	return err;
1377 }
1378 
1379 /*
1380  * This is an older interface.  It's kept for backward compatibility
1381  * to the option that doesn't provide association id.
1382  */
1383 static int sctp_setsockopt_connectx_old(struct sock *sk,
1384 					struct sockaddr __user *addrs,
1385 					int addrs_size)
1386 {
1387 	return __sctp_setsockopt_connectx(sk, addrs, addrs_size, NULL);
1388 }
1389 
1390 /*
1391  * New interface for the API.  The since the API is done with a socket
1392  * option, to make it simple we feed back the association id is as a return
1393  * indication to the call.  Error is always negative and association id is
1394  * always positive.
1395  */
1396 static int sctp_setsockopt_connectx(struct sock *sk,
1397 				    struct sockaddr __user *addrs,
1398 				    int addrs_size)
1399 {
1400 	sctp_assoc_t assoc_id = 0;
1401 	int err = 0;
1402 
1403 	err = __sctp_setsockopt_connectx(sk, addrs, addrs_size, &assoc_id);
1404 
1405 	if (err)
1406 		return err;
1407 	else
1408 		return assoc_id;
1409 }
1410 
1411 /*
1412  * New (hopefully final) interface for the API.
1413  * We use the sctp_getaddrs_old structure so that use-space library
1414  * can avoid any unnecessary allocations. The only different part
1415  * is that we store the actual length of the address buffer into the
1416  * addrs_num structure member. That way we can re-use the existing
1417  * code.
1418  */
1419 #ifdef CONFIG_COMPAT
1420 struct compat_sctp_getaddrs_old {
1421 	sctp_assoc_t	assoc_id;
1422 	s32		addr_num;
1423 	compat_uptr_t	addrs;		/* struct sockaddr * */
1424 };
1425 #endif
1426 
1427 static int sctp_getsockopt_connectx3(struct sock *sk, int len,
1428 				     char __user *optval,
1429 				     int __user *optlen)
1430 {
1431 	struct sctp_getaddrs_old param;
1432 	sctp_assoc_t assoc_id = 0;
1433 	int err = 0;
1434 
1435 #ifdef CONFIG_COMPAT
1436 	if (in_compat_syscall()) {
1437 		struct compat_sctp_getaddrs_old param32;
1438 
1439 		if (len < sizeof(param32))
1440 			return -EINVAL;
1441 		if (copy_from_user(&param32, optval, sizeof(param32)))
1442 			return -EFAULT;
1443 
1444 		param.assoc_id = param32.assoc_id;
1445 		param.addr_num = param32.addr_num;
1446 		param.addrs = compat_ptr(param32.addrs);
1447 	} else
1448 #endif
1449 	{
1450 		if (len < sizeof(param))
1451 			return -EINVAL;
1452 		if (copy_from_user(&param, optval, sizeof(param)))
1453 			return -EFAULT;
1454 	}
1455 
1456 	err = __sctp_setsockopt_connectx(sk, (struct sockaddr __user *)
1457 					 param.addrs, param.addr_num,
1458 					 &assoc_id);
1459 	if (err == 0 || err == -EINPROGRESS) {
1460 		if (copy_to_user(optval, &assoc_id, sizeof(assoc_id)))
1461 			return -EFAULT;
1462 		if (put_user(sizeof(assoc_id), optlen))
1463 			return -EFAULT;
1464 	}
1465 
1466 	return err;
1467 }
1468 
1469 /* API 3.1.4 close() - UDP Style Syntax
1470  * Applications use close() to perform graceful shutdown (as described in
1471  * Section 10.1 of [SCTP]) on ALL the associations currently represented
1472  * by a UDP-style socket.
1473  *
1474  * The syntax is
1475  *
1476  *   ret = close(int sd);
1477  *
1478  *   sd      - the socket descriptor of the associations to be closed.
1479  *
1480  * To gracefully shutdown a specific association represented by the
1481  * UDP-style socket, an application should use the sendmsg() call,
1482  * passing no user data, but including the appropriate flag in the
1483  * ancillary data (see Section xxxx).
1484  *
1485  * If sd in the close() call is a branched-off socket representing only
1486  * one association, the shutdown is performed on that association only.
1487  *
1488  * 4.1.6 close() - TCP Style Syntax
1489  *
1490  * Applications use close() to gracefully close down an association.
1491  *
1492  * The syntax is:
1493  *
1494  *    int close(int sd);
1495  *
1496  *      sd      - the socket descriptor of the association to be closed.
1497  *
1498  * After an application calls close() on a socket descriptor, no further
1499  * socket operations will succeed on that descriptor.
1500  *
1501  * API 7.1.4 SO_LINGER
1502  *
1503  * An application using the TCP-style socket can use this option to
1504  * perform the SCTP ABORT primitive.  The linger option structure is:
1505  *
1506  *  struct  linger {
1507  *     int     l_onoff;                // option on/off
1508  *     int     l_linger;               // linger time
1509  * };
1510  *
1511  * To enable the option, set l_onoff to 1.  If the l_linger value is set
1512  * to 0, calling close() is the same as the ABORT primitive.  If the
1513  * value is set to a negative value, the setsockopt() call will return
1514  * an error.  If the value is set to a positive value linger_time, the
1515  * close() can be blocked for at most linger_time ms.  If the graceful
1516  * shutdown phase does not finish during this period, close() will
1517  * return but the graceful shutdown phase continues in the system.
1518  */
1519 static void sctp_close(struct sock *sk, long timeout)
1520 {
1521 	struct net *net = sock_net(sk);
1522 	struct sctp_endpoint *ep;
1523 	struct sctp_association *asoc;
1524 	struct list_head *pos, *temp;
1525 	unsigned int data_was_unread;
1526 
1527 	pr_debug("%s: sk:%p, timeout:%ld\n", __func__, sk, timeout);
1528 
1529 	lock_sock_nested(sk, SINGLE_DEPTH_NESTING);
1530 	sk->sk_shutdown = SHUTDOWN_MASK;
1531 	sk->sk_state = SCTP_SS_CLOSING;
1532 
1533 	ep = sctp_sk(sk)->ep;
1534 
1535 	/* Clean up any skbs sitting on the receive queue.  */
1536 	data_was_unread = sctp_queue_purge_ulpevents(&sk->sk_receive_queue);
1537 	data_was_unread += sctp_queue_purge_ulpevents(&sctp_sk(sk)->pd_lobby);
1538 
1539 	/* Walk all associations on an endpoint.  */
1540 	list_for_each_safe(pos, temp, &ep->asocs) {
1541 		asoc = list_entry(pos, struct sctp_association, asocs);
1542 
1543 		if (sctp_style(sk, TCP)) {
1544 			/* A closed association can still be in the list if
1545 			 * it belongs to a TCP-style listening socket that is
1546 			 * not yet accepted. If so, free it. If not, send an
1547 			 * ABORT or SHUTDOWN based on the linger options.
1548 			 */
1549 			if (sctp_state(asoc, CLOSED)) {
1550 				sctp_association_free(asoc);
1551 				continue;
1552 			}
1553 		}
1554 
1555 		if (data_was_unread || !skb_queue_empty(&asoc->ulpq.lobby) ||
1556 		    !skb_queue_empty(&asoc->ulpq.reasm) ||
1557 		    (sock_flag(sk, SOCK_LINGER) && !sk->sk_lingertime)) {
1558 			struct sctp_chunk *chunk;
1559 
1560 			chunk = sctp_make_abort_user(asoc, NULL, 0);
1561 			sctp_primitive_ABORT(net, asoc, chunk);
1562 		} else
1563 			sctp_primitive_SHUTDOWN(net, asoc, NULL);
1564 	}
1565 
1566 	/* On a TCP-style socket, block for at most linger_time if set. */
1567 	if (sctp_style(sk, TCP) && timeout)
1568 		sctp_wait_for_close(sk, timeout);
1569 
1570 	/* This will run the backlog queue.  */
1571 	release_sock(sk);
1572 
1573 	/* Supposedly, no process has access to the socket, but
1574 	 * the net layers still may.
1575 	 * Also, sctp_destroy_sock() needs to be called with addr_wq_lock
1576 	 * held and that should be grabbed before socket lock.
1577 	 */
1578 	spin_lock_bh(&net->sctp.addr_wq_lock);
1579 	bh_lock_sock_nested(sk);
1580 
1581 	/* Hold the sock, since sk_common_release() will put sock_put()
1582 	 * and we have just a little more cleanup.
1583 	 */
1584 	sock_hold(sk);
1585 	sk_common_release(sk);
1586 
1587 	bh_unlock_sock(sk);
1588 	spin_unlock_bh(&net->sctp.addr_wq_lock);
1589 
1590 	sock_put(sk);
1591 
1592 	SCTP_DBG_OBJCNT_DEC(sock);
1593 }
1594 
1595 /* Handle EPIPE error. */
1596 static int sctp_error(struct sock *sk, int flags, int err)
1597 {
1598 	if (err == -EPIPE)
1599 		err = sock_error(sk) ? : -EPIPE;
1600 	if (err == -EPIPE && !(flags & MSG_NOSIGNAL))
1601 		send_sig(SIGPIPE, current, 0);
1602 	return err;
1603 }
1604 
1605 /* API 3.1.3 sendmsg() - UDP Style Syntax
1606  *
1607  * An application uses sendmsg() and recvmsg() calls to transmit data to
1608  * and receive data from its peer.
1609  *
1610  *  ssize_t sendmsg(int socket, const struct msghdr *message,
1611  *                  int flags);
1612  *
1613  *  socket  - the socket descriptor of the endpoint.
1614  *  message - pointer to the msghdr structure which contains a single
1615  *            user message and possibly some ancillary data.
1616  *
1617  *            See Section 5 for complete description of the data
1618  *            structures.
1619  *
1620  *  flags   - flags sent or received with the user message, see Section
1621  *            5 for complete description of the flags.
1622  *
1623  * Note:  This function could use a rewrite especially when explicit
1624  * connect support comes in.
1625  */
1626 /* BUG:  We do not implement the equivalent of sk_stream_wait_memory(). */
1627 
1628 static int sctp_msghdr_parse(const struct msghdr *msg,
1629 			     struct sctp_cmsgs *cmsgs);
1630 
1631 static int sctp_sendmsg(struct sock *sk, struct msghdr *msg, size_t msg_len)
1632 {
1633 	struct net *net = sock_net(sk);
1634 	struct sctp_sock *sp;
1635 	struct sctp_endpoint *ep;
1636 	struct sctp_association *new_asoc = NULL, *asoc = NULL;
1637 	struct sctp_transport *transport, *chunk_tp;
1638 	struct sctp_chunk *chunk;
1639 	union sctp_addr to;
1640 	struct sockaddr *msg_name = NULL;
1641 	struct sctp_sndrcvinfo default_sinfo;
1642 	struct sctp_sndrcvinfo *sinfo;
1643 	struct sctp_initmsg *sinit;
1644 	sctp_assoc_t associd = 0;
1645 	struct sctp_cmsgs cmsgs = { NULL };
1646 	enum sctp_scope scope;
1647 	bool fill_sinfo_ttl = false, wait_connect = false;
1648 	struct sctp_datamsg *datamsg;
1649 	int msg_flags = msg->msg_flags;
1650 	__u16 sinfo_flags = 0;
1651 	long timeo;
1652 	int err;
1653 
1654 	err = 0;
1655 	sp = sctp_sk(sk);
1656 	ep = sp->ep;
1657 
1658 	pr_debug("%s: sk:%p, msg:%p, msg_len:%zu ep:%p\n", __func__, sk,
1659 		 msg, msg_len, ep);
1660 
1661 	/* We cannot send a message over a TCP-style listening socket. */
1662 	if (sctp_style(sk, TCP) && sctp_sstate(sk, LISTENING)) {
1663 		err = -EPIPE;
1664 		goto out_nounlock;
1665 	}
1666 
1667 	/* Parse out the SCTP CMSGs.  */
1668 	err = sctp_msghdr_parse(msg, &cmsgs);
1669 	if (err) {
1670 		pr_debug("%s: msghdr parse err:%x\n", __func__, err);
1671 		goto out_nounlock;
1672 	}
1673 
1674 	/* Fetch the destination address for this packet.  This
1675 	 * address only selects the association--it is not necessarily
1676 	 * the address we will send to.
1677 	 * For a peeled-off socket, msg_name is ignored.
1678 	 */
1679 	if (!sctp_style(sk, UDP_HIGH_BANDWIDTH) && msg->msg_name) {
1680 		int msg_namelen = msg->msg_namelen;
1681 
1682 		err = sctp_verify_addr(sk, (union sctp_addr *)msg->msg_name,
1683 				       msg_namelen);
1684 		if (err)
1685 			return err;
1686 
1687 		if (msg_namelen > sizeof(to))
1688 			msg_namelen = sizeof(to);
1689 		memcpy(&to, msg->msg_name, msg_namelen);
1690 		msg_name = msg->msg_name;
1691 	}
1692 
1693 	sinit = cmsgs.init;
1694 	if (cmsgs.sinfo != NULL) {
1695 		memset(&default_sinfo, 0, sizeof(default_sinfo));
1696 		default_sinfo.sinfo_stream = cmsgs.sinfo->snd_sid;
1697 		default_sinfo.sinfo_flags = cmsgs.sinfo->snd_flags;
1698 		default_sinfo.sinfo_ppid = cmsgs.sinfo->snd_ppid;
1699 		default_sinfo.sinfo_context = cmsgs.sinfo->snd_context;
1700 		default_sinfo.sinfo_assoc_id = cmsgs.sinfo->snd_assoc_id;
1701 
1702 		sinfo = &default_sinfo;
1703 		fill_sinfo_ttl = true;
1704 	} else {
1705 		sinfo = cmsgs.srinfo;
1706 	}
1707 	/* Did the user specify SNDINFO/SNDRCVINFO? */
1708 	if (sinfo) {
1709 		sinfo_flags = sinfo->sinfo_flags;
1710 		associd = sinfo->sinfo_assoc_id;
1711 	}
1712 
1713 	pr_debug("%s: msg_len:%zu, sinfo_flags:0x%x\n", __func__,
1714 		 msg_len, sinfo_flags);
1715 
1716 	/* SCTP_EOF or SCTP_ABORT cannot be set on a TCP-style socket. */
1717 	if (sctp_style(sk, TCP) && (sinfo_flags & (SCTP_EOF | SCTP_ABORT))) {
1718 		err = -EINVAL;
1719 		goto out_nounlock;
1720 	}
1721 
1722 	/* If SCTP_EOF is set, no data can be sent. Disallow sending zero
1723 	 * length messages when SCTP_EOF|SCTP_ABORT is not set.
1724 	 * If SCTP_ABORT is set, the message length could be non zero with
1725 	 * the msg_iov set to the user abort reason.
1726 	 */
1727 	if (((sinfo_flags & SCTP_EOF) && (msg_len > 0)) ||
1728 	    (!(sinfo_flags & (SCTP_EOF|SCTP_ABORT)) && (msg_len == 0))) {
1729 		err = -EINVAL;
1730 		goto out_nounlock;
1731 	}
1732 
1733 	/* If SCTP_ADDR_OVER is set, there must be an address
1734 	 * specified in msg_name.
1735 	 */
1736 	if ((sinfo_flags & SCTP_ADDR_OVER) && (!msg->msg_name)) {
1737 		err = -EINVAL;
1738 		goto out_nounlock;
1739 	}
1740 
1741 	transport = NULL;
1742 
1743 	pr_debug("%s: about to look up association\n", __func__);
1744 
1745 	lock_sock(sk);
1746 
1747 	/* If a msg_name has been specified, assume this is to be used.  */
1748 	if (msg_name) {
1749 		/* Look for a matching association on the endpoint. */
1750 		asoc = sctp_endpoint_lookup_assoc(ep, &to, &transport);
1751 
1752 		/* If we could not find a matching association on the
1753 		 * endpoint, make sure that it is not a TCP-style
1754 		 * socket that already has an association or there is
1755 		 * no peeled-off association on another socket.
1756 		 */
1757 		if (!asoc &&
1758 		    ((sctp_style(sk, TCP) &&
1759 		      (sctp_sstate(sk, ESTABLISHED) ||
1760 		       sctp_sstate(sk, CLOSING))) ||
1761 		     sctp_endpoint_is_peeled_off(ep, &to))) {
1762 			err = -EADDRNOTAVAIL;
1763 			goto out_unlock;
1764 		}
1765 	} else {
1766 		asoc = sctp_id2assoc(sk, associd);
1767 		if (!asoc) {
1768 			err = -EPIPE;
1769 			goto out_unlock;
1770 		}
1771 	}
1772 
1773 	if (asoc) {
1774 		pr_debug("%s: just looked up association:%p\n", __func__, asoc);
1775 
1776 		/* We cannot send a message on a TCP-style SCTP_SS_ESTABLISHED
1777 		 * socket that has an association in CLOSED state. This can
1778 		 * happen when an accepted socket has an association that is
1779 		 * already CLOSED.
1780 		 */
1781 		if (sctp_state(asoc, CLOSED) && sctp_style(sk, TCP)) {
1782 			err = -EPIPE;
1783 			goto out_unlock;
1784 		}
1785 
1786 		if (sinfo_flags & SCTP_EOF) {
1787 			pr_debug("%s: shutting down association:%p\n",
1788 				 __func__, asoc);
1789 
1790 			sctp_primitive_SHUTDOWN(net, asoc, NULL);
1791 			err = 0;
1792 			goto out_unlock;
1793 		}
1794 		if (sinfo_flags & SCTP_ABORT) {
1795 
1796 			chunk = sctp_make_abort_user(asoc, msg, msg_len);
1797 			if (!chunk) {
1798 				err = -ENOMEM;
1799 				goto out_unlock;
1800 			}
1801 
1802 			pr_debug("%s: aborting association:%p\n",
1803 				 __func__, asoc);
1804 
1805 			sctp_primitive_ABORT(net, asoc, chunk);
1806 			err = 0;
1807 			goto out_unlock;
1808 		}
1809 	}
1810 
1811 	/* Do we need to create the association?  */
1812 	if (!asoc) {
1813 		pr_debug("%s: there is no association yet\n", __func__);
1814 
1815 		if (sinfo_flags & (SCTP_EOF | SCTP_ABORT)) {
1816 			err = -EINVAL;
1817 			goto out_unlock;
1818 		}
1819 
1820 		/* Check for invalid stream against the stream counts,
1821 		 * either the default or the user specified stream counts.
1822 		 */
1823 		if (sinfo) {
1824 			if (!sinit || !sinit->sinit_num_ostreams) {
1825 				/* Check against the defaults. */
1826 				if (sinfo->sinfo_stream >=
1827 				    sp->initmsg.sinit_num_ostreams) {
1828 					err = -EINVAL;
1829 					goto out_unlock;
1830 				}
1831 			} else {
1832 				/* Check against the requested.  */
1833 				if (sinfo->sinfo_stream >=
1834 				    sinit->sinit_num_ostreams) {
1835 					err = -EINVAL;
1836 					goto out_unlock;
1837 				}
1838 			}
1839 		}
1840 
1841 		/*
1842 		 * API 3.1.2 bind() - UDP Style Syntax
1843 		 * If a bind() or sctp_bindx() is not called prior to a
1844 		 * sendmsg() call that initiates a new association, the
1845 		 * system picks an ephemeral port and will choose an address
1846 		 * set equivalent to binding with a wildcard address.
1847 		 */
1848 		if (!ep->base.bind_addr.port) {
1849 			if (sctp_autobind(sk)) {
1850 				err = -EAGAIN;
1851 				goto out_unlock;
1852 			}
1853 		} else {
1854 			/*
1855 			 * If an unprivileged user inherits a one-to-many
1856 			 * style socket with open associations on a privileged
1857 			 * port, it MAY be permitted to accept new associations,
1858 			 * but it SHOULD NOT be permitted to open new
1859 			 * associations.
1860 			 */
1861 			if (ep->base.bind_addr.port < inet_prot_sock(net) &&
1862 			    !ns_capable(net->user_ns, CAP_NET_BIND_SERVICE)) {
1863 				err = -EACCES;
1864 				goto out_unlock;
1865 			}
1866 		}
1867 
1868 		scope = sctp_scope(&to);
1869 		new_asoc = sctp_association_new(ep, sk, scope, GFP_KERNEL);
1870 		if (!new_asoc) {
1871 			err = -ENOMEM;
1872 			goto out_unlock;
1873 		}
1874 		asoc = new_asoc;
1875 		err = sctp_assoc_set_bind_addr_from_ep(asoc, scope, GFP_KERNEL);
1876 		if (err < 0) {
1877 			err = -ENOMEM;
1878 			goto out_free;
1879 		}
1880 
1881 		/* If the SCTP_INIT ancillary data is specified, set all
1882 		 * the association init values accordingly.
1883 		 */
1884 		if (sinit) {
1885 			if (sinit->sinit_num_ostreams) {
1886 				asoc->c.sinit_num_ostreams =
1887 					sinit->sinit_num_ostreams;
1888 			}
1889 			if (sinit->sinit_max_instreams) {
1890 				asoc->c.sinit_max_instreams =
1891 					sinit->sinit_max_instreams;
1892 			}
1893 			if (sinit->sinit_max_attempts) {
1894 				asoc->max_init_attempts
1895 					= sinit->sinit_max_attempts;
1896 			}
1897 			if (sinit->sinit_max_init_timeo) {
1898 				asoc->max_init_timeo =
1899 				 msecs_to_jiffies(sinit->sinit_max_init_timeo);
1900 			}
1901 		}
1902 
1903 		/* Prime the peer's transport structures.  */
1904 		transport = sctp_assoc_add_peer(asoc, &to, GFP_KERNEL, SCTP_UNKNOWN);
1905 		if (!transport) {
1906 			err = -ENOMEM;
1907 			goto out_free;
1908 		}
1909 	}
1910 
1911 	/* ASSERT: we have a valid association at this point.  */
1912 	pr_debug("%s: we have a valid association\n", __func__);
1913 
1914 	if (!sinfo) {
1915 		/* If the user didn't specify SNDINFO/SNDRCVINFO, make up
1916 		 * one with some defaults.
1917 		 */
1918 		memset(&default_sinfo, 0, sizeof(default_sinfo));
1919 		default_sinfo.sinfo_stream = asoc->default_stream;
1920 		default_sinfo.sinfo_flags = asoc->default_flags;
1921 		default_sinfo.sinfo_ppid = asoc->default_ppid;
1922 		default_sinfo.sinfo_context = asoc->default_context;
1923 		default_sinfo.sinfo_timetolive = asoc->default_timetolive;
1924 		default_sinfo.sinfo_assoc_id = sctp_assoc2id(asoc);
1925 
1926 		sinfo = &default_sinfo;
1927 	} else if (fill_sinfo_ttl) {
1928 		/* In case SNDINFO was specified, we still need to fill
1929 		 * it with a default ttl from the assoc here.
1930 		 */
1931 		sinfo->sinfo_timetolive = asoc->default_timetolive;
1932 	}
1933 
1934 	/* API 7.1.7, the sndbuf size per association bounds the
1935 	 * maximum size of data that can be sent in a single send call.
1936 	 */
1937 	if (msg_len > sk->sk_sndbuf) {
1938 		err = -EMSGSIZE;
1939 		goto out_free;
1940 	}
1941 
1942 	if (asoc->pmtu_pending)
1943 		sctp_assoc_pending_pmtu(asoc);
1944 
1945 	/* If fragmentation is disabled and the message length exceeds the
1946 	 * association fragmentation point, return EMSGSIZE.  The I-D
1947 	 * does not specify what this error is, but this looks like
1948 	 * a great fit.
1949 	 */
1950 	if (sctp_sk(sk)->disable_fragments && (msg_len > asoc->frag_point)) {
1951 		err = -EMSGSIZE;
1952 		goto out_free;
1953 	}
1954 
1955 	/* Check for invalid stream. */
1956 	if (sinfo->sinfo_stream >= asoc->stream.outcnt) {
1957 		err = -EINVAL;
1958 		goto out_free;
1959 	}
1960 
1961 	/* Allocate sctp_stream_out_ext if not already done */
1962 	if (unlikely(!asoc->stream.out[sinfo->sinfo_stream].ext)) {
1963 		err = sctp_stream_init_ext(&asoc->stream, sinfo->sinfo_stream);
1964 		if (err)
1965 			goto out_free;
1966 	}
1967 
1968 	if (sctp_wspace(asoc) < msg_len)
1969 		sctp_prsctp_prune(asoc, sinfo, msg_len - sctp_wspace(asoc));
1970 
1971 	timeo = sock_sndtimeo(sk, msg->msg_flags & MSG_DONTWAIT);
1972 	if (!sctp_wspace(asoc)) {
1973 		/* sk can be changed by peel off when waiting for buf. */
1974 		err = sctp_wait_for_sndbuf(asoc, &timeo, msg_len, &sk);
1975 		if (err) {
1976 			if (err == -ESRCH) {
1977 				/* asoc is already dead. */
1978 				new_asoc = NULL;
1979 				err = -EPIPE;
1980 			}
1981 			goto out_free;
1982 		}
1983 	}
1984 
1985 	/* If an address is passed with the sendto/sendmsg call, it is used
1986 	 * to override the primary destination address in the TCP model, or
1987 	 * when SCTP_ADDR_OVER flag is set in the UDP model.
1988 	 */
1989 	if ((sctp_style(sk, TCP) && msg_name) ||
1990 	    (sinfo_flags & SCTP_ADDR_OVER)) {
1991 		chunk_tp = sctp_assoc_lookup_paddr(asoc, &to);
1992 		if (!chunk_tp) {
1993 			err = -EINVAL;
1994 			goto out_free;
1995 		}
1996 	} else
1997 		chunk_tp = NULL;
1998 
1999 	/* Auto-connect, if we aren't connected already. */
2000 	if (sctp_state(asoc, CLOSED)) {
2001 		err = sctp_primitive_ASSOCIATE(net, asoc, NULL);
2002 		if (err < 0)
2003 			goto out_free;
2004 
2005 		wait_connect = true;
2006 		pr_debug("%s: we associated primitively\n", __func__);
2007 	}
2008 
2009 	/* Break the message into multiple chunks of maximum size. */
2010 	datamsg = sctp_datamsg_from_user(asoc, sinfo, &msg->msg_iter);
2011 	if (IS_ERR(datamsg)) {
2012 		err = PTR_ERR(datamsg);
2013 		goto out_free;
2014 	}
2015 	asoc->force_delay = !!(msg->msg_flags & MSG_MORE);
2016 
2017 	/* Now send the (possibly) fragmented message. */
2018 	list_for_each_entry(chunk, &datamsg->chunks, frag_list) {
2019 		sctp_chunk_hold(chunk);
2020 
2021 		/* Do accounting for the write space.  */
2022 		sctp_set_owner_w(chunk);
2023 
2024 		chunk->transport = chunk_tp;
2025 	}
2026 
2027 	/* Send it to the lower layers.  Note:  all chunks
2028 	 * must either fail or succeed.   The lower layer
2029 	 * works that way today.  Keep it that way or this
2030 	 * breaks.
2031 	 */
2032 	err = sctp_primitive_SEND(net, asoc, datamsg);
2033 	/* Did the lower layer accept the chunk? */
2034 	if (err) {
2035 		sctp_datamsg_free(datamsg);
2036 		goto out_free;
2037 	}
2038 
2039 	pr_debug("%s: we sent primitively\n", __func__);
2040 
2041 	sctp_datamsg_put(datamsg);
2042 	err = msg_len;
2043 
2044 	if (unlikely(wait_connect)) {
2045 		timeo = sock_sndtimeo(sk, msg_flags & MSG_DONTWAIT);
2046 		sctp_wait_for_connect(asoc, &timeo);
2047 	}
2048 
2049 	/* If we are already past ASSOCIATE, the lower
2050 	 * layers are responsible for association cleanup.
2051 	 */
2052 	goto out_unlock;
2053 
2054 out_free:
2055 	if (new_asoc)
2056 		sctp_association_free(asoc);
2057 out_unlock:
2058 	release_sock(sk);
2059 
2060 out_nounlock:
2061 	return sctp_error(sk, msg_flags, err);
2062 
2063 #if 0
2064 do_sock_err:
2065 	if (msg_len)
2066 		err = msg_len;
2067 	else
2068 		err = sock_error(sk);
2069 	goto out;
2070 
2071 do_interrupted:
2072 	if (msg_len)
2073 		err = msg_len;
2074 	goto out;
2075 #endif /* 0 */
2076 }
2077 
2078 /* This is an extended version of skb_pull() that removes the data from the
2079  * start of a skb even when data is spread across the list of skb's in the
2080  * frag_list. len specifies the total amount of data that needs to be removed.
2081  * when 'len' bytes could be removed from the skb, it returns 0.
2082  * If 'len' exceeds the total skb length,  it returns the no. of bytes that
2083  * could not be removed.
2084  */
2085 static int sctp_skb_pull(struct sk_buff *skb, int len)
2086 {
2087 	struct sk_buff *list;
2088 	int skb_len = skb_headlen(skb);
2089 	int rlen;
2090 
2091 	if (len <= skb_len) {
2092 		__skb_pull(skb, len);
2093 		return 0;
2094 	}
2095 	len -= skb_len;
2096 	__skb_pull(skb, skb_len);
2097 
2098 	skb_walk_frags(skb, list) {
2099 		rlen = sctp_skb_pull(list, len);
2100 		skb->len -= (len-rlen);
2101 		skb->data_len -= (len-rlen);
2102 
2103 		if (!rlen)
2104 			return 0;
2105 
2106 		len = rlen;
2107 	}
2108 
2109 	return len;
2110 }
2111 
2112 /* API 3.1.3  recvmsg() - UDP Style Syntax
2113  *
2114  *  ssize_t recvmsg(int socket, struct msghdr *message,
2115  *                    int flags);
2116  *
2117  *  socket  - the socket descriptor of the endpoint.
2118  *  message - pointer to the msghdr structure which contains a single
2119  *            user message and possibly some ancillary data.
2120  *
2121  *            See Section 5 for complete description of the data
2122  *            structures.
2123  *
2124  *  flags   - flags sent or received with the user message, see Section
2125  *            5 for complete description of the flags.
2126  */
2127 static int sctp_recvmsg(struct sock *sk, struct msghdr *msg, size_t len,
2128 			int noblock, int flags, int *addr_len)
2129 {
2130 	struct sctp_ulpevent *event = NULL;
2131 	struct sctp_sock *sp = sctp_sk(sk);
2132 	struct sk_buff *skb, *head_skb;
2133 	int copied;
2134 	int err = 0;
2135 	int skb_len;
2136 
2137 	pr_debug("%s: sk:%p, msghdr:%p, len:%zd, noblock:%d, flags:0x%x, "
2138 		 "addr_len:%p)\n", __func__, sk, msg, len, noblock, flags,
2139 		 addr_len);
2140 
2141 	lock_sock(sk);
2142 
2143 	if (sctp_style(sk, TCP) && !sctp_sstate(sk, ESTABLISHED) &&
2144 	    !sctp_sstate(sk, CLOSING) && !sctp_sstate(sk, CLOSED)) {
2145 		err = -ENOTCONN;
2146 		goto out;
2147 	}
2148 
2149 	skb = sctp_skb_recv_datagram(sk, flags, noblock, &err);
2150 	if (!skb)
2151 		goto out;
2152 
2153 	/* Get the total length of the skb including any skb's in the
2154 	 * frag_list.
2155 	 */
2156 	skb_len = skb->len;
2157 
2158 	copied = skb_len;
2159 	if (copied > len)
2160 		copied = len;
2161 
2162 	err = skb_copy_datagram_msg(skb, 0, msg, copied);
2163 
2164 	event = sctp_skb2event(skb);
2165 
2166 	if (err)
2167 		goto out_free;
2168 
2169 	if (event->chunk && event->chunk->head_skb)
2170 		head_skb = event->chunk->head_skb;
2171 	else
2172 		head_skb = skb;
2173 	sock_recv_ts_and_drops(msg, sk, head_skb);
2174 	if (sctp_ulpevent_is_notification(event)) {
2175 		msg->msg_flags |= MSG_NOTIFICATION;
2176 		sp->pf->event_msgname(event, msg->msg_name, addr_len);
2177 	} else {
2178 		sp->pf->skb_msgname(head_skb, msg->msg_name, addr_len);
2179 	}
2180 
2181 	/* Check if we allow SCTP_NXTINFO. */
2182 	if (sp->recvnxtinfo)
2183 		sctp_ulpevent_read_nxtinfo(event, msg, sk);
2184 	/* Check if we allow SCTP_RCVINFO. */
2185 	if (sp->recvrcvinfo)
2186 		sctp_ulpevent_read_rcvinfo(event, msg);
2187 	/* Check if we allow SCTP_SNDRCVINFO. */
2188 	if (sp->subscribe.sctp_data_io_event)
2189 		sctp_ulpevent_read_sndrcvinfo(event, msg);
2190 
2191 	err = copied;
2192 
2193 	/* If skb's length exceeds the user's buffer, update the skb and
2194 	 * push it back to the receive_queue so that the next call to
2195 	 * recvmsg() will return the remaining data. Don't set MSG_EOR.
2196 	 */
2197 	if (skb_len > copied) {
2198 		msg->msg_flags &= ~MSG_EOR;
2199 		if (flags & MSG_PEEK)
2200 			goto out_free;
2201 		sctp_skb_pull(skb, copied);
2202 		skb_queue_head(&sk->sk_receive_queue, skb);
2203 
2204 		/* When only partial message is copied to the user, increase
2205 		 * rwnd by that amount. If all the data in the skb is read,
2206 		 * rwnd is updated when the event is freed.
2207 		 */
2208 		if (!sctp_ulpevent_is_notification(event))
2209 			sctp_assoc_rwnd_increase(event->asoc, copied);
2210 		goto out;
2211 	} else if ((event->msg_flags & MSG_NOTIFICATION) ||
2212 		   (event->msg_flags & MSG_EOR))
2213 		msg->msg_flags |= MSG_EOR;
2214 	else
2215 		msg->msg_flags &= ~MSG_EOR;
2216 
2217 out_free:
2218 	if (flags & MSG_PEEK) {
2219 		/* Release the skb reference acquired after peeking the skb in
2220 		 * sctp_skb_recv_datagram().
2221 		 */
2222 		kfree_skb(skb);
2223 	} else {
2224 		/* Free the event which includes releasing the reference to
2225 		 * the owner of the skb, freeing the skb and updating the
2226 		 * rwnd.
2227 		 */
2228 		sctp_ulpevent_free(event);
2229 	}
2230 out:
2231 	release_sock(sk);
2232 	return err;
2233 }
2234 
2235 /* 7.1.12 Enable/Disable message fragmentation (SCTP_DISABLE_FRAGMENTS)
2236  *
2237  * This option is a on/off flag.  If enabled no SCTP message
2238  * fragmentation will be performed.  Instead if a message being sent
2239  * exceeds the current PMTU size, the message will NOT be sent and
2240  * instead a error will be indicated to the user.
2241  */
2242 static int sctp_setsockopt_disable_fragments(struct sock *sk,
2243 					     char __user *optval,
2244 					     unsigned int optlen)
2245 {
2246 	int val;
2247 
2248 	if (optlen < sizeof(int))
2249 		return -EINVAL;
2250 
2251 	if (get_user(val, (int __user *)optval))
2252 		return -EFAULT;
2253 
2254 	sctp_sk(sk)->disable_fragments = (val == 0) ? 0 : 1;
2255 
2256 	return 0;
2257 }
2258 
2259 static int sctp_setsockopt_events(struct sock *sk, char __user *optval,
2260 				  unsigned int optlen)
2261 {
2262 	struct sctp_association *asoc;
2263 	struct sctp_ulpevent *event;
2264 
2265 	if (optlen > sizeof(struct sctp_event_subscribe))
2266 		return -EINVAL;
2267 	if (copy_from_user(&sctp_sk(sk)->subscribe, optval, optlen))
2268 		return -EFAULT;
2269 
2270 	/* At the time when a user app subscribes to SCTP_SENDER_DRY_EVENT,
2271 	 * if there is no data to be sent or retransmit, the stack will
2272 	 * immediately send up this notification.
2273 	 */
2274 	if (sctp_ulpevent_type_enabled(SCTP_SENDER_DRY_EVENT,
2275 				       &sctp_sk(sk)->subscribe)) {
2276 		asoc = sctp_id2assoc(sk, 0);
2277 
2278 		if (asoc && sctp_outq_is_empty(&asoc->outqueue)) {
2279 			event = sctp_ulpevent_make_sender_dry_event(asoc,
2280 					GFP_ATOMIC);
2281 			if (!event)
2282 				return -ENOMEM;
2283 
2284 			sctp_ulpq_tail_event(&asoc->ulpq, event);
2285 		}
2286 	}
2287 
2288 	return 0;
2289 }
2290 
2291 /* 7.1.8 Automatic Close of associations (SCTP_AUTOCLOSE)
2292  *
2293  * This socket option is applicable to the UDP-style socket only.  When
2294  * set it will cause associations that are idle for more than the
2295  * specified number of seconds to automatically close.  An association
2296  * being idle is defined an association that has NOT sent or received
2297  * user data.  The special value of '0' indicates that no automatic
2298  * close of any associations should be performed.  The option expects an
2299  * integer defining the number of seconds of idle time before an
2300  * association is closed.
2301  */
2302 static int sctp_setsockopt_autoclose(struct sock *sk, char __user *optval,
2303 				     unsigned int optlen)
2304 {
2305 	struct sctp_sock *sp = sctp_sk(sk);
2306 	struct net *net = sock_net(sk);
2307 
2308 	/* Applicable to UDP-style socket only */
2309 	if (sctp_style(sk, TCP))
2310 		return -EOPNOTSUPP;
2311 	if (optlen != sizeof(int))
2312 		return -EINVAL;
2313 	if (copy_from_user(&sp->autoclose, optval, optlen))
2314 		return -EFAULT;
2315 
2316 	if (sp->autoclose > net->sctp.max_autoclose)
2317 		sp->autoclose = net->sctp.max_autoclose;
2318 
2319 	return 0;
2320 }
2321 
2322 /* 7.1.13 Peer Address Parameters (SCTP_PEER_ADDR_PARAMS)
2323  *
2324  * Applications can enable or disable heartbeats for any peer address of
2325  * an association, modify an address's heartbeat interval, force a
2326  * heartbeat to be sent immediately, and adjust the address's maximum
2327  * number of retransmissions sent before an address is considered
2328  * unreachable.  The following structure is used to access and modify an
2329  * address's parameters:
2330  *
2331  *  struct sctp_paddrparams {
2332  *     sctp_assoc_t            spp_assoc_id;
2333  *     struct sockaddr_storage spp_address;
2334  *     uint32_t                spp_hbinterval;
2335  *     uint16_t                spp_pathmaxrxt;
2336  *     uint32_t                spp_pathmtu;
2337  *     uint32_t                spp_sackdelay;
2338  *     uint32_t                spp_flags;
2339  * };
2340  *
2341  *   spp_assoc_id    - (one-to-many style socket) This is filled in the
2342  *                     application, and identifies the association for
2343  *                     this query.
2344  *   spp_address     - This specifies which address is of interest.
2345  *   spp_hbinterval  - This contains the value of the heartbeat interval,
2346  *                     in milliseconds.  If a  value of zero
2347  *                     is present in this field then no changes are to
2348  *                     be made to this parameter.
2349  *   spp_pathmaxrxt  - This contains the maximum number of
2350  *                     retransmissions before this address shall be
2351  *                     considered unreachable. If a  value of zero
2352  *                     is present in this field then no changes are to
2353  *                     be made to this parameter.
2354  *   spp_pathmtu     - When Path MTU discovery is disabled the value
2355  *                     specified here will be the "fixed" path mtu.
2356  *                     Note that if the spp_address field is empty
2357  *                     then all associations on this address will
2358  *                     have this fixed path mtu set upon them.
2359  *
2360  *   spp_sackdelay   - When delayed sack is enabled, this value specifies
2361  *                     the number of milliseconds that sacks will be delayed
2362  *                     for. This value will apply to all addresses of an
2363  *                     association if the spp_address field is empty. Note
2364  *                     also, that if delayed sack is enabled and this
2365  *                     value is set to 0, no change is made to the last
2366  *                     recorded delayed sack timer value.
2367  *
2368  *   spp_flags       - These flags are used to control various features
2369  *                     on an association. The flag field may contain
2370  *                     zero or more of the following options.
2371  *
2372  *                     SPP_HB_ENABLE  - Enable heartbeats on the
2373  *                     specified address. Note that if the address
2374  *                     field is empty all addresses for the association
2375  *                     have heartbeats enabled upon them.
2376  *
2377  *                     SPP_HB_DISABLE - Disable heartbeats on the
2378  *                     speicifed address. Note that if the address
2379  *                     field is empty all addresses for the association
2380  *                     will have their heartbeats disabled. Note also
2381  *                     that SPP_HB_ENABLE and SPP_HB_DISABLE are
2382  *                     mutually exclusive, only one of these two should
2383  *                     be specified. Enabling both fields will have
2384  *                     undetermined results.
2385  *
2386  *                     SPP_HB_DEMAND - Request a user initiated heartbeat
2387  *                     to be made immediately.
2388  *
2389  *                     SPP_HB_TIME_IS_ZERO - Specify's that the time for
2390  *                     heartbeat delayis to be set to the value of 0
2391  *                     milliseconds.
2392  *
2393  *                     SPP_PMTUD_ENABLE - This field will enable PMTU
2394  *                     discovery upon the specified address. Note that
2395  *                     if the address feild is empty then all addresses
2396  *                     on the association are effected.
2397  *
2398  *                     SPP_PMTUD_DISABLE - This field will disable PMTU
2399  *                     discovery upon the specified address. Note that
2400  *                     if the address feild is empty then all addresses
2401  *                     on the association are effected. Not also that
2402  *                     SPP_PMTUD_ENABLE and SPP_PMTUD_DISABLE are mutually
2403  *                     exclusive. Enabling both will have undetermined
2404  *                     results.
2405  *
2406  *                     SPP_SACKDELAY_ENABLE - Setting this flag turns
2407  *                     on delayed sack. The time specified in spp_sackdelay
2408  *                     is used to specify the sack delay for this address. Note
2409  *                     that if spp_address is empty then all addresses will
2410  *                     enable delayed sack and take on the sack delay
2411  *                     value specified in spp_sackdelay.
2412  *                     SPP_SACKDELAY_DISABLE - Setting this flag turns
2413  *                     off delayed sack. If the spp_address field is blank then
2414  *                     delayed sack is disabled for the entire association. Note
2415  *                     also that this field is mutually exclusive to
2416  *                     SPP_SACKDELAY_ENABLE, setting both will have undefined
2417  *                     results.
2418  */
2419 static int sctp_apply_peer_addr_params(struct sctp_paddrparams *params,
2420 				       struct sctp_transport   *trans,
2421 				       struct sctp_association *asoc,
2422 				       struct sctp_sock        *sp,
2423 				       int                      hb_change,
2424 				       int                      pmtud_change,
2425 				       int                      sackdelay_change)
2426 {
2427 	int error;
2428 
2429 	if (params->spp_flags & SPP_HB_DEMAND && trans) {
2430 		struct net *net = sock_net(trans->asoc->base.sk);
2431 
2432 		error = sctp_primitive_REQUESTHEARTBEAT(net, trans->asoc, trans);
2433 		if (error)
2434 			return error;
2435 	}
2436 
2437 	/* Note that unless the spp_flag is set to SPP_HB_ENABLE the value of
2438 	 * this field is ignored.  Note also that a value of zero indicates
2439 	 * the current setting should be left unchanged.
2440 	 */
2441 	if (params->spp_flags & SPP_HB_ENABLE) {
2442 
2443 		/* Re-zero the interval if the SPP_HB_TIME_IS_ZERO is
2444 		 * set.  This lets us use 0 value when this flag
2445 		 * is set.
2446 		 */
2447 		if (params->spp_flags & SPP_HB_TIME_IS_ZERO)
2448 			params->spp_hbinterval = 0;
2449 
2450 		if (params->spp_hbinterval ||
2451 		    (params->spp_flags & SPP_HB_TIME_IS_ZERO)) {
2452 			if (trans) {
2453 				trans->hbinterval =
2454 				    msecs_to_jiffies(params->spp_hbinterval);
2455 			} else if (asoc) {
2456 				asoc->hbinterval =
2457 				    msecs_to_jiffies(params->spp_hbinterval);
2458 			} else {
2459 				sp->hbinterval = params->spp_hbinterval;
2460 			}
2461 		}
2462 	}
2463 
2464 	if (hb_change) {
2465 		if (trans) {
2466 			trans->param_flags =
2467 				(trans->param_flags & ~SPP_HB) | hb_change;
2468 		} else if (asoc) {
2469 			asoc->param_flags =
2470 				(asoc->param_flags & ~SPP_HB) | hb_change;
2471 		} else {
2472 			sp->param_flags =
2473 				(sp->param_flags & ~SPP_HB) | hb_change;
2474 		}
2475 	}
2476 
2477 	/* When Path MTU discovery is disabled the value specified here will
2478 	 * be the "fixed" path mtu (i.e. the value of the spp_flags field must
2479 	 * include the flag SPP_PMTUD_DISABLE for this field to have any
2480 	 * effect).
2481 	 */
2482 	if ((params->spp_flags & SPP_PMTUD_DISABLE) && params->spp_pathmtu) {
2483 		if (trans) {
2484 			trans->pathmtu = params->spp_pathmtu;
2485 			sctp_assoc_sync_pmtu(asoc);
2486 		} else if (asoc) {
2487 			asoc->pathmtu = params->spp_pathmtu;
2488 		} else {
2489 			sp->pathmtu = params->spp_pathmtu;
2490 		}
2491 	}
2492 
2493 	if (pmtud_change) {
2494 		if (trans) {
2495 			int update = (trans->param_flags & SPP_PMTUD_DISABLE) &&
2496 				(params->spp_flags & SPP_PMTUD_ENABLE);
2497 			trans->param_flags =
2498 				(trans->param_flags & ~SPP_PMTUD) | pmtud_change;
2499 			if (update) {
2500 				sctp_transport_pmtu(trans, sctp_opt2sk(sp));
2501 				sctp_assoc_sync_pmtu(asoc);
2502 			}
2503 		} else if (asoc) {
2504 			asoc->param_flags =
2505 				(asoc->param_flags & ~SPP_PMTUD) | pmtud_change;
2506 		} else {
2507 			sp->param_flags =
2508 				(sp->param_flags & ~SPP_PMTUD) | pmtud_change;
2509 		}
2510 	}
2511 
2512 	/* Note that unless the spp_flag is set to SPP_SACKDELAY_ENABLE the
2513 	 * value of this field is ignored.  Note also that a value of zero
2514 	 * indicates the current setting should be left unchanged.
2515 	 */
2516 	if ((params->spp_flags & SPP_SACKDELAY_ENABLE) && params->spp_sackdelay) {
2517 		if (trans) {
2518 			trans->sackdelay =
2519 				msecs_to_jiffies(params->spp_sackdelay);
2520 		} else if (asoc) {
2521 			asoc->sackdelay =
2522 				msecs_to_jiffies(params->spp_sackdelay);
2523 		} else {
2524 			sp->sackdelay = params->spp_sackdelay;
2525 		}
2526 	}
2527 
2528 	if (sackdelay_change) {
2529 		if (trans) {
2530 			trans->param_flags =
2531 				(trans->param_flags & ~SPP_SACKDELAY) |
2532 				sackdelay_change;
2533 		} else if (asoc) {
2534 			asoc->param_flags =
2535 				(asoc->param_flags & ~SPP_SACKDELAY) |
2536 				sackdelay_change;
2537 		} else {
2538 			sp->param_flags =
2539 				(sp->param_flags & ~SPP_SACKDELAY) |
2540 				sackdelay_change;
2541 		}
2542 	}
2543 
2544 	/* Note that a value of zero indicates the current setting should be
2545 	   left unchanged.
2546 	 */
2547 	if (params->spp_pathmaxrxt) {
2548 		if (trans) {
2549 			trans->pathmaxrxt = params->spp_pathmaxrxt;
2550 		} else if (asoc) {
2551 			asoc->pathmaxrxt = params->spp_pathmaxrxt;
2552 		} else {
2553 			sp->pathmaxrxt = params->spp_pathmaxrxt;
2554 		}
2555 	}
2556 
2557 	return 0;
2558 }
2559 
2560 static int sctp_setsockopt_peer_addr_params(struct sock *sk,
2561 					    char __user *optval,
2562 					    unsigned int optlen)
2563 {
2564 	struct sctp_paddrparams  params;
2565 	struct sctp_transport   *trans = NULL;
2566 	struct sctp_association *asoc = NULL;
2567 	struct sctp_sock        *sp = sctp_sk(sk);
2568 	int error;
2569 	int hb_change, pmtud_change, sackdelay_change;
2570 
2571 	if (optlen != sizeof(struct sctp_paddrparams))
2572 		return -EINVAL;
2573 
2574 	if (copy_from_user(&params, optval, optlen))
2575 		return -EFAULT;
2576 
2577 	/* Validate flags and value parameters. */
2578 	hb_change        = params.spp_flags & SPP_HB;
2579 	pmtud_change     = params.spp_flags & SPP_PMTUD;
2580 	sackdelay_change = params.spp_flags & SPP_SACKDELAY;
2581 
2582 	if (hb_change        == SPP_HB ||
2583 	    pmtud_change     == SPP_PMTUD ||
2584 	    sackdelay_change == SPP_SACKDELAY ||
2585 	    params.spp_sackdelay > 500 ||
2586 	    (params.spp_pathmtu &&
2587 	     params.spp_pathmtu < SCTP_DEFAULT_MINSEGMENT))
2588 		return -EINVAL;
2589 
2590 	/* If an address other than INADDR_ANY is specified, and
2591 	 * no transport is found, then the request is invalid.
2592 	 */
2593 	if (!sctp_is_any(sk, (union sctp_addr *)&params.spp_address)) {
2594 		trans = sctp_addr_id2transport(sk, &params.spp_address,
2595 					       params.spp_assoc_id);
2596 		if (!trans)
2597 			return -EINVAL;
2598 	}
2599 
2600 	/* Get association, if assoc_id != 0 and the socket is a one
2601 	 * to many style socket, and an association was not found, then
2602 	 * the id was invalid.
2603 	 */
2604 	asoc = sctp_id2assoc(sk, params.spp_assoc_id);
2605 	if (!asoc && params.spp_assoc_id && sctp_style(sk, UDP))
2606 		return -EINVAL;
2607 
2608 	/* Heartbeat demand can only be sent on a transport or
2609 	 * association, but not a socket.
2610 	 */
2611 	if (params.spp_flags & SPP_HB_DEMAND && !trans && !asoc)
2612 		return -EINVAL;
2613 
2614 	/* Process parameters. */
2615 	error = sctp_apply_peer_addr_params(&params, trans, asoc, sp,
2616 					    hb_change, pmtud_change,
2617 					    sackdelay_change);
2618 
2619 	if (error)
2620 		return error;
2621 
2622 	/* If changes are for association, also apply parameters to each
2623 	 * transport.
2624 	 */
2625 	if (!trans && asoc) {
2626 		list_for_each_entry(trans, &asoc->peer.transport_addr_list,
2627 				transports) {
2628 			sctp_apply_peer_addr_params(&params, trans, asoc, sp,
2629 						    hb_change, pmtud_change,
2630 						    sackdelay_change);
2631 		}
2632 	}
2633 
2634 	return 0;
2635 }
2636 
2637 static inline __u32 sctp_spp_sackdelay_enable(__u32 param_flags)
2638 {
2639 	return (param_flags & ~SPP_SACKDELAY) | SPP_SACKDELAY_ENABLE;
2640 }
2641 
2642 static inline __u32 sctp_spp_sackdelay_disable(__u32 param_flags)
2643 {
2644 	return (param_flags & ~SPP_SACKDELAY) | SPP_SACKDELAY_DISABLE;
2645 }
2646 
2647 /*
2648  * 7.1.23.  Get or set delayed ack timer (SCTP_DELAYED_SACK)
2649  *
2650  * This option will effect the way delayed acks are performed.  This
2651  * option allows you to get or set the delayed ack time, in
2652  * milliseconds.  It also allows changing the delayed ack frequency.
2653  * Changing the frequency to 1 disables the delayed sack algorithm.  If
2654  * the assoc_id is 0, then this sets or gets the endpoints default
2655  * values.  If the assoc_id field is non-zero, then the set or get
2656  * effects the specified association for the one to many model (the
2657  * assoc_id field is ignored by the one to one model).  Note that if
2658  * sack_delay or sack_freq are 0 when setting this option, then the
2659  * current values will remain unchanged.
2660  *
2661  * struct sctp_sack_info {
2662  *     sctp_assoc_t            sack_assoc_id;
2663  *     uint32_t                sack_delay;
2664  *     uint32_t                sack_freq;
2665  * };
2666  *
2667  * sack_assoc_id -  This parameter, indicates which association the user
2668  *    is performing an action upon.  Note that if this field's value is
2669  *    zero then the endpoints default value is changed (effecting future
2670  *    associations only).
2671  *
2672  * sack_delay -  This parameter contains the number of milliseconds that
2673  *    the user is requesting the delayed ACK timer be set to.  Note that
2674  *    this value is defined in the standard to be between 200 and 500
2675  *    milliseconds.
2676  *
2677  * sack_freq -  This parameter contains the number of packets that must
2678  *    be received before a sack is sent without waiting for the delay
2679  *    timer to expire.  The default value for this is 2, setting this
2680  *    value to 1 will disable the delayed sack algorithm.
2681  */
2682 
2683 static int sctp_setsockopt_delayed_ack(struct sock *sk,
2684 				       char __user *optval, unsigned int optlen)
2685 {
2686 	struct sctp_sack_info    params;
2687 	struct sctp_transport   *trans = NULL;
2688 	struct sctp_association *asoc = NULL;
2689 	struct sctp_sock        *sp = sctp_sk(sk);
2690 
2691 	if (optlen == sizeof(struct sctp_sack_info)) {
2692 		if (copy_from_user(&params, optval, optlen))
2693 			return -EFAULT;
2694 
2695 		if (params.sack_delay == 0 && params.sack_freq == 0)
2696 			return 0;
2697 	} else if (optlen == sizeof(struct sctp_assoc_value)) {
2698 		pr_warn_ratelimited(DEPRECATED
2699 				    "%s (pid %d) "
2700 				    "Use of struct sctp_assoc_value in delayed_ack socket option.\n"
2701 				    "Use struct sctp_sack_info instead\n",
2702 				    current->comm, task_pid_nr(current));
2703 		if (copy_from_user(&params, optval, optlen))
2704 			return -EFAULT;
2705 
2706 		if (params.sack_delay == 0)
2707 			params.sack_freq = 1;
2708 		else
2709 			params.sack_freq = 0;
2710 	} else
2711 		return -EINVAL;
2712 
2713 	/* Validate value parameter. */
2714 	if (params.sack_delay > 500)
2715 		return -EINVAL;
2716 
2717 	/* Get association, if sack_assoc_id != 0 and the socket is a one
2718 	 * to many style socket, and an association was not found, then
2719 	 * the id was invalid.
2720 	 */
2721 	asoc = sctp_id2assoc(sk, params.sack_assoc_id);
2722 	if (!asoc && params.sack_assoc_id && sctp_style(sk, UDP))
2723 		return -EINVAL;
2724 
2725 	if (params.sack_delay) {
2726 		if (asoc) {
2727 			asoc->sackdelay =
2728 				msecs_to_jiffies(params.sack_delay);
2729 			asoc->param_flags =
2730 				sctp_spp_sackdelay_enable(asoc->param_flags);
2731 		} else {
2732 			sp->sackdelay = params.sack_delay;
2733 			sp->param_flags =
2734 				sctp_spp_sackdelay_enable(sp->param_flags);
2735 		}
2736 	}
2737 
2738 	if (params.sack_freq == 1) {
2739 		if (asoc) {
2740 			asoc->param_flags =
2741 				sctp_spp_sackdelay_disable(asoc->param_flags);
2742 		} else {
2743 			sp->param_flags =
2744 				sctp_spp_sackdelay_disable(sp->param_flags);
2745 		}
2746 	} else if (params.sack_freq > 1) {
2747 		if (asoc) {
2748 			asoc->sackfreq = params.sack_freq;
2749 			asoc->param_flags =
2750 				sctp_spp_sackdelay_enable(asoc->param_flags);
2751 		} else {
2752 			sp->sackfreq = params.sack_freq;
2753 			sp->param_flags =
2754 				sctp_spp_sackdelay_enable(sp->param_flags);
2755 		}
2756 	}
2757 
2758 	/* If change is for association, also apply to each transport. */
2759 	if (asoc) {
2760 		list_for_each_entry(trans, &asoc->peer.transport_addr_list,
2761 				transports) {
2762 			if (params.sack_delay) {
2763 				trans->sackdelay =
2764 					msecs_to_jiffies(params.sack_delay);
2765 				trans->param_flags =
2766 					sctp_spp_sackdelay_enable(trans->param_flags);
2767 			}
2768 			if (params.sack_freq == 1) {
2769 				trans->param_flags =
2770 					sctp_spp_sackdelay_disable(trans->param_flags);
2771 			} else if (params.sack_freq > 1) {
2772 				trans->sackfreq = params.sack_freq;
2773 				trans->param_flags =
2774 					sctp_spp_sackdelay_enable(trans->param_flags);
2775 			}
2776 		}
2777 	}
2778 
2779 	return 0;
2780 }
2781 
2782 /* 7.1.3 Initialization Parameters (SCTP_INITMSG)
2783  *
2784  * Applications can specify protocol parameters for the default association
2785  * initialization.  The option name argument to setsockopt() and getsockopt()
2786  * is SCTP_INITMSG.
2787  *
2788  * Setting initialization parameters is effective only on an unconnected
2789  * socket (for UDP-style sockets only future associations are effected
2790  * by the change).  With TCP-style sockets, this option is inherited by
2791  * sockets derived from a listener socket.
2792  */
2793 static int sctp_setsockopt_initmsg(struct sock *sk, char __user *optval, unsigned int optlen)
2794 {
2795 	struct sctp_initmsg sinit;
2796 	struct sctp_sock *sp = sctp_sk(sk);
2797 
2798 	if (optlen != sizeof(struct sctp_initmsg))
2799 		return -EINVAL;
2800 	if (copy_from_user(&sinit, optval, optlen))
2801 		return -EFAULT;
2802 
2803 	if (sinit.sinit_num_ostreams)
2804 		sp->initmsg.sinit_num_ostreams = sinit.sinit_num_ostreams;
2805 	if (sinit.sinit_max_instreams)
2806 		sp->initmsg.sinit_max_instreams = sinit.sinit_max_instreams;
2807 	if (sinit.sinit_max_attempts)
2808 		sp->initmsg.sinit_max_attempts = sinit.sinit_max_attempts;
2809 	if (sinit.sinit_max_init_timeo)
2810 		sp->initmsg.sinit_max_init_timeo = sinit.sinit_max_init_timeo;
2811 
2812 	return 0;
2813 }
2814 
2815 /*
2816  * 7.1.14 Set default send parameters (SCTP_DEFAULT_SEND_PARAM)
2817  *
2818  *   Applications that wish to use the sendto() system call may wish to
2819  *   specify a default set of parameters that would normally be supplied
2820  *   through the inclusion of ancillary data.  This socket option allows
2821  *   such an application to set the default sctp_sndrcvinfo structure.
2822  *   The application that wishes to use this socket option simply passes
2823  *   in to this call the sctp_sndrcvinfo structure defined in Section
2824  *   5.2.2) The input parameters accepted by this call include
2825  *   sinfo_stream, sinfo_flags, sinfo_ppid, sinfo_context,
2826  *   sinfo_timetolive.  The user must provide the sinfo_assoc_id field in
2827  *   to this call if the caller is using the UDP model.
2828  */
2829 static int sctp_setsockopt_default_send_param(struct sock *sk,
2830 					      char __user *optval,
2831 					      unsigned int optlen)
2832 {
2833 	struct sctp_sock *sp = sctp_sk(sk);
2834 	struct sctp_association *asoc;
2835 	struct sctp_sndrcvinfo info;
2836 
2837 	if (optlen != sizeof(info))
2838 		return -EINVAL;
2839 	if (copy_from_user(&info, optval, optlen))
2840 		return -EFAULT;
2841 	if (info.sinfo_flags &
2842 	    ~(SCTP_UNORDERED | SCTP_ADDR_OVER |
2843 	      SCTP_ABORT | SCTP_EOF))
2844 		return -EINVAL;
2845 
2846 	asoc = sctp_id2assoc(sk, info.sinfo_assoc_id);
2847 	if (!asoc && info.sinfo_assoc_id && sctp_style(sk, UDP))
2848 		return -EINVAL;
2849 	if (asoc) {
2850 		asoc->default_stream = info.sinfo_stream;
2851 		asoc->default_flags = info.sinfo_flags;
2852 		asoc->default_ppid = info.sinfo_ppid;
2853 		asoc->default_context = info.sinfo_context;
2854 		asoc->default_timetolive = info.sinfo_timetolive;
2855 	} else {
2856 		sp->default_stream = info.sinfo_stream;
2857 		sp->default_flags = info.sinfo_flags;
2858 		sp->default_ppid = info.sinfo_ppid;
2859 		sp->default_context = info.sinfo_context;
2860 		sp->default_timetolive = info.sinfo_timetolive;
2861 	}
2862 
2863 	return 0;
2864 }
2865 
2866 /* RFC6458, Section 8.1.31. Set/get Default Send Parameters
2867  * (SCTP_DEFAULT_SNDINFO)
2868  */
2869 static int sctp_setsockopt_default_sndinfo(struct sock *sk,
2870 					   char __user *optval,
2871 					   unsigned int optlen)
2872 {
2873 	struct sctp_sock *sp = sctp_sk(sk);
2874 	struct sctp_association *asoc;
2875 	struct sctp_sndinfo info;
2876 
2877 	if (optlen != sizeof(info))
2878 		return -EINVAL;
2879 	if (copy_from_user(&info, optval, optlen))
2880 		return -EFAULT;
2881 	if (info.snd_flags &
2882 	    ~(SCTP_UNORDERED | SCTP_ADDR_OVER |
2883 	      SCTP_ABORT | SCTP_EOF))
2884 		return -EINVAL;
2885 
2886 	asoc = sctp_id2assoc(sk, info.snd_assoc_id);
2887 	if (!asoc && info.snd_assoc_id && sctp_style(sk, UDP))
2888 		return -EINVAL;
2889 	if (asoc) {
2890 		asoc->default_stream = info.snd_sid;
2891 		asoc->default_flags = info.snd_flags;
2892 		asoc->default_ppid = info.snd_ppid;
2893 		asoc->default_context = info.snd_context;
2894 	} else {
2895 		sp->default_stream = info.snd_sid;
2896 		sp->default_flags = info.snd_flags;
2897 		sp->default_ppid = info.snd_ppid;
2898 		sp->default_context = info.snd_context;
2899 	}
2900 
2901 	return 0;
2902 }
2903 
2904 /* 7.1.10 Set Primary Address (SCTP_PRIMARY_ADDR)
2905  *
2906  * Requests that the local SCTP stack use the enclosed peer address as
2907  * the association primary.  The enclosed address must be one of the
2908  * association peer's addresses.
2909  */
2910 static int sctp_setsockopt_primary_addr(struct sock *sk, char __user *optval,
2911 					unsigned int optlen)
2912 {
2913 	struct sctp_prim prim;
2914 	struct sctp_transport *trans;
2915 
2916 	if (optlen != sizeof(struct sctp_prim))
2917 		return -EINVAL;
2918 
2919 	if (copy_from_user(&prim, optval, sizeof(struct sctp_prim)))
2920 		return -EFAULT;
2921 
2922 	trans = sctp_addr_id2transport(sk, &prim.ssp_addr, prim.ssp_assoc_id);
2923 	if (!trans)
2924 		return -EINVAL;
2925 
2926 	sctp_assoc_set_primary(trans->asoc, trans);
2927 
2928 	return 0;
2929 }
2930 
2931 /*
2932  * 7.1.5 SCTP_NODELAY
2933  *
2934  * Turn on/off any Nagle-like algorithm.  This means that packets are
2935  * generally sent as soon as possible and no unnecessary delays are
2936  * introduced, at the cost of more packets in the network.  Expects an
2937  *  integer boolean flag.
2938  */
2939 static int sctp_setsockopt_nodelay(struct sock *sk, char __user *optval,
2940 				   unsigned int optlen)
2941 {
2942 	int val;
2943 
2944 	if (optlen < sizeof(int))
2945 		return -EINVAL;
2946 	if (get_user(val, (int __user *)optval))
2947 		return -EFAULT;
2948 
2949 	sctp_sk(sk)->nodelay = (val == 0) ? 0 : 1;
2950 	return 0;
2951 }
2952 
2953 /*
2954  *
2955  * 7.1.1 SCTP_RTOINFO
2956  *
2957  * The protocol parameters used to initialize and bound retransmission
2958  * timeout (RTO) are tunable. sctp_rtoinfo structure is used to access
2959  * and modify these parameters.
2960  * All parameters are time values, in milliseconds.  A value of 0, when
2961  * modifying the parameters, indicates that the current value should not
2962  * be changed.
2963  *
2964  */
2965 static int sctp_setsockopt_rtoinfo(struct sock *sk, char __user *optval, unsigned int optlen)
2966 {
2967 	struct sctp_rtoinfo rtoinfo;
2968 	struct sctp_association *asoc;
2969 	unsigned long rto_min, rto_max;
2970 	struct sctp_sock *sp = sctp_sk(sk);
2971 
2972 	if (optlen != sizeof (struct sctp_rtoinfo))
2973 		return -EINVAL;
2974 
2975 	if (copy_from_user(&rtoinfo, optval, optlen))
2976 		return -EFAULT;
2977 
2978 	asoc = sctp_id2assoc(sk, rtoinfo.srto_assoc_id);
2979 
2980 	/* Set the values to the specific association */
2981 	if (!asoc && rtoinfo.srto_assoc_id && sctp_style(sk, UDP))
2982 		return -EINVAL;
2983 
2984 	rto_max = rtoinfo.srto_max;
2985 	rto_min = rtoinfo.srto_min;
2986 
2987 	if (rto_max)
2988 		rto_max = asoc ? msecs_to_jiffies(rto_max) : rto_max;
2989 	else
2990 		rto_max = asoc ? asoc->rto_max : sp->rtoinfo.srto_max;
2991 
2992 	if (rto_min)
2993 		rto_min = asoc ? msecs_to_jiffies(rto_min) : rto_min;
2994 	else
2995 		rto_min = asoc ? asoc->rto_min : sp->rtoinfo.srto_min;
2996 
2997 	if (rto_min > rto_max)
2998 		return -EINVAL;
2999 
3000 	if (asoc) {
3001 		if (rtoinfo.srto_initial != 0)
3002 			asoc->rto_initial =
3003 				msecs_to_jiffies(rtoinfo.srto_initial);
3004 		asoc->rto_max = rto_max;
3005 		asoc->rto_min = rto_min;
3006 	} else {
3007 		/* If there is no association or the association-id = 0
3008 		 * set the values to the endpoint.
3009 		 */
3010 		if (rtoinfo.srto_initial != 0)
3011 			sp->rtoinfo.srto_initial = rtoinfo.srto_initial;
3012 		sp->rtoinfo.srto_max = rto_max;
3013 		sp->rtoinfo.srto_min = rto_min;
3014 	}
3015 
3016 	return 0;
3017 }
3018 
3019 /*
3020  *
3021  * 7.1.2 SCTP_ASSOCINFO
3022  *
3023  * This option is used to tune the maximum retransmission attempts
3024  * of the association.
3025  * Returns an error if the new association retransmission value is
3026  * greater than the sum of the retransmission value  of the peer.
3027  * See [SCTP] for more information.
3028  *
3029  */
3030 static int sctp_setsockopt_associnfo(struct sock *sk, char __user *optval, unsigned int optlen)
3031 {
3032 
3033 	struct sctp_assocparams assocparams;
3034 	struct sctp_association *asoc;
3035 
3036 	if (optlen != sizeof(struct sctp_assocparams))
3037 		return -EINVAL;
3038 	if (copy_from_user(&assocparams, optval, optlen))
3039 		return -EFAULT;
3040 
3041 	asoc = sctp_id2assoc(sk, assocparams.sasoc_assoc_id);
3042 
3043 	if (!asoc && assocparams.sasoc_assoc_id && sctp_style(sk, UDP))
3044 		return -EINVAL;
3045 
3046 	/* Set the values to the specific association */
3047 	if (asoc) {
3048 		if (assocparams.sasoc_asocmaxrxt != 0) {
3049 			__u32 path_sum = 0;
3050 			int   paths = 0;
3051 			struct sctp_transport *peer_addr;
3052 
3053 			list_for_each_entry(peer_addr, &asoc->peer.transport_addr_list,
3054 					transports) {
3055 				path_sum += peer_addr->pathmaxrxt;
3056 				paths++;
3057 			}
3058 
3059 			/* Only validate asocmaxrxt if we have more than
3060 			 * one path/transport.  We do this because path
3061 			 * retransmissions are only counted when we have more
3062 			 * then one path.
3063 			 */
3064 			if (paths > 1 &&
3065 			    assocparams.sasoc_asocmaxrxt > path_sum)
3066 				return -EINVAL;
3067 
3068 			asoc->max_retrans = assocparams.sasoc_asocmaxrxt;
3069 		}
3070 
3071 		if (assocparams.sasoc_cookie_life != 0)
3072 			asoc->cookie_life = ms_to_ktime(assocparams.sasoc_cookie_life);
3073 	} else {
3074 		/* Set the values to the endpoint */
3075 		struct sctp_sock *sp = sctp_sk(sk);
3076 
3077 		if (assocparams.sasoc_asocmaxrxt != 0)
3078 			sp->assocparams.sasoc_asocmaxrxt =
3079 						assocparams.sasoc_asocmaxrxt;
3080 		if (assocparams.sasoc_cookie_life != 0)
3081 			sp->assocparams.sasoc_cookie_life =
3082 						assocparams.sasoc_cookie_life;
3083 	}
3084 	return 0;
3085 }
3086 
3087 /*
3088  * 7.1.16 Set/clear IPv4 mapped addresses (SCTP_I_WANT_MAPPED_V4_ADDR)
3089  *
3090  * This socket option is a boolean flag which turns on or off mapped V4
3091  * addresses.  If this option is turned on and the socket is type
3092  * PF_INET6, then IPv4 addresses will be mapped to V6 representation.
3093  * If this option is turned off, then no mapping will be done of V4
3094  * addresses and a user will receive both PF_INET6 and PF_INET type
3095  * addresses on the socket.
3096  */
3097 static int sctp_setsockopt_mappedv4(struct sock *sk, char __user *optval, unsigned int optlen)
3098 {
3099 	int val;
3100 	struct sctp_sock *sp = sctp_sk(sk);
3101 
3102 	if (optlen < sizeof(int))
3103 		return -EINVAL;
3104 	if (get_user(val, (int __user *)optval))
3105 		return -EFAULT;
3106 	if (val)
3107 		sp->v4mapped = 1;
3108 	else
3109 		sp->v4mapped = 0;
3110 
3111 	return 0;
3112 }
3113 
3114 /*
3115  * 8.1.16.  Get or Set the Maximum Fragmentation Size (SCTP_MAXSEG)
3116  * This option will get or set the maximum size to put in any outgoing
3117  * SCTP DATA chunk.  If a message is larger than this size it will be
3118  * fragmented by SCTP into the specified size.  Note that the underlying
3119  * SCTP implementation may fragment into smaller sized chunks when the
3120  * PMTU of the underlying association is smaller than the value set by
3121  * the user.  The default value for this option is '0' which indicates
3122  * the user is NOT limiting fragmentation and only the PMTU will effect
3123  * SCTP's choice of DATA chunk size.  Note also that values set larger
3124  * than the maximum size of an IP datagram will effectively let SCTP
3125  * control fragmentation (i.e. the same as setting this option to 0).
3126  *
3127  * The following structure is used to access and modify this parameter:
3128  *
3129  * struct sctp_assoc_value {
3130  *   sctp_assoc_t assoc_id;
3131  *   uint32_t assoc_value;
3132  * };
3133  *
3134  * assoc_id:  This parameter is ignored for one-to-one style sockets.
3135  *    For one-to-many style sockets this parameter indicates which
3136  *    association the user is performing an action upon.  Note that if
3137  *    this field's value is zero then the endpoints default value is
3138  *    changed (effecting future associations only).
3139  * assoc_value:  This parameter specifies the maximum size in bytes.
3140  */
3141 static int sctp_setsockopt_maxseg(struct sock *sk, char __user *optval, unsigned int optlen)
3142 {
3143 	struct sctp_sock *sp = sctp_sk(sk);
3144 	struct sctp_assoc_value params;
3145 	struct sctp_association *asoc;
3146 	int val;
3147 
3148 	if (optlen == sizeof(int)) {
3149 		pr_warn_ratelimited(DEPRECATED
3150 				    "%s (pid %d) "
3151 				    "Use of int in maxseg socket option.\n"
3152 				    "Use struct sctp_assoc_value instead\n",
3153 				    current->comm, task_pid_nr(current));
3154 		if (copy_from_user(&val, optval, optlen))
3155 			return -EFAULT;
3156 		params.assoc_id = 0;
3157 	} else if (optlen == sizeof(struct sctp_assoc_value)) {
3158 		if (copy_from_user(&params, optval, optlen))
3159 			return -EFAULT;
3160 		val = params.assoc_value;
3161 	} else {
3162 		return -EINVAL;
3163 	}
3164 
3165 	if (val) {
3166 		int min_len, max_len;
3167 
3168 		min_len = SCTP_DEFAULT_MINSEGMENT - sp->pf->af->net_header_len;
3169 		min_len -= sizeof(struct sctphdr) +
3170 			   sizeof(struct sctp_data_chunk);
3171 
3172 		max_len = SCTP_MAX_CHUNK_LEN - sizeof(struct sctp_data_chunk);
3173 
3174 		if (val < min_len || val > max_len)
3175 			return -EINVAL;
3176 	}
3177 
3178 	asoc = sctp_id2assoc(sk, params.assoc_id);
3179 	if (asoc) {
3180 		if (val == 0) {
3181 			val = asoc->pathmtu - sp->pf->af->net_header_len;
3182 			val -= sizeof(struct sctphdr) +
3183 			       sizeof(struct sctp_data_chunk);
3184 		}
3185 		asoc->user_frag = val;
3186 		asoc->frag_point = sctp_frag_point(asoc, asoc->pathmtu);
3187 	} else {
3188 		if (params.assoc_id && sctp_style(sk, UDP))
3189 			return -EINVAL;
3190 		sp->user_frag = val;
3191 	}
3192 
3193 	return 0;
3194 }
3195 
3196 
3197 /*
3198  *  7.1.9 Set Peer Primary Address (SCTP_SET_PEER_PRIMARY_ADDR)
3199  *
3200  *   Requests that the peer mark the enclosed address as the association
3201  *   primary. The enclosed address must be one of the association's
3202  *   locally bound addresses. The following structure is used to make a
3203  *   set primary request:
3204  */
3205 static int sctp_setsockopt_peer_primary_addr(struct sock *sk, char __user *optval,
3206 					     unsigned int optlen)
3207 {
3208 	struct net *net = sock_net(sk);
3209 	struct sctp_sock	*sp;
3210 	struct sctp_association	*asoc = NULL;
3211 	struct sctp_setpeerprim	prim;
3212 	struct sctp_chunk	*chunk;
3213 	struct sctp_af		*af;
3214 	int 			err;
3215 
3216 	sp = sctp_sk(sk);
3217 
3218 	if (!net->sctp.addip_enable)
3219 		return -EPERM;
3220 
3221 	if (optlen != sizeof(struct sctp_setpeerprim))
3222 		return -EINVAL;
3223 
3224 	if (copy_from_user(&prim, optval, optlen))
3225 		return -EFAULT;
3226 
3227 	asoc = sctp_id2assoc(sk, prim.sspp_assoc_id);
3228 	if (!asoc)
3229 		return -EINVAL;
3230 
3231 	if (!asoc->peer.asconf_capable)
3232 		return -EPERM;
3233 
3234 	if (asoc->peer.addip_disabled_mask & SCTP_PARAM_SET_PRIMARY)
3235 		return -EPERM;
3236 
3237 	if (!sctp_state(asoc, ESTABLISHED))
3238 		return -ENOTCONN;
3239 
3240 	af = sctp_get_af_specific(prim.sspp_addr.ss_family);
3241 	if (!af)
3242 		return -EINVAL;
3243 
3244 	if (!af->addr_valid((union sctp_addr *)&prim.sspp_addr, sp, NULL))
3245 		return -EADDRNOTAVAIL;
3246 
3247 	if (!sctp_assoc_lookup_laddr(asoc, (union sctp_addr *)&prim.sspp_addr))
3248 		return -EADDRNOTAVAIL;
3249 
3250 	/* Create an ASCONF chunk with SET_PRIMARY parameter	*/
3251 	chunk = sctp_make_asconf_set_prim(asoc,
3252 					  (union sctp_addr *)&prim.sspp_addr);
3253 	if (!chunk)
3254 		return -ENOMEM;
3255 
3256 	err = sctp_send_asconf(asoc, chunk);
3257 
3258 	pr_debug("%s: we set peer primary addr primitively\n", __func__);
3259 
3260 	return err;
3261 }
3262 
3263 static int sctp_setsockopt_adaptation_layer(struct sock *sk, char __user *optval,
3264 					    unsigned int optlen)
3265 {
3266 	struct sctp_setadaptation adaptation;
3267 
3268 	if (optlen != sizeof(struct sctp_setadaptation))
3269 		return -EINVAL;
3270 	if (copy_from_user(&adaptation, optval, optlen))
3271 		return -EFAULT;
3272 
3273 	sctp_sk(sk)->adaptation_ind = adaptation.ssb_adaptation_ind;
3274 
3275 	return 0;
3276 }
3277 
3278 /*
3279  * 7.1.29.  Set or Get the default context (SCTP_CONTEXT)
3280  *
3281  * The context field in the sctp_sndrcvinfo structure is normally only
3282  * used when a failed message is retrieved holding the value that was
3283  * sent down on the actual send call.  This option allows the setting of
3284  * a default context on an association basis that will be received on
3285  * reading messages from the peer.  This is especially helpful in the
3286  * one-2-many model for an application to keep some reference to an
3287  * internal state machine that is processing messages on the
3288  * association.  Note that the setting of this value only effects
3289  * received messages from the peer and does not effect the value that is
3290  * saved with outbound messages.
3291  */
3292 static int sctp_setsockopt_context(struct sock *sk, char __user *optval,
3293 				   unsigned int optlen)
3294 {
3295 	struct sctp_assoc_value params;
3296 	struct sctp_sock *sp;
3297 	struct sctp_association *asoc;
3298 
3299 	if (optlen != sizeof(struct sctp_assoc_value))
3300 		return -EINVAL;
3301 	if (copy_from_user(&params, optval, optlen))
3302 		return -EFAULT;
3303 
3304 	sp = sctp_sk(sk);
3305 
3306 	if (params.assoc_id != 0) {
3307 		asoc = sctp_id2assoc(sk, params.assoc_id);
3308 		if (!asoc)
3309 			return -EINVAL;
3310 		asoc->default_rcv_context = params.assoc_value;
3311 	} else {
3312 		sp->default_rcv_context = params.assoc_value;
3313 	}
3314 
3315 	return 0;
3316 }
3317 
3318 /*
3319  * 7.1.24.  Get or set fragmented interleave (SCTP_FRAGMENT_INTERLEAVE)
3320  *
3321  * This options will at a minimum specify if the implementation is doing
3322  * fragmented interleave.  Fragmented interleave, for a one to many
3323  * socket, is when subsequent calls to receive a message may return
3324  * parts of messages from different associations.  Some implementations
3325  * may allow you to turn this value on or off.  If so, when turned off,
3326  * no fragment interleave will occur (which will cause a head of line
3327  * blocking amongst multiple associations sharing the same one to many
3328  * socket).  When this option is turned on, then each receive call may
3329  * come from a different association (thus the user must receive data
3330  * with the extended calls (e.g. sctp_recvmsg) to keep track of which
3331  * association each receive belongs to.
3332  *
3333  * This option takes a boolean value.  A non-zero value indicates that
3334  * fragmented interleave is on.  A value of zero indicates that
3335  * fragmented interleave is off.
3336  *
3337  * Note that it is important that an implementation that allows this
3338  * option to be turned on, have it off by default.  Otherwise an unaware
3339  * application using the one to many model may become confused and act
3340  * incorrectly.
3341  */
3342 static int sctp_setsockopt_fragment_interleave(struct sock *sk,
3343 					       char __user *optval,
3344 					       unsigned int optlen)
3345 {
3346 	int val;
3347 
3348 	if (optlen != sizeof(int))
3349 		return -EINVAL;
3350 	if (get_user(val, (int __user *)optval))
3351 		return -EFAULT;
3352 
3353 	sctp_sk(sk)->frag_interleave = (val == 0) ? 0 : 1;
3354 
3355 	return 0;
3356 }
3357 
3358 /*
3359  * 8.1.21.  Set or Get the SCTP Partial Delivery Point
3360  *       (SCTP_PARTIAL_DELIVERY_POINT)
3361  *
3362  * This option will set or get the SCTP partial delivery point.  This
3363  * point is the size of a message where the partial delivery API will be
3364  * invoked to help free up rwnd space for the peer.  Setting this to a
3365  * lower value will cause partial deliveries to happen more often.  The
3366  * calls argument is an integer that sets or gets the partial delivery
3367  * point.  Note also that the call will fail if the user attempts to set
3368  * this value larger than the socket receive buffer size.
3369  *
3370  * Note that any single message having a length smaller than or equal to
3371  * the SCTP partial delivery point will be delivered in one single read
3372  * call as long as the user provided buffer is large enough to hold the
3373  * message.
3374  */
3375 static int sctp_setsockopt_partial_delivery_point(struct sock *sk,
3376 						  char __user *optval,
3377 						  unsigned int optlen)
3378 {
3379 	u32 val;
3380 
3381 	if (optlen != sizeof(u32))
3382 		return -EINVAL;
3383 	if (get_user(val, (int __user *)optval))
3384 		return -EFAULT;
3385 
3386 	/* Note: We double the receive buffer from what the user sets
3387 	 * it to be, also initial rwnd is based on rcvbuf/2.
3388 	 */
3389 	if (val > (sk->sk_rcvbuf >> 1))
3390 		return -EINVAL;
3391 
3392 	sctp_sk(sk)->pd_point = val;
3393 
3394 	return 0; /* is this the right error code? */
3395 }
3396 
3397 /*
3398  * 7.1.28.  Set or Get the maximum burst (SCTP_MAX_BURST)
3399  *
3400  * This option will allow a user to change the maximum burst of packets
3401  * that can be emitted by this association.  Note that the default value
3402  * is 4, and some implementations may restrict this setting so that it
3403  * can only be lowered.
3404  *
3405  * NOTE: This text doesn't seem right.  Do this on a socket basis with
3406  * future associations inheriting the socket value.
3407  */
3408 static int sctp_setsockopt_maxburst(struct sock *sk,
3409 				    char __user *optval,
3410 				    unsigned int optlen)
3411 {
3412 	struct sctp_assoc_value params;
3413 	struct sctp_sock *sp;
3414 	struct sctp_association *asoc;
3415 	int val;
3416 	int assoc_id = 0;
3417 
3418 	if (optlen == sizeof(int)) {
3419 		pr_warn_ratelimited(DEPRECATED
3420 				    "%s (pid %d) "
3421 				    "Use of int in max_burst socket option deprecated.\n"
3422 				    "Use struct sctp_assoc_value instead\n",
3423 				    current->comm, task_pid_nr(current));
3424 		if (copy_from_user(&val, optval, optlen))
3425 			return -EFAULT;
3426 	} else if (optlen == sizeof(struct sctp_assoc_value)) {
3427 		if (copy_from_user(&params, optval, optlen))
3428 			return -EFAULT;
3429 		val = params.assoc_value;
3430 		assoc_id = params.assoc_id;
3431 	} else
3432 		return -EINVAL;
3433 
3434 	sp = sctp_sk(sk);
3435 
3436 	if (assoc_id != 0) {
3437 		asoc = sctp_id2assoc(sk, assoc_id);
3438 		if (!asoc)
3439 			return -EINVAL;
3440 		asoc->max_burst = val;
3441 	} else
3442 		sp->max_burst = val;
3443 
3444 	return 0;
3445 }
3446 
3447 /*
3448  * 7.1.18.  Add a chunk that must be authenticated (SCTP_AUTH_CHUNK)
3449  *
3450  * This set option adds a chunk type that the user is requesting to be
3451  * received only in an authenticated way.  Changes to the list of chunks
3452  * will only effect future associations on the socket.
3453  */
3454 static int sctp_setsockopt_auth_chunk(struct sock *sk,
3455 				      char __user *optval,
3456 				      unsigned int optlen)
3457 {
3458 	struct sctp_endpoint *ep = sctp_sk(sk)->ep;
3459 	struct sctp_authchunk val;
3460 
3461 	if (!ep->auth_enable)
3462 		return -EACCES;
3463 
3464 	if (optlen != sizeof(struct sctp_authchunk))
3465 		return -EINVAL;
3466 	if (copy_from_user(&val, optval, optlen))
3467 		return -EFAULT;
3468 
3469 	switch (val.sauth_chunk) {
3470 	case SCTP_CID_INIT:
3471 	case SCTP_CID_INIT_ACK:
3472 	case SCTP_CID_SHUTDOWN_COMPLETE:
3473 	case SCTP_CID_AUTH:
3474 		return -EINVAL;
3475 	}
3476 
3477 	/* add this chunk id to the endpoint */
3478 	return sctp_auth_ep_add_chunkid(ep, val.sauth_chunk);
3479 }
3480 
3481 /*
3482  * 7.1.19.  Get or set the list of supported HMAC Identifiers (SCTP_HMAC_IDENT)
3483  *
3484  * This option gets or sets the list of HMAC algorithms that the local
3485  * endpoint requires the peer to use.
3486  */
3487 static int sctp_setsockopt_hmac_ident(struct sock *sk,
3488 				      char __user *optval,
3489 				      unsigned int optlen)
3490 {
3491 	struct sctp_endpoint *ep = sctp_sk(sk)->ep;
3492 	struct sctp_hmacalgo *hmacs;
3493 	u32 idents;
3494 	int err;
3495 
3496 	if (!ep->auth_enable)
3497 		return -EACCES;
3498 
3499 	if (optlen < sizeof(struct sctp_hmacalgo))
3500 		return -EINVAL;
3501 
3502 	hmacs = memdup_user(optval, optlen);
3503 	if (IS_ERR(hmacs))
3504 		return PTR_ERR(hmacs);
3505 
3506 	idents = hmacs->shmac_num_idents;
3507 	if (idents == 0 || idents > SCTP_AUTH_NUM_HMACS ||
3508 	    (idents * sizeof(u16)) > (optlen - sizeof(struct sctp_hmacalgo))) {
3509 		err = -EINVAL;
3510 		goto out;
3511 	}
3512 
3513 	err = sctp_auth_ep_set_hmacs(ep, hmacs);
3514 out:
3515 	kfree(hmacs);
3516 	return err;
3517 }
3518 
3519 /*
3520  * 7.1.20.  Set a shared key (SCTP_AUTH_KEY)
3521  *
3522  * This option will set a shared secret key which is used to build an
3523  * association shared key.
3524  */
3525 static int sctp_setsockopt_auth_key(struct sock *sk,
3526 				    char __user *optval,
3527 				    unsigned int optlen)
3528 {
3529 	struct sctp_endpoint *ep = sctp_sk(sk)->ep;
3530 	struct sctp_authkey *authkey;
3531 	struct sctp_association *asoc;
3532 	int ret;
3533 
3534 	if (!ep->auth_enable)
3535 		return -EACCES;
3536 
3537 	if (optlen <= sizeof(struct sctp_authkey))
3538 		return -EINVAL;
3539 
3540 	authkey = memdup_user(optval, optlen);
3541 	if (IS_ERR(authkey))
3542 		return PTR_ERR(authkey);
3543 
3544 	if (authkey->sca_keylength > optlen - sizeof(struct sctp_authkey)) {
3545 		ret = -EINVAL;
3546 		goto out;
3547 	}
3548 
3549 	asoc = sctp_id2assoc(sk, authkey->sca_assoc_id);
3550 	if (!asoc && authkey->sca_assoc_id && sctp_style(sk, UDP)) {
3551 		ret = -EINVAL;
3552 		goto out;
3553 	}
3554 
3555 	ret = sctp_auth_set_key(ep, asoc, authkey);
3556 out:
3557 	kzfree(authkey);
3558 	return ret;
3559 }
3560 
3561 /*
3562  * 7.1.21.  Get or set the active shared key (SCTP_AUTH_ACTIVE_KEY)
3563  *
3564  * This option will get or set the active shared key to be used to build
3565  * the association shared key.
3566  */
3567 static int sctp_setsockopt_active_key(struct sock *sk,
3568 				      char __user *optval,
3569 				      unsigned int optlen)
3570 {
3571 	struct sctp_endpoint *ep = sctp_sk(sk)->ep;
3572 	struct sctp_authkeyid val;
3573 	struct sctp_association *asoc;
3574 
3575 	if (!ep->auth_enable)
3576 		return -EACCES;
3577 
3578 	if (optlen != sizeof(struct sctp_authkeyid))
3579 		return -EINVAL;
3580 	if (copy_from_user(&val, optval, optlen))
3581 		return -EFAULT;
3582 
3583 	asoc = sctp_id2assoc(sk, val.scact_assoc_id);
3584 	if (!asoc && val.scact_assoc_id && sctp_style(sk, UDP))
3585 		return -EINVAL;
3586 
3587 	return sctp_auth_set_active_key(ep, asoc, val.scact_keynumber);
3588 }
3589 
3590 /*
3591  * 7.1.22.  Delete a shared key (SCTP_AUTH_DELETE_KEY)
3592  *
3593  * This set option will delete a shared secret key from use.
3594  */
3595 static int sctp_setsockopt_del_key(struct sock *sk,
3596 				   char __user *optval,
3597 				   unsigned int optlen)
3598 {
3599 	struct sctp_endpoint *ep = sctp_sk(sk)->ep;
3600 	struct sctp_authkeyid val;
3601 	struct sctp_association *asoc;
3602 
3603 	if (!ep->auth_enable)
3604 		return -EACCES;
3605 
3606 	if (optlen != sizeof(struct sctp_authkeyid))
3607 		return -EINVAL;
3608 	if (copy_from_user(&val, optval, optlen))
3609 		return -EFAULT;
3610 
3611 	asoc = sctp_id2assoc(sk, val.scact_assoc_id);
3612 	if (!asoc && val.scact_assoc_id && sctp_style(sk, UDP))
3613 		return -EINVAL;
3614 
3615 	return sctp_auth_del_key_id(ep, asoc, val.scact_keynumber);
3616 
3617 }
3618 
3619 /*
3620  * 8.1.23 SCTP_AUTO_ASCONF
3621  *
3622  * This option will enable or disable the use of the automatic generation of
3623  * ASCONF chunks to add and delete addresses to an existing association.  Note
3624  * that this option has two caveats namely: a) it only affects sockets that
3625  * are bound to all addresses available to the SCTP stack, and b) the system
3626  * administrator may have an overriding control that turns the ASCONF feature
3627  * off no matter what setting the socket option may have.
3628  * This option expects an integer boolean flag, where a non-zero value turns on
3629  * the option, and a zero value turns off the option.
3630  * Note. In this implementation, socket operation overrides default parameter
3631  * being set by sysctl as well as FreeBSD implementation
3632  */
3633 static int sctp_setsockopt_auto_asconf(struct sock *sk, char __user *optval,
3634 					unsigned int optlen)
3635 {
3636 	int val;
3637 	struct sctp_sock *sp = sctp_sk(sk);
3638 
3639 	if (optlen < sizeof(int))
3640 		return -EINVAL;
3641 	if (get_user(val, (int __user *)optval))
3642 		return -EFAULT;
3643 	if (!sctp_is_ep_boundall(sk) && val)
3644 		return -EINVAL;
3645 	if ((val && sp->do_auto_asconf) || (!val && !sp->do_auto_asconf))
3646 		return 0;
3647 
3648 	spin_lock_bh(&sock_net(sk)->sctp.addr_wq_lock);
3649 	if (val == 0 && sp->do_auto_asconf) {
3650 		list_del(&sp->auto_asconf_list);
3651 		sp->do_auto_asconf = 0;
3652 	} else if (val && !sp->do_auto_asconf) {
3653 		list_add_tail(&sp->auto_asconf_list,
3654 		    &sock_net(sk)->sctp.auto_asconf_splist);
3655 		sp->do_auto_asconf = 1;
3656 	}
3657 	spin_unlock_bh(&sock_net(sk)->sctp.addr_wq_lock);
3658 	return 0;
3659 }
3660 
3661 /*
3662  * SCTP_PEER_ADDR_THLDS
3663  *
3664  * This option allows us to alter the partially failed threshold for one or all
3665  * transports in an association.  See Section 6.1 of:
3666  * http://www.ietf.org/id/draft-nishida-tsvwg-sctp-failover-05.txt
3667  */
3668 static int sctp_setsockopt_paddr_thresholds(struct sock *sk,
3669 					    char __user *optval,
3670 					    unsigned int optlen)
3671 {
3672 	struct sctp_paddrthlds val;
3673 	struct sctp_transport *trans;
3674 	struct sctp_association *asoc;
3675 
3676 	if (optlen < sizeof(struct sctp_paddrthlds))
3677 		return -EINVAL;
3678 	if (copy_from_user(&val, (struct sctp_paddrthlds __user *)optval,
3679 			   sizeof(struct sctp_paddrthlds)))
3680 		return -EFAULT;
3681 
3682 
3683 	if (sctp_is_any(sk, (const union sctp_addr *)&val.spt_address)) {
3684 		asoc = sctp_id2assoc(sk, val.spt_assoc_id);
3685 		if (!asoc)
3686 			return -ENOENT;
3687 		list_for_each_entry(trans, &asoc->peer.transport_addr_list,
3688 				    transports) {
3689 			if (val.spt_pathmaxrxt)
3690 				trans->pathmaxrxt = val.spt_pathmaxrxt;
3691 			trans->pf_retrans = val.spt_pathpfthld;
3692 		}
3693 
3694 		if (val.spt_pathmaxrxt)
3695 			asoc->pathmaxrxt = val.spt_pathmaxrxt;
3696 		asoc->pf_retrans = val.spt_pathpfthld;
3697 	} else {
3698 		trans = sctp_addr_id2transport(sk, &val.spt_address,
3699 					       val.spt_assoc_id);
3700 		if (!trans)
3701 			return -ENOENT;
3702 
3703 		if (val.spt_pathmaxrxt)
3704 			trans->pathmaxrxt = val.spt_pathmaxrxt;
3705 		trans->pf_retrans = val.spt_pathpfthld;
3706 	}
3707 
3708 	return 0;
3709 }
3710 
3711 static int sctp_setsockopt_recvrcvinfo(struct sock *sk,
3712 				       char __user *optval,
3713 				       unsigned int optlen)
3714 {
3715 	int val;
3716 
3717 	if (optlen < sizeof(int))
3718 		return -EINVAL;
3719 	if (get_user(val, (int __user *) optval))
3720 		return -EFAULT;
3721 
3722 	sctp_sk(sk)->recvrcvinfo = (val == 0) ? 0 : 1;
3723 
3724 	return 0;
3725 }
3726 
3727 static int sctp_setsockopt_recvnxtinfo(struct sock *sk,
3728 				       char __user *optval,
3729 				       unsigned int optlen)
3730 {
3731 	int val;
3732 
3733 	if (optlen < sizeof(int))
3734 		return -EINVAL;
3735 	if (get_user(val, (int __user *) optval))
3736 		return -EFAULT;
3737 
3738 	sctp_sk(sk)->recvnxtinfo = (val == 0) ? 0 : 1;
3739 
3740 	return 0;
3741 }
3742 
3743 static int sctp_setsockopt_pr_supported(struct sock *sk,
3744 					char __user *optval,
3745 					unsigned int optlen)
3746 {
3747 	struct sctp_assoc_value params;
3748 	struct sctp_association *asoc;
3749 	int retval = -EINVAL;
3750 
3751 	if (optlen != sizeof(params))
3752 		goto out;
3753 
3754 	if (copy_from_user(&params, optval, optlen)) {
3755 		retval = -EFAULT;
3756 		goto out;
3757 	}
3758 
3759 	asoc = sctp_id2assoc(sk, params.assoc_id);
3760 	if (asoc) {
3761 		asoc->prsctp_enable = !!params.assoc_value;
3762 	} else if (!params.assoc_id) {
3763 		struct sctp_sock *sp = sctp_sk(sk);
3764 
3765 		sp->ep->prsctp_enable = !!params.assoc_value;
3766 	} else {
3767 		goto out;
3768 	}
3769 
3770 	retval = 0;
3771 
3772 out:
3773 	return retval;
3774 }
3775 
3776 static int sctp_setsockopt_default_prinfo(struct sock *sk,
3777 					  char __user *optval,
3778 					  unsigned int optlen)
3779 {
3780 	struct sctp_default_prinfo info;
3781 	struct sctp_association *asoc;
3782 	int retval = -EINVAL;
3783 
3784 	if (optlen != sizeof(info))
3785 		goto out;
3786 
3787 	if (copy_from_user(&info, optval, sizeof(info))) {
3788 		retval = -EFAULT;
3789 		goto out;
3790 	}
3791 
3792 	if (info.pr_policy & ~SCTP_PR_SCTP_MASK)
3793 		goto out;
3794 
3795 	if (info.pr_policy == SCTP_PR_SCTP_NONE)
3796 		info.pr_value = 0;
3797 
3798 	asoc = sctp_id2assoc(sk, info.pr_assoc_id);
3799 	if (asoc) {
3800 		SCTP_PR_SET_POLICY(asoc->default_flags, info.pr_policy);
3801 		asoc->default_timetolive = info.pr_value;
3802 	} else if (!info.pr_assoc_id) {
3803 		struct sctp_sock *sp = sctp_sk(sk);
3804 
3805 		SCTP_PR_SET_POLICY(sp->default_flags, info.pr_policy);
3806 		sp->default_timetolive = info.pr_value;
3807 	} else {
3808 		goto out;
3809 	}
3810 
3811 	retval = 0;
3812 
3813 out:
3814 	return retval;
3815 }
3816 
3817 static int sctp_setsockopt_reconfig_supported(struct sock *sk,
3818 					      char __user *optval,
3819 					      unsigned int optlen)
3820 {
3821 	struct sctp_assoc_value params;
3822 	struct sctp_association *asoc;
3823 	int retval = -EINVAL;
3824 
3825 	if (optlen != sizeof(params))
3826 		goto out;
3827 
3828 	if (copy_from_user(&params, optval, optlen)) {
3829 		retval = -EFAULT;
3830 		goto out;
3831 	}
3832 
3833 	asoc = sctp_id2assoc(sk, params.assoc_id);
3834 	if (asoc) {
3835 		asoc->reconf_enable = !!params.assoc_value;
3836 	} else if (!params.assoc_id) {
3837 		struct sctp_sock *sp = sctp_sk(sk);
3838 
3839 		sp->ep->reconf_enable = !!params.assoc_value;
3840 	} else {
3841 		goto out;
3842 	}
3843 
3844 	retval = 0;
3845 
3846 out:
3847 	return retval;
3848 }
3849 
3850 static int sctp_setsockopt_enable_strreset(struct sock *sk,
3851 					   char __user *optval,
3852 					   unsigned int optlen)
3853 {
3854 	struct sctp_assoc_value params;
3855 	struct sctp_association *asoc;
3856 	int retval = -EINVAL;
3857 
3858 	if (optlen != sizeof(params))
3859 		goto out;
3860 
3861 	if (copy_from_user(&params, optval, optlen)) {
3862 		retval = -EFAULT;
3863 		goto out;
3864 	}
3865 
3866 	if (params.assoc_value & (~SCTP_ENABLE_STRRESET_MASK))
3867 		goto out;
3868 
3869 	asoc = sctp_id2assoc(sk, params.assoc_id);
3870 	if (asoc) {
3871 		asoc->strreset_enable = params.assoc_value;
3872 	} else if (!params.assoc_id) {
3873 		struct sctp_sock *sp = sctp_sk(sk);
3874 
3875 		sp->ep->strreset_enable = params.assoc_value;
3876 	} else {
3877 		goto out;
3878 	}
3879 
3880 	retval = 0;
3881 
3882 out:
3883 	return retval;
3884 }
3885 
3886 static int sctp_setsockopt_reset_streams(struct sock *sk,
3887 					 char __user *optval,
3888 					 unsigned int optlen)
3889 {
3890 	struct sctp_reset_streams *params;
3891 	struct sctp_association *asoc;
3892 	int retval = -EINVAL;
3893 
3894 	if (optlen < sizeof(struct sctp_reset_streams))
3895 		return -EINVAL;
3896 
3897 	params = memdup_user(optval, optlen);
3898 	if (IS_ERR(params))
3899 		return PTR_ERR(params);
3900 
3901 	asoc = sctp_id2assoc(sk, params->srs_assoc_id);
3902 	if (!asoc)
3903 		goto out;
3904 
3905 	retval = sctp_send_reset_streams(asoc, params);
3906 
3907 out:
3908 	kfree(params);
3909 	return retval;
3910 }
3911 
3912 static int sctp_setsockopt_reset_assoc(struct sock *sk,
3913 				       char __user *optval,
3914 				       unsigned int optlen)
3915 {
3916 	struct sctp_association *asoc;
3917 	sctp_assoc_t associd;
3918 	int retval = -EINVAL;
3919 
3920 	if (optlen != sizeof(associd))
3921 		goto out;
3922 
3923 	if (copy_from_user(&associd, optval, optlen)) {
3924 		retval = -EFAULT;
3925 		goto out;
3926 	}
3927 
3928 	asoc = sctp_id2assoc(sk, associd);
3929 	if (!asoc)
3930 		goto out;
3931 
3932 	retval = sctp_send_reset_assoc(asoc);
3933 
3934 out:
3935 	return retval;
3936 }
3937 
3938 static int sctp_setsockopt_add_streams(struct sock *sk,
3939 				       char __user *optval,
3940 				       unsigned int optlen)
3941 {
3942 	struct sctp_association *asoc;
3943 	struct sctp_add_streams params;
3944 	int retval = -EINVAL;
3945 
3946 	if (optlen != sizeof(params))
3947 		goto out;
3948 
3949 	if (copy_from_user(&params, optval, optlen)) {
3950 		retval = -EFAULT;
3951 		goto out;
3952 	}
3953 
3954 	asoc = sctp_id2assoc(sk, params.sas_assoc_id);
3955 	if (!asoc)
3956 		goto out;
3957 
3958 	retval = sctp_send_add_streams(asoc, &params);
3959 
3960 out:
3961 	return retval;
3962 }
3963 
3964 static int sctp_setsockopt_scheduler(struct sock *sk,
3965 				     char __user *optval,
3966 				     unsigned int optlen)
3967 {
3968 	struct sctp_association *asoc;
3969 	struct sctp_assoc_value params;
3970 	int retval = -EINVAL;
3971 
3972 	if (optlen < sizeof(params))
3973 		goto out;
3974 
3975 	optlen = sizeof(params);
3976 	if (copy_from_user(&params, optval, optlen)) {
3977 		retval = -EFAULT;
3978 		goto out;
3979 	}
3980 
3981 	if (params.assoc_value > SCTP_SS_MAX)
3982 		goto out;
3983 
3984 	asoc = sctp_id2assoc(sk, params.assoc_id);
3985 	if (!asoc)
3986 		goto out;
3987 
3988 	retval = sctp_sched_set_sched(asoc, params.assoc_value);
3989 
3990 out:
3991 	return retval;
3992 }
3993 
3994 static int sctp_setsockopt_scheduler_value(struct sock *sk,
3995 					   char __user *optval,
3996 					   unsigned int optlen)
3997 {
3998 	struct sctp_association *asoc;
3999 	struct sctp_stream_value params;
4000 	int retval = -EINVAL;
4001 
4002 	if (optlen < sizeof(params))
4003 		goto out;
4004 
4005 	optlen = sizeof(params);
4006 	if (copy_from_user(&params, optval, optlen)) {
4007 		retval = -EFAULT;
4008 		goto out;
4009 	}
4010 
4011 	asoc = sctp_id2assoc(sk, params.assoc_id);
4012 	if (!asoc)
4013 		goto out;
4014 
4015 	retval = sctp_sched_set_value(asoc, params.stream_id,
4016 				      params.stream_value, GFP_KERNEL);
4017 
4018 out:
4019 	return retval;
4020 }
4021 
4022 /* API 6.2 setsockopt(), getsockopt()
4023  *
4024  * Applications use setsockopt() and getsockopt() to set or retrieve
4025  * socket options.  Socket options are used to change the default
4026  * behavior of sockets calls.  They are described in Section 7.
4027  *
4028  * The syntax is:
4029  *
4030  *   ret = getsockopt(int sd, int level, int optname, void __user *optval,
4031  *                    int __user *optlen);
4032  *   ret = setsockopt(int sd, int level, int optname, const void __user *optval,
4033  *                    int optlen);
4034  *
4035  *   sd      - the socket descript.
4036  *   level   - set to IPPROTO_SCTP for all SCTP options.
4037  *   optname - the option name.
4038  *   optval  - the buffer to store the value of the option.
4039  *   optlen  - the size of the buffer.
4040  */
4041 static int sctp_setsockopt(struct sock *sk, int level, int optname,
4042 			   char __user *optval, unsigned int optlen)
4043 {
4044 	int retval = 0;
4045 
4046 	pr_debug("%s: sk:%p, optname:%d\n", __func__, sk, optname);
4047 
4048 	/* I can hardly begin to describe how wrong this is.  This is
4049 	 * so broken as to be worse than useless.  The API draft
4050 	 * REALLY is NOT helpful here...  I am not convinced that the
4051 	 * semantics of setsockopt() with a level OTHER THAN SOL_SCTP
4052 	 * are at all well-founded.
4053 	 */
4054 	if (level != SOL_SCTP) {
4055 		struct sctp_af *af = sctp_sk(sk)->pf->af;
4056 		retval = af->setsockopt(sk, level, optname, optval, optlen);
4057 		goto out_nounlock;
4058 	}
4059 
4060 	lock_sock(sk);
4061 
4062 	switch (optname) {
4063 	case SCTP_SOCKOPT_BINDX_ADD:
4064 		/* 'optlen' is the size of the addresses buffer. */
4065 		retval = sctp_setsockopt_bindx(sk, (struct sockaddr __user *)optval,
4066 					       optlen, SCTP_BINDX_ADD_ADDR);
4067 		break;
4068 
4069 	case SCTP_SOCKOPT_BINDX_REM:
4070 		/* 'optlen' is the size of the addresses buffer. */
4071 		retval = sctp_setsockopt_bindx(sk, (struct sockaddr __user *)optval,
4072 					       optlen, SCTP_BINDX_REM_ADDR);
4073 		break;
4074 
4075 	case SCTP_SOCKOPT_CONNECTX_OLD:
4076 		/* 'optlen' is the size of the addresses buffer. */
4077 		retval = sctp_setsockopt_connectx_old(sk,
4078 					    (struct sockaddr __user *)optval,
4079 					    optlen);
4080 		break;
4081 
4082 	case SCTP_SOCKOPT_CONNECTX:
4083 		/* 'optlen' is the size of the addresses buffer. */
4084 		retval = sctp_setsockopt_connectx(sk,
4085 					    (struct sockaddr __user *)optval,
4086 					    optlen);
4087 		break;
4088 
4089 	case SCTP_DISABLE_FRAGMENTS:
4090 		retval = sctp_setsockopt_disable_fragments(sk, optval, optlen);
4091 		break;
4092 
4093 	case SCTP_EVENTS:
4094 		retval = sctp_setsockopt_events(sk, optval, optlen);
4095 		break;
4096 
4097 	case SCTP_AUTOCLOSE:
4098 		retval = sctp_setsockopt_autoclose(sk, optval, optlen);
4099 		break;
4100 
4101 	case SCTP_PEER_ADDR_PARAMS:
4102 		retval = sctp_setsockopt_peer_addr_params(sk, optval, optlen);
4103 		break;
4104 
4105 	case SCTP_DELAYED_SACK:
4106 		retval = sctp_setsockopt_delayed_ack(sk, optval, optlen);
4107 		break;
4108 	case SCTP_PARTIAL_DELIVERY_POINT:
4109 		retval = sctp_setsockopt_partial_delivery_point(sk, optval, optlen);
4110 		break;
4111 
4112 	case SCTP_INITMSG:
4113 		retval = sctp_setsockopt_initmsg(sk, optval, optlen);
4114 		break;
4115 	case SCTP_DEFAULT_SEND_PARAM:
4116 		retval = sctp_setsockopt_default_send_param(sk, optval,
4117 							    optlen);
4118 		break;
4119 	case SCTP_DEFAULT_SNDINFO:
4120 		retval = sctp_setsockopt_default_sndinfo(sk, optval, optlen);
4121 		break;
4122 	case SCTP_PRIMARY_ADDR:
4123 		retval = sctp_setsockopt_primary_addr(sk, optval, optlen);
4124 		break;
4125 	case SCTP_SET_PEER_PRIMARY_ADDR:
4126 		retval = sctp_setsockopt_peer_primary_addr(sk, optval, optlen);
4127 		break;
4128 	case SCTP_NODELAY:
4129 		retval = sctp_setsockopt_nodelay(sk, optval, optlen);
4130 		break;
4131 	case SCTP_RTOINFO:
4132 		retval = sctp_setsockopt_rtoinfo(sk, optval, optlen);
4133 		break;
4134 	case SCTP_ASSOCINFO:
4135 		retval = sctp_setsockopt_associnfo(sk, optval, optlen);
4136 		break;
4137 	case SCTP_I_WANT_MAPPED_V4_ADDR:
4138 		retval = sctp_setsockopt_mappedv4(sk, optval, optlen);
4139 		break;
4140 	case SCTP_MAXSEG:
4141 		retval = sctp_setsockopt_maxseg(sk, optval, optlen);
4142 		break;
4143 	case SCTP_ADAPTATION_LAYER:
4144 		retval = sctp_setsockopt_adaptation_layer(sk, optval, optlen);
4145 		break;
4146 	case SCTP_CONTEXT:
4147 		retval = sctp_setsockopt_context(sk, optval, optlen);
4148 		break;
4149 	case SCTP_FRAGMENT_INTERLEAVE:
4150 		retval = sctp_setsockopt_fragment_interleave(sk, optval, optlen);
4151 		break;
4152 	case SCTP_MAX_BURST:
4153 		retval = sctp_setsockopt_maxburst(sk, optval, optlen);
4154 		break;
4155 	case SCTP_AUTH_CHUNK:
4156 		retval = sctp_setsockopt_auth_chunk(sk, optval, optlen);
4157 		break;
4158 	case SCTP_HMAC_IDENT:
4159 		retval = sctp_setsockopt_hmac_ident(sk, optval, optlen);
4160 		break;
4161 	case SCTP_AUTH_KEY:
4162 		retval = sctp_setsockopt_auth_key(sk, optval, optlen);
4163 		break;
4164 	case SCTP_AUTH_ACTIVE_KEY:
4165 		retval = sctp_setsockopt_active_key(sk, optval, optlen);
4166 		break;
4167 	case SCTP_AUTH_DELETE_KEY:
4168 		retval = sctp_setsockopt_del_key(sk, optval, optlen);
4169 		break;
4170 	case SCTP_AUTO_ASCONF:
4171 		retval = sctp_setsockopt_auto_asconf(sk, optval, optlen);
4172 		break;
4173 	case SCTP_PEER_ADDR_THLDS:
4174 		retval = sctp_setsockopt_paddr_thresholds(sk, optval, optlen);
4175 		break;
4176 	case SCTP_RECVRCVINFO:
4177 		retval = sctp_setsockopt_recvrcvinfo(sk, optval, optlen);
4178 		break;
4179 	case SCTP_RECVNXTINFO:
4180 		retval = sctp_setsockopt_recvnxtinfo(sk, optval, optlen);
4181 		break;
4182 	case SCTP_PR_SUPPORTED:
4183 		retval = sctp_setsockopt_pr_supported(sk, optval, optlen);
4184 		break;
4185 	case SCTP_DEFAULT_PRINFO:
4186 		retval = sctp_setsockopt_default_prinfo(sk, optval, optlen);
4187 		break;
4188 	case SCTP_RECONFIG_SUPPORTED:
4189 		retval = sctp_setsockopt_reconfig_supported(sk, optval, optlen);
4190 		break;
4191 	case SCTP_ENABLE_STREAM_RESET:
4192 		retval = sctp_setsockopt_enable_strreset(sk, optval, optlen);
4193 		break;
4194 	case SCTP_RESET_STREAMS:
4195 		retval = sctp_setsockopt_reset_streams(sk, optval, optlen);
4196 		break;
4197 	case SCTP_RESET_ASSOC:
4198 		retval = sctp_setsockopt_reset_assoc(sk, optval, optlen);
4199 		break;
4200 	case SCTP_ADD_STREAMS:
4201 		retval = sctp_setsockopt_add_streams(sk, optval, optlen);
4202 		break;
4203 	case SCTP_STREAM_SCHEDULER:
4204 		retval = sctp_setsockopt_scheduler(sk, optval, optlen);
4205 		break;
4206 	case SCTP_STREAM_SCHEDULER_VALUE:
4207 		retval = sctp_setsockopt_scheduler_value(sk, optval, optlen);
4208 		break;
4209 	default:
4210 		retval = -ENOPROTOOPT;
4211 		break;
4212 	}
4213 
4214 	release_sock(sk);
4215 
4216 out_nounlock:
4217 	return retval;
4218 }
4219 
4220 /* API 3.1.6 connect() - UDP Style Syntax
4221  *
4222  * An application may use the connect() call in the UDP model to initiate an
4223  * association without sending data.
4224  *
4225  * The syntax is:
4226  *
4227  * ret = connect(int sd, const struct sockaddr *nam, socklen_t len);
4228  *
4229  * sd: the socket descriptor to have a new association added to.
4230  *
4231  * nam: the address structure (either struct sockaddr_in or struct
4232  *    sockaddr_in6 defined in RFC2553 [7]).
4233  *
4234  * len: the size of the address.
4235  */
4236 static int sctp_connect(struct sock *sk, struct sockaddr *addr,
4237 			int addr_len)
4238 {
4239 	int err = 0;
4240 	struct sctp_af *af;
4241 
4242 	lock_sock(sk);
4243 
4244 	pr_debug("%s: sk:%p, sockaddr:%p, addr_len:%d\n", __func__, sk,
4245 		 addr, addr_len);
4246 
4247 	/* Validate addr_len before calling common connect/connectx routine. */
4248 	af = sctp_get_af_specific(addr->sa_family);
4249 	if (!af || addr_len < af->sockaddr_len) {
4250 		err = -EINVAL;
4251 	} else {
4252 		/* Pass correct addr len to common routine (so it knows there
4253 		 * is only one address being passed.
4254 		 */
4255 		err = __sctp_connect(sk, addr, af->sockaddr_len, NULL);
4256 	}
4257 
4258 	release_sock(sk);
4259 	return err;
4260 }
4261 
4262 /* FIXME: Write comments. */
4263 static int sctp_disconnect(struct sock *sk, int flags)
4264 {
4265 	return -EOPNOTSUPP; /* STUB */
4266 }
4267 
4268 /* 4.1.4 accept() - TCP Style Syntax
4269  *
4270  * Applications use accept() call to remove an established SCTP
4271  * association from the accept queue of the endpoint.  A new socket
4272  * descriptor will be returned from accept() to represent the newly
4273  * formed association.
4274  */
4275 static struct sock *sctp_accept(struct sock *sk, int flags, int *err, bool kern)
4276 {
4277 	struct sctp_sock *sp;
4278 	struct sctp_endpoint *ep;
4279 	struct sock *newsk = NULL;
4280 	struct sctp_association *asoc;
4281 	long timeo;
4282 	int error = 0;
4283 
4284 	lock_sock(sk);
4285 
4286 	sp = sctp_sk(sk);
4287 	ep = sp->ep;
4288 
4289 	if (!sctp_style(sk, TCP)) {
4290 		error = -EOPNOTSUPP;
4291 		goto out;
4292 	}
4293 
4294 	if (!sctp_sstate(sk, LISTENING)) {
4295 		error = -EINVAL;
4296 		goto out;
4297 	}
4298 
4299 	timeo = sock_rcvtimeo(sk, flags & O_NONBLOCK);
4300 
4301 	error = sctp_wait_for_accept(sk, timeo);
4302 	if (error)
4303 		goto out;
4304 
4305 	/* We treat the list of associations on the endpoint as the accept
4306 	 * queue and pick the first association on the list.
4307 	 */
4308 	asoc = list_entry(ep->asocs.next, struct sctp_association, asocs);
4309 
4310 	newsk = sp->pf->create_accept_sk(sk, asoc, kern);
4311 	if (!newsk) {
4312 		error = -ENOMEM;
4313 		goto out;
4314 	}
4315 
4316 	/* Populate the fields of the newsk from the oldsk and migrate the
4317 	 * asoc to the newsk.
4318 	 */
4319 	sctp_sock_migrate(sk, newsk, asoc, SCTP_SOCKET_TCP);
4320 
4321 out:
4322 	release_sock(sk);
4323 	*err = error;
4324 	return newsk;
4325 }
4326 
4327 /* The SCTP ioctl handler. */
4328 static int sctp_ioctl(struct sock *sk, int cmd, unsigned long arg)
4329 {
4330 	int rc = -ENOTCONN;
4331 
4332 	lock_sock(sk);
4333 
4334 	/*
4335 	 * SEQPACKET-style sockets in LISTENING state are valid, for
4336 	 * SCTP, so only discard TCP-style sockets in LISTENING state.
4337 	 */
4338 	if (sctp_style(sk, TCP) && sctp_sstate(sk, LISTENING))
4339 		goto out;
4340 
4341 	switch (cmd) {
4342 	case SIOCINQ: {
4343 		struct sk_buff *skb;
4344 		unsigned int amount = 0;
4345 
4346 		skb = skb_peek(&sk->sk_receive_queue);
4347 		if (skb != NULL) {
4348 			/*
4349 			 * We will only return the amount of this packet since
4350 			 * that is all that will be read.
4351 			 */
4352 			amount = skb->len;
4353 		}
4354 		rc = put_user(amount, (int __user *)arg);
4355 		break;
4356 	}
4357 	default:
4358 		rc = -ENOIOCTLCMD;
4359 		break;
4360 	}
4361 out:
4362 	release_sock(sk);
4363 	return rc;
4364 }
4365 
4366 /* This is the function which gets called during socket creation to
4367  * initialized the SCTP-specific portion of the sock.
4368  * The sock structure should already be zero-filled memory.
4369  */
4370 static int sctp_init_sock(struct sock *sk)
4371 {
4372 	struct net *net = sock_net(sk);
4373 	struct sctp_sock *sp;
4374 
4375 	pr_debug("%s: sk:%p\n", __func__, sk);
4376 
4377 	sp = sctp_sk(sk);
4378 
4379 	/* Initialize the SCTP per socket area.  */
4380 	switch (sk->sk_type) {
4381 	case SOCK_SEQPACKET:
4382 		sp->type = SCTP_SOCKET_UDP;
4383 		break;
4384 	case SOCK_STREAM:
4385 		sp->type = SCTP_SOCKET_TCP;
4386 		break;
4387 	default:
4388 		return -ESOCKTNOSUPPORT;
4389 	}
4390 
4391 	sk->sk_gso_type = SKB_GSO_SCTP;
4392 
4393 	/* Initialize default send parameters. These parameters can be
4394 	 * modified with the SCTP_DEFAULT_SEND_PARAM socket option.
4395 	 */
4396 	sp->default_stream = 0;
4397 	sp->default_ppid = 0;
4398 	sp->default_flags = 0;
4399 	sp->default_context = 0;
4400 	sp->default_timetolive = 0;
4401 
4402 	sp->default_rcv_context = 0;
4403 	sp->max_burst = net->sctp.max_burst;
4404 
4405 	sp->sctp_hmac_alg = net->sctp.sctp_hmac_alg;
4406 
4407 	/* Initialize default setup parameters. These parameters
4408 	 * can be modified with the SCTP_INITMSG socket option or
4409 	 * overridden by the SCTP_INIT CMSG.
4410 	 */
4411 	sp->initmsg.sinit_num_ostreams   = sctp_max_outstreams;
4412 	sp->initmsg.sinit_max_instreams  = sctp_max_instreams;
4413 	sp->initmsg.sinit_max_attempts   = net->sctp.max_retrans_init;
4414 	sp->initmsg.sinit_max_init_timeo = net->sctp.rto_max;
4415 
4416 	/* Initialize default RTO related parameters.  These parameters can
4417 	 * be modified for with the SCTP_RTOINFO socket option.
4418 	 */
4419 	sp->rtoinfo.srto_initial = net->sctp.rto_initial;
4420 	sp->rtoinfo.srto_max     = net->sctp.rto_max;
4421 	sp->rtoinfo.srto_min     = net->sctp.rto_min;
4422 
4423 	/* Initialize default association related parameters. These parameters
4424 	 * can be modified with the SCTP_ASSOCINFO socket option.
4425 	 */
4426 	sp->assocparams.sasoc_asocmaxrxt = net->sctp.max_retrans_association;
4427 	sp->assocparams.sasoc_number_peer_destinations = 0;
4428 	sp->assocparams.sasoc_peer_rwnd = 0;
4429 	sp->assocparams.sasoc_local_rwnd = 0;
4430 	sp->assocparams.sasoc_cookie_life = net->sctp.valid_cookie_life;
4431 
4432 	/* Initialize default event subscriptions. By default, all the
4433 	 * options are off.
4434 	 */
4435 	memset(&sp->subscribe, 0, sizeof(struct sctp_event_subscribe));
4436 
4437 	/* Default Peer Address Parameters.  These defaults can
4438 	 * be modified via SCTP_PEER_ADDR_PARAMS
4439 	 */
4440 	sp->hbinterval  = net->sctp.hb_interval;
4441 	sp->pathmaxrxt  = net->sctp.max_retrans_path;
4442 	sp->pathmtu     = 0; /* allow default discovery */
4443 	sp->sackdelay   = net->sctp.sack_timeout;
4444 	sp->sackfreq	= 2;
4445 	sp->param_flags = SPP_HB_ENABLE |
4446 			  SPP_PMTUD_ENABLE |
4447 			  SPP_SACKDELAY_ENABLE;
4448 
4449 	/* If enabled no SCTP message fragmentation will be performed.
4450 	 * Configure through SCTP_DISABLE_FRAGMENTS socket option.
4451 	 */
4452 	sp->disable_fragments = 0;
4453 
4454 	/* Enable Nagle algorithm by default.  */
4455 	sp->nodelay           = 0;
4456 
4457 	sp->recvrcvinfo = 0;
4458 	sp->recvnxtinfo = 0;
4459 
4460 	/* Enable by default. */
4461 	sp->v4mapped          = 1;
4462 
4463 	/* Auto-close idle associations after the configured
4464 	 * number of seconds.  A value of 0 disables this
4465 	 * feature.  Configure through the SCTP_AUTOCLOSE socket option,
4466 	 * for UDP-style sockets only.
4467 	 */
4468 	sp->autoclose         = 0;
4469 
4470 	/* User specified fragmentation limit. */
4471 	sp->user_frag         = 0;
4472 
4473 	sp->adaptation_ind = 0;
4474 
4475 	sp->pf = sctp_get_pf_specific(sk->sk_family);
4476 
4477 	/* Control variables for partial data delivery. */
4478 	atomic_set(&sp->pd_mode, 0);
4479 	skb_queue_head_init(&sp->pd_lobby);
4480 	sp->frag_interleave = 0;
4481 
4482 	/* Create a per socket endpoint structure.  Even if we
4483 	 * change the data structure relationships, this may still
4484 	 * be useful for storing pre-connect address information.
4485 	 */
4486 	sp->ep = sctp_endpoint_new(sk, GFP_KERNEL);
4487 	if (!sp->ep)
4488 		return -ENOMEM;
4489 
4490 	sp->hmac = NULL;
4491 
4492 	sk->sk_destruct = sctp_destruct_sock;
4493 
4494 	SCTP_DBG_OBJCNT_INC(sock);
4495 
4496 	local_bh_disable();
4497 	percpu_counter_inc(&sctp_sockets_allocated);
4498 	sock_prot_inuse_add(net, sk->sk_prot, 1);
4499 
4500 	/* Nothing can fail after this block, otherwise
4501 	 * sctp_destroy_sock() will be called without addr_wq_lock held
4502 	 */
4503 	if (net->sctp.default_auto_asconf) {
4504 		spin_lock(&sock_net(sk)->sctp.addr_wq_lock);
4505 		list_add_tail(&sp->auto_asconf_list,
4506 		    &net->sctp.auto_asconf_splist);
4507 		sp->do_auto_asconf = 1;
4508 		spin_unlock(&sock_net(sk)->sctp.addr_wq_lock);
4509 	} else {
4510 		sp->do_auto_asconf = 0;
4511 	}
4512 
4513 	local_bh_enable();
4514 
4515 	return 0;
4516 }
4517 
4518 /* Cleanup any SCTP per socket resources. Must be called with
4519  * sock_net(sk)->sctp.addr_wq_lock held if sp->do_auto_asconf is true
4520  */
4521 static void sctp_destroy_sock(struct sock *sk)
4522 {
4523 	struct sctp_sock *sp;
4524 
4525 	pr_debug("%s: sk:%p\n", __func__, sk);
4526 
4527 	/* Release our hold on the endpoint. */
4528 	sp = sctp_sk(sk);
4529 	/* This could happen during socket init, thus we bail out
4530 	 * early, since the rest of the below is not setup either.
4531 	 */
4532 	if (sp->ep == NULL)
4533 		return;
4534 
4535 	if (sp->do_auto_asconf) {
4536 		sp->do_auto_asconf = 0;
4537 		list_del(&sp->auto_asconf_list);
4538 	}
4539 	sctp_endpoint_free(sp->ep);
4540 	local_bh_disable();
4541 	percpu_counter_dec(&sctp_sockets_allocated);
4542 	sock_prot_inuse_add(sock_net(sk), sk->sk_prot, -1);
4543 	local_bh_enable();
4544 }
4545 
4546 /* Triggered when there are no references on the socket anymore */
4547 static void sctp_destruct_sock(struct sock *sk)
4548 {
4549 	struct sctp_sock *sp = sctp_sk(sk);
4550 
4551 	/* Free up the HMAC transform. */
4552 	crypto_free_shash(sp->hmac);
4553 
4554 	inet_sock_destruct(sk);
4555 }
4556 
4557 /* API 4.1.7 shutdown() - TCP Style Syntax
4558  *     int shutdown(int socket, int how);
4559  *
4560  *     sd      - the socket descriptor of the association to be closed.
4561  *     how     - Specifies the type of shutdown.  The  values  are
4562  *               as follows:
4563  *               SHUT_RD
4564  *                     Disables further receive operations. No SCTP
4565  *                     protocol action is taken.
4566  *               SHUT_WR
4567  *                     Disables further send operations, and initiates
4568  *                     the SCTP shutdown sequence.
4569  *               SHUT_RDWR
4570  *                     Disables further send  and  receive  operations
4571  *                     and initiates the SCTP shutdown sequence.
4572  */
4573 static void sctp_shutdown(struct sock *sk, int how)
4574 {
4575 	struct net *net = sock_net(sk);
4576 	struct sctp_endpoint *ep;
4577 
4578 	if (!sctp_style(sk, TCP))
4579 		return;
4580 
4581 	ep = sctp_sk(sk)->ep;
4582 	if (how & SEND_SHUTDOWN && !list_empty(&ep->asocs)) {
4583 		struct sctp_association *asoc;
4584 
4585 		sk->sk_state = SCTP_SS_CLOSING;
4586 		asoc = list_entry(ep->asocs.next,
4587 				  struct sctp_association, asocs);
4588 		sctp_primitive_SHUTDOWN(net, asoc, NULL);
4589 	}
4590 }
4591 
4592 int sctp_get_sctp_info(struct sock *sk, struct sctp_association *asoc,
4593 		       struct sctp_info *info)
4594 {
4595 	struct sctp_transport *prim;
4596 	struct list_head *pos;
4597 	int mask;
4598 
4599 	memset(info, 0, sizeof(*info));
4600 	if (!asoc) {
4601 		struct sctp_sock *sp = sctp_sk(sk);
4602 
4603 		info->sctpi_s_autoclose = sp->autoclose;
4604 		info->sctpi_s_adaptation_ind = sp->adaptation_ind;
4605 		info->sctpi_s_pd_point = sp->pd_point;
4606 		info->sctpi_s_nodelay = sp->nodelay;
4607 		info->sctpi_s_disable_fragments = sp->disable_fragments;
4608 		info->sctpi_s_v4mapped = sp->v4mapped;
4609 		info->sctpi_s_frag_interleave = sp->frag_interleave;
4610 		info->sctpi_s_type = sp->type;
4611 
4612 		return 0;
4613 	}
4614 
4615 	info->sctpi_tag = asoc->c.my_vtag;
4616 	info->sctpi_state = asoc->state;
4617 	info->sctpi_rwnd = asoc->a_rwnd;
4618 	info->sctpi_unackdata = asoc->unack_data;
4619 	info->sctpi_penddata = sctp_tsnmap_pending(&asoc->peer.tsn_map);
4620 	info->sctpi_instrms = asoc->stream.incnt;
4621 	info->sctpi_outstrms = asoc->stream.outcnt;
4622 	list_for_each(pos, &asoc->base.inqueue.in_chunk_list)
4623 		info->sctpi_inqueue++;
4624 	list_for_each(pos, &asoc->outqueue.out_chunk_list)
4625 		info->sctpi_outqueue++;
4626 	info->sctpi_overall_error = asoc->overall_error_count;
4627 	info->sctpi_max_burst = asoc->max_burst;
4628 	info->sctpi_maxseg = asoc->frag_point;
4629 	info->sctpi_peer_rwnd = asoc->peer.rwnd;
4630 	info->sctpi_peer_tag = asoc->c.peer_vtag;
4631 
4632 	mask = asoc->peer.ecn_capable << 1;
4633 	mask = (mask | asoc->peer.ipv4_address) << 1;
4634 	mask = (mask | asoc->peer.ipv6_address) << 1;
4635 	mask = (mask | asoc->peer.hostname_address) << 1;
4636 	mask = (mask | asoc->peer.asconf_capable) << 1;
4637 	mask = (mask | asoc->peer.prsctp_capable) << 1;
4638 	mask = (mask | asoc->peer.auth_capable);
4639 	info->sctpi_peer_capable = mask;
4640 	mask = asoc->peer.sack_needed << 1;
4641 	mask = (mask | asoc->peer.sack_generation) << 1;
4642 	mask = (mask | asoc->peer.zero_window_announced);
4643 	info->sctpi_peer_sack = mask;
4644 
4645 	info->sctpi_isacks = asoc->stats.isacks;
4646 	info->sctpi_osacks = asoc->stats.osacks;
4647 	info->sctpi_opackets = asoc->stats.opackets;
4648 	info->sctpi_ipackets = asoc->stats.ipackets;
4649 	info->sctpi_rtxchunks = asoc->stats.rtxchunks;
4650 	info->sctpi_outofseqtsns = asoc->stats.outofseqtsns;
4651 	info->sctpi_idupchunks = asoc->stats.idupchunks;
4652 	info->sctpi_gapcnt = asoc->stats.gapcnt;
4653 	info->sctpi_ouodchunks = asoc->stats.ouodchunks;
4654 	info->sctpi_iuodchunks = asoc->stats.iuodchunks;
4655 	info->sctpi_oodchunks = asoc->stats.oodchunks;
4656 	info->sctpi_iodchunks = asoc->stats.iodchunks;
4657 	info->sctpi_octrlchunks = asoc->stats.octrlchunks;
4658 	info->sctpi_ictrlchunks = asoc->stats.ictrlchunks;
4659 
4660 	prim = asoc->peer.primary_path;
4661 	memcpy(&info->sctpi_p_address, &prim->ipaddr, sizeof(prim->ipaddr));
4662 	info->sctpi_p_state = prim->state;
4663 	info->sctpi_p_cwnd = prim->cwnd;
4664 	info->sctpi_p_srtt = prim->srtt;
4665 	info->sctpi_p_rto = jiffies_to_msecs(prim->rto);
4666 	info->sctpi_p_hbinterval = prim->hbinterval;
4667 	info->sctpi_p_pathmaxrxt = prim->pathmaxrxt;
4668 	info->sctpi_p_sackdelay = jiffies_to_msecs(prim->sackdelay);
4669 	info->sctpi_p_ssthresh = prim->ssthresh;
4670 	info->sctpi_p_partial_bytes_acked = prim->partial_bytes_acked;
4671 	info->sctpi_p_flight_size = prim->flight_size;
4672 	info->sctpi_p_error = prim->error_count;
4673 
4674 	return 0;
4675 }
4676 EXPORT_SYMBOL_GPL(sctp_get_sctp_info);
4677 
4678 /* use callback to avoid exporting the core structure */
4679 int sctp_transport_walk_start(struct rhashtable_iter *iter)
4680 {
4681 	int err;
4682 
4683 	rhltable_walk_enter(&sctp_transport_hashtable, iter);
4684 
4685 	err = rhashtable_walk_start(iter);
4686 	if (err && err != -EAGAIN) {
4687 		rhashtable_walk_stop(iter);
4688 		rhashtable_walk_exit(iter);
4689 		return err;
4690 	}
4691 
4692 	return 0;
4693 }
4694 
4695 void sctp_transport_walk_stop(struct rhashtable_iter *iter)
4696 {
4697 	rhashtable_walk_stop(iter);
4698 	rhashtable_walk_exit(iter);
4699 }
4700 
4701 struct sctp_transport *sctp_transport_get_next(struct net *net,
4702 					       struct rhashtable_iter *iter)
4703 {
4704 	struct sctp_transport *t;
4705 
4706 	t = rhashtable_walk_next(iter);
4707 	for (; t; t = rhashtable_walk_next(iter)) {
4708 		if (IS_ERR(t)) {
4709 			if (PTR_ERR(t) == -EAGAIN)
4710 				continue;
4711 			break;
4712 		}
4713 
4714 		if (net_eq(sock_net(t->asoc->base.sk), net) &&
4715 		    t->asoc->peer.primary_path == t)
4716 			break;
4717 	}
4718 
4719 	return t;
4720 }
4721 
4722 struct sctp_transport *sctp_transport_get_idx(struct net *net,
4723 					      struct rhashtable_iter *iter,
4724 					      int pos)
4725 {
4726 	void *obj = SEQ_START_TOKEN;
4727 
4728 	while (pos && (obj = sctp_transport_get_next(net, iter)) &&
4729 	       !IS_ERR(obj))
4730 		pos--;
4731 
4732 	return obj;
4733 }
4734 
4735 int sctp_for_each_endpoint(int (*cb)(struct sctp_endpoint *, void *),
4736 			   void *p) {
4737 	int err = 0;
4738 	int hash = 0;
4739 	struct sctp_ep_common *epb;
4740 	struct sctp_hashbucket *head;
4741 
4742 	for (head = sctp_ep_hashtable; hash < sctp_ep_hashsize;
4743 	     hash++, head++) {
4744 		read_lock_bh(&head->lock);
4745 		sctp_for_each_hentry(epb, &head->chain) {
4746 			err = cb(sctp_ep(epb), p);
4747 			if (err)
4748 				break;
4749 		}
4750 		read_unlock_bh(&head->lock);
4751 	}
4752 
4753 	return err;
4754 }
4755 EXPORT_SYMBOL_GPL(sctp_for_each_endpoint);
4756 
4757 int sctp_transport_lookup_process(int (*cb)(struct sctp_transport *, void *),
4758 				  struct net *net,
4759 				  const union sctp_addr *laddr,
4760 				  const union sctp_addr *paddr, void *p)
4761 {
4762 	struct sctp_transport *transport;
4763 	int err;
4764 
4765 	rcu_read_lock();
4766 	transport = sctp_addrs_lookup_transport(net, laddr, paddr);
4767 	rcu_read_unlock();
4768 	if (!transport)
4769 		return -ENOENT;
4770 
4771 	err = cb(transport, p);
4772 	sctp_transport_put(transport);
4773 
4774 	return err;
4775 }
4776 EXPORT_SYMBOL_GPL(sctp_transport_lookup_process);
4777 
4778 int sctp_for_each_transport(int (*cb)(struct sctp_transport *, void *),
4779 			    int (*cb_done)(struct sctp_transport *, void *),
4780 			    struct net *net, int *pos, void *p) {
4781 	struct rhashtable_iter hti;
4782 	struct sctp_transport *tsp;
4783 	int ret;
4784 
4785 again:
4786 	ret = sctp_transport_walk_start(&hti);
4787 	if (ret)
4788 		return ret;
4789 
4790 	tsp = sctp_transport_get_idx(net, &hti, *pos + 1);
4791 	for (; !IS_ERR_OR_NULL(tsp); tsp = sctp_transport_get_next(net, &hti)) {
4792 		if (!sctp_transport_hold(tsp))
4793 			continue;
4794 		ret = cb(tsp, p);
4795 		if (ret)
4796 			break;
4797 		(*pos)++;
4798 		sctp_transport_put(tsp);
4799 	}
4800 	sctp_transport_walk_stop(&hti);
4801 
4802 	if (ret) {
4803 		if (cb_done && !cb_done(tsp, p)) {
4804 			(*pos)++;
4805 			sctp_transport_put(tsp);
4806 			goto again;
4807 		}
4808 		sctp_transport_put(tsp);
4809 	}
4810 
4811 	return ret;
4812 }
4813 EXPORT_SYMBOL_GPL(sctp_for_each_transport);
4814 
4815 /* 7.2.1 Association Status (SCTP_STATUS)
4816 
4817  * Applications can retrieve current status information about an
4818  * association, including association state, peer receiver window size,
4819  * number of unacked data chunks, and number of data chunks pending
4820  * receipt.  This information is read-only.
4821  */
4822 static int sctp_getsockopt_sctp_status(struct sock *sk, int len,
4823 				       char __user *optval,
4824 				       int __user *optlen)
4825 {
4826 	struct sctp_status status;
4827 	struct sctp_association *asoc = NULL;
4828 	struct sctp_transport *transport;
4829 	sctp_assoc_t associd;
4830 	int retval = 0;
4831 
4832 	if (len < sizeof(status)) {
4833 		retval = -EINVAL;
4834 		goto out;
4835 	}
4836 
4837 	len = sizeof(status);
4838 	if (copy_from_user(&status, optval, len)) {
4839 		retval = -EFAULT;
4840 		goto out;
4841 	}
4842 
4843 	associd = status.sstat_assoc_id;
4844 	asoc = sctp_id2assoc(sk, associd);
4845 	if (!asoc) {
4846 		retval = -EINVAL;
4847 		goto out;
4848 	}
4849 
4850 	transport = asoc->peer.primary_path;
4851 
4852 	status.sstat_assoc_id = sctp_assoc2id(asoc);
4853 	status.sstat_state = sctp_assoc_to_state(asoc);
4854 	status.sstat_rwnd =  asoc->peer.rwnd;
4855 	status.sstat_unackdata = asoc->unack_data;
4856 
4857 	status.sstat_penddata = sctp_tsnmap_pending(&asoc->peer.tsn_map);
4858 	status.sstat_instrms = asoc->stream.incnt;
4859 	status.sstat_outstrms = asoc->stream.outcnt;
4860 	status.sstat_fragmentation_point = asoc->frag_point;
4861 	status.sstat_primary.spinfo_assoc_id = sctp_assoc2id(transport->asoc);
4862 	memcpy(&status.sstat_primary.spinfo_address, &transport->ipaddr,
4863 			transport->af_specific->sockaddr_len);
4864 	/* Map ipv4 address into v4-mapped-on-v6 address.  */
4865 	sctp_get_pf_specific(sk->sk_family)->addr_to_user(sctp_sk(sk),
4866 		(union sctp_addr *)&status.sstat_primary.spinfo_address);
4867 	status.sstat_primary.spinfo_state = transport->state;
4868 	status.sstat_primary.spinfo_cwnd = transport->cwnd;
4869 	status.sstat_primary.spinfo_srtt = transport->srtt;
4870 	status.sstat_primary.spinfo_rto = jiffies_to_msecs(transport->rto);
4871 	status.sstat_primary.spinfo_mtu = transport->pathmtu;
4872 
4873 	if (status.sstat_primary.spinfo_state == SCTP_UNKNOWN)
4874 		status.sstat_primary.spinfo_state = SCTP_ACTIVE;
4875 
4876 	if (put_user(len, optlen)) {
4877 		retval = -EFAULT;
4878 		goto out;
4879 	}
4880 
4881 	pr_debug("%s: len:%d, state:%d, rwnd:%d, assoc_id:%d\n",
4882 		 __func__, len, status.sstat_state, status.sstat_rwnd,
4883 		 status.sstat_assoc_id);
4884 
4885 	if (copy_to_user(optval, &status, len)) {
4886 		retval = -EFAULT;
4887 		goto out;
4888 	}
4889 
4890 out:
4891 	return retval;
4892 }
4893 
4894 
4895 /* 7.2.2 Peer Address Information (SCTP_GET_PEER_ADDR_INFO)
4896  *
4897  * Applications can retrieve information about a specific peer address
4898  * of an association, including its reachability state, congestion
4899  * window, and retransmission timer values.  This information is
4900  * read-only.
4901  */
4902 static int sctp_getsockopt_peer_addr_info(struct sock *sk, int len,
4903 					  char __user *optval,
4904 					  int __user *optlen)
4905 {
4906 	struct sctp_paddrinfo pinfo;
4907 	struct sctp_transport *transport;
4908 	int retval = 0;
4909 
4910 	if (len < sizeof(pinfo)) {
4911 		retval = -EINVAL;
4912 		goto out;
4913 	}
4914 
4915 	len = sizeof(pinfo);
4916 	if (copy_from_user(&pinfo, optval, len)) {
4917 		retval = -EFAULT;
4918 		goto out;
4919 	}
4920 
4921 	transport = sctp_addr_id2transport(sk, &pinfo.spinfo_address,
4922 					   pinfo.spinfo_assoc_id);
4923 	if (!transport)
4924 		return -EINVAL;
4925 
4926 	pinfo.spinfo_assoc_id = sctp_assoc2id(transport->asoc);
4927 	pinfo.spinfo_state = transport->state;
4928 	pinfo.spinfo_cwnd = transport->cwnd;
4929 	pinfo.spinfo_srtt = transport->srtt;
4930 	pinfo.spinfo_rto = jiffies_to_msecs(transport->rto);
4931 	pinfo.spinfo_mtu = transport->pathmtu;
4932 
4933 	if (pinfo.spinfo_state == SCTP_UNKNOWN)
4934 		pinfo.spinfo_state = SCTP_ACTIVE;
4935 
4936 	if (put_user(len, optlen)) {
4937 		retval = -EFAULT;
4938 		goto out;
4939 	}
4940 
4941 	if (copy_to_user(optval, &pinfo, len)) {
4942 		retval = -EFAULT;
4943 		goto out;
4944 	}
4945 
4946 out:
4947 	return retval;
4948 }
4949 
4950 /* 7.1.12 Enable/Disable message fragmentation (SCTP_DISABLE_FRAGMENTS)
4951  *
4952  * This option is a on/off flag.  If enabled no SCTP message
4953  * fragmentation will be performed.  Instead if a message being sent
4954  * exceeds the current PMTU size, the message will NOT be sent and
4955  * instead a error will be indicated to the user.
4956  */
4957 static int sctp_getsockopt_disable_fragments(struct sock *sk, int len,
4958 					char __user *optval, int __user *optlen)
4959 {
4960 	int val;
4961 
4962 	if (len < sizeof(int))
4963 		return -EINVAL;
4964 
4965 	len = sizeof(int);
4966 	val = (sctp_sk(sk)->disable_fragments == 1);
4967 	if (put_user(len, optlen))
4968 		return -EFAULT;
4969 	if (copy_to_user(optval, &val, len))
4970 		return -EFAULT;
4971 	return 0;
4972 }
4973 
4974 /* 7.1.15 Set notification and ancillary events (SCTP_EVENTS)
4975  *
4976  * This socket option is used to specify various notifications and
4977  * ancillary data the user wishes to receive.
4978  */
4979 static int sctp_getsockopt_events(struct sock *sk, int len, char __user *optval,
4980 				  int __user *optlen)
4981 {
4982 	if (len == 0)
4983 		return -EINVAL;
4984 	if (len > sizeof(struct sctp_event_subscribe))
4985 		len = sizeof(struct sctp_event_subscribe);
4986 	if (put_user(len, optlen))
4987 		return -EFAULT;
4988 	if (copy_to_user(optval, &sctp_sk(sk)->subscribe, len))
4989 		return -EFAULT;
4990 	return 0;
4991 }
4992 
4993 /* 7.1.8 Automatic Close of associations (SCTP_AUTOCLOSE)
4994  *
4995  * This socket option is applicable to the UDP-style socket only.  When
4996  * set it will cause associations that are idle for more than the
4997  * specified number of seconds to automatically close.  An association
4998  * being idle is defined an association that has NOT sent or received
4999  * user data.  The special value of '0' indicates that no automatic
5000  * close of any associations should be performed.  The option expects an
5001  * integer defining the number of seconds of idle time before an
5002  * association is closed.
5003  */
5004 static int sctp_getsockopt_autoclose(struct sock *sk, int len, char __user *optval, int __user *optlen)
5005 {
5006 	/* Applicable to UDP-style socket only */
5007 	if (sctp_style(sk, TCP))
5008 		return -EOPNOTSUPP;
5009 	if (len < sizeof(int))
5010 		return -EINVAL;
5011 	len = sizeof(int);
5012 	if (put_user(len, optlen))
5013 		return -EFAULT;
5014 	if (copy_to_user(optval, &sctp_sk(sk)->autoclose, sizeof(int)))
5015 		return -EFAULT;
5016 	return 0;
5017 }
5018 
5019 /* Helper routine to branch off an association to a new socket.  */
5020 int sctp_do_peeloff(struct sock *sk, sctp_assoc_t id, struct socket **sockp)
5021 {
5022 	struct sctp_association *asoc = sctp_id2assoc(sk, id);
5023 	struct sctp_sock *sp = sctp_sk(sk);
5024 	struct socket *sock;
5025 	int err = 0;
5026 
5027 	/* Do not peel off from one netns to another one. */
5028 	if (!net_eq(current->nsproxy->net_ns, sock_net(sk)))
5029 		return -EINVAL;
5030 
5031 	if (!asoc)
5032 		return -EINVAL;
5033 
5034 	/* An association cannot be branched off from an already peeled-off
5035 	 * socket, nor is this supported for tcp style sockets.
5036 	 */
5037 	if (!sctp_style(sk, UDP))
5038 		return -EINVAL;
5039 
5040 	/* Create a new socket.  */
5041 	err = sock_create(sk->sk_family, SOCK_SEQPACKET, IPPROTO_SCTP, &sock);
5042 	if (err < 0)
5043 		return err;
5044 
5045 	sctp_copy_sock(sock->sk, sk, asoc);
5046 
5047 	/* Make peeled-off sockets more like 1-1 accepted sockets.
5048 	 * Set the daddr and initialize id to something more random
5049 	 */
5050 	sp->pf->to_sk_daddr(&asoc->peer.primary_addr, sk);
5051 
5052 	/* Populate the fields of the newsk from the oldsk and migrate the
5053 	 * asoc to the newsk.
5054 	 */
5055 	sctp_sock_migrate(sk, sock->sk, asoc, SCTP_SOCKET_UDP_HIGH_BANDWIDTH);
5056 
5057 	*sockp = sock;
5058 
5059 	return err;
5060 }
5061 EXPORT_SYMBOL(sctp_do_peeloff);
5062 
5063 static int sctp_getsockopt_peeloff_common(struct sock *sk, sctp_peeloff_arg_t *peeloff,
5064 					  struct file **newfile, unsigned flags)
5065 {
5066 	struct socket *newsock;
5067 	int retval;
5068 
5069 	retval = sctp_do_peeloff(sk, peeloff->associd, &newsock);
5070 	if (retval < 0)
5071 		goto out;
5072 
5073 	/* Map the socket to an unused fd that can be returned to the user.  */
5074 	retval = get_unused_fd_flags(flags & SOCK_CLOEXEC);
5075 	if (retval < 0) {
5076 		sock_release(newsock);
5077 		goto out;
5078 	}
5079 
5080 	*newfile = sock_alloc_file(newsock, 0, NULL);
5081 	if (IS_ERR(*newfile)) {
5082 		put_unused_fd(retval);
5083 		retval = PTR_ERR(*newfile);
5084 		*newfile = NULL;
5085 		return retval;
5086 	}
5087 
5088 	pr_debug("%s: sk:%p, newsk:%p, sd:%d\n", __func__, sk, newsock->sk,
5089 		 retval);
5090 
5091 	peeloff->sd = retval;
5092 
5093 	if (flags & SOCK_NONBLOCK)
5094 		(*newfile)->f_flags |= O_NONBLOCK;
5095 out:
5096 	return retval;
5097 }
5098 
5099 static int sctp_getsockopt_peeloff(struct sock *sk, int len, char __user *optval, int __user *optlen)
5100 {
5101 	sctp_peeloff_arg_t peeloff;
5102 	struct file *newfile = NULL;
5103 	int retval = 0;
5104 
5105 	if (len < sizeof(sctp_peeloff_arg_t))
5106 		return -EINVAL;
5107 	len = sizeof(sctp_peeloff_arg_t);
5108 	if (copy_from_user(&peeloff, optval, len))
5109 		return -EFAULT;
5110 
5111 	retval = sctp_getsockopt_peeloff_common(sk, &peeloff, &newfile, 0);
5112 	if (retval < 0)
5113 		goto out;
5114 
5115 	/* Return the fd mapped to the new socket.  */
5116 	if (put_user(len, optlen)) {
5117 		fput(newfile);
5118 		put_unused_fd(retval);
5119 		return -EFAULT;
5120 	}
5121 
5122 	if (copy_to_user(optval, &peeloff, len)) {
5123 		fput(newfile);
5124 		put_unused_fd(retval);
5125 		return -EFAULT;
5126 	}
5127 	fd_install(retval, newfile);
5128 out:
5129 	return retval;
5130 }
5131 
5132 static int sctp_getsockopt_peeloff_flags(struct sock *sk, int len,
5133 					 char __user *optval, int __user *optlen)
5134 {
5135 	sctp_peeloff_flags_arg_t peeloff;
5136 	struct file *newfile = NULL;
5137 	int retval = 0;
5138 
5139 	if (len < sizeof(sctp_peeloff_flags_arg_t))
5140 		return -EINVAL;
5141 	len = sizeof(sctp_peeloff_flags_arg_t);
5142 	if (copy_from_user(&peeloff, optval, len))
5143 		return -EFAULT;
5144 
5145 	retval = sctp_getsockopt_peeloff_common(sk, &peeloff.p_arg,
5146 						&newfile, peeloff.flags);
5147 	if (retval < 0)
5148 		goto out;
5149 
5150 	/* Return the fd mapped to the new socket.  */
5151 	if (put_user(len, optlen)) {
5152 		fput(newfile);
5153 		put_unused_fd(retval);
5154 		return -EFAULT;
5155 	}
5156 
5157 	if (copy_to_user(optval, &peeloff, len)) {
5158 		fput(newfile);
5159 		put_unused_fd(retval);
5160 		return -EFAULT;
5161 	}
5162 	fd_install(retval, newfile);
5163 out:
5164 	return retval;
5165 }
5166 
5167 /* 7.1.13 Peer Address Parameters (SCTP_PEER_ADDR_PARAMS)
5168  *
5169  * Applications can enable or disable heartbeats for any peer address of
5170  * an association, modify an address's heartbeat interval, force a
5171  * heartbeat to be sent immediately, and adjust the address's maximum
5172  * number of retransmissions sent before an address is considered
5173  * unreachable.  The following structure is used to access and modify an
5174  * address's parameters:
5175  *
5176  *  struct sctp_paddrparams {
5177  *     sctp_assoc_t            spp_assoc_id;
5178  *     struct sockaddr_storage spp_address;
5179  *     uint32_t                spp_hbinterval;
5180  *     uint16_t                spp_pathmaxrxt;
5181  *     uint32_t                spp_pathmtu;
5182  *     uint32_t                spp_sackdelay;
5183  *     uint32_t                spp_flags;
5184  * };
5185  *
5186  *   spp_assoc_id    - (one-to-many style socket) This is filled in the
5187  *                     application, and identifies the association for
5188  *                     this query.
5189  *   spp_address     - This specifies which address is of interest.
5190  *   spp_hbinterval  - This contains the value of the heartbeat interval,
5191  *                     in milliseconds.  If a  value of zero
5192  *                     is present in this field then no changes are to
5193  *                     be made to this parameter.
5194  *   spp_pathmaxrxt  - This contains the maximum number of
5195  *                     retransmissions before this address shall be
5196  *                     considered unreachable. If a  value of zero
5197  *                     is present in this field then no changes are to
5198  *                     be made to this parameter.
5199  *   spp_pathmtu     - When Path MTU discovery is disabled the value
5200  *                     specified here will be the "fixed" path mtu.
5201  *                     Note that if the spp_address field is empty
5202  *                     then all associations on this address will
5203  *                     have this fixed path mtu set upon them.
5204  *
5205  *   spp_sackdelay   - When delayed sack is enabled, this value specifies
5206  *                     the number of milliseconds that sacks will be delayed
5207  *                     for. This value will apply to all addresses of an
5208  *                     association if the spp_address field is empty. Note
5209  *                     also, that if delayed sack is enabled and this
5210  *                     value is set to 0, no change is made to the last
5211  *                     recorded delayed sack timer value.
5212  *
5213  *   spp_flags       - These flags are used to control various features
5214  *                     on an association. The flag field may contain
5215  *                     zero or more of the following options.
5216  *
5217  *                     SPP_HB_ENABLE  - Enable heartbeats on the
5218  *                     specified address. Note that if the address
5219  *                     field is empty all addresses for the association
5220  *                     have heartbeats enabled upon them.
5221  *
5222  *                     SPP_HB_DISABLE - Disable heartbeats on the
5223  *                     speicifed address. Note that if the address
5224  *                     field is empty all addresses for the association
5225  *                     will have their heartbeats disabled. Note also
5226  *                     that SPP_HB_ENABLE and SPP_HB_DISABLE are
5227  *                     mutually exclusive, only one of these two should
5228  *                     be specified. Enabling both fields will have
5229  *                     undetermined results.
5230  *
5231  *                     SPP_HB_DEMAND - Request a user initiated heartbeat
5232  *                     to be made immediately.
5233  *
5234  *                     SPP_PMTUD_ENABLE - This field will enable PMTU
5235  *                     discovery upon the specified address. Note that
5236  *                     if the address feild is empty then all addresses
5237  *                     on the association are effected.
5238  *
5239  *                     SPP_PMTUD_DISABLE - This field will disable PMTU
5240  *                     discovery upon the specified address. Note that
5241  *                     if the address feild is empty then all addresses
5242  *                     on the association are effected. Not also that
5243  *                     SPP_PMTUD_ENABLE and SPP_PMTUD_DISABLE are mutually
5244  *                     exclusive. Enabling both will have undetermined
5245  *                     results.
5246  *
5247  *                     SPP_SACKDELAY_ENABLE - Setting this flag turns
5248  *                     on delayed sack. The time specified in spp_sackdelay
5249  *                     is used to specify the sack delay for this address. Note
5250  *                     that if spp_address is empty then all addresses will
5251  *                     enable delayed sack and take on the sack delay
5252  *                     value specified in spp_sackdelay.
5253  *                     SPP_SACKDELAY_DISABLE - Setting this flag turns
5254  *                     off delayed sack. If the spp_address field is blank then
5255  *                     delayed sack is disabled for the entire association. Note
5256  *                     also that this field is mutually exclusive to
5257  *                     SPP_SACKDELAY_ENABLE, setting both will have undefined
5258  *                     results.
5259  */
5260 static int sctp_getsockopt_peer_addr_params(struct sock *sk, int len,
5261 					    char __user *optval, int __user *optlen)
5262 {
5263 	struct sctp_paddrparams  params;
5264 	struct sctp_transport   *trans = NULL;
5265 	struct sctp_association *asoc = NULL;
5266 	struct sctp_sock        *sp = sctp_sk(sk);
5267 
5268 	if (len < sizeof(struct sctp_paddrparams))
5269 		return -EINVAL;
5270 	len = sizeof(struct sctp_paddrparams);
5271 	if (copy_from_user(&params, optval, len))
5272 		return -EFAULT;
5273 
5274 	/* If an address other than INADDR_ANY is specified, and
5275 	 * no transport is found, then the request is invalid.
5276 	 */
5277 	if (!sctp_is_any(sk, (union sctp_addr *)&params.spp_address)) {
5278 		trans = sctp_addr_id2transport(sk, &params.spp_address,
5279 					       params.spp_assoc_id);
5280 		if (!trans) {
5281 			pr_debug("%s: failed no transport\n", __func__);
5282 			return -EINVAL;
5283 		}
5284 	}
5285 
5286 	/* Get association, if assoc_id != 0 and the socket is a one
5287 	 * to many style socket, and an association was not found, then
5288 	 * the id was invalid.
5289 	 */
5290 	asoc = sctp_id2assoc(sk, params.spp_assoc_id);
5291 	if (!asoc && params.spp_assoc_id && sctp_style(sk, UDP)) {
5292 		pr_debug("%s: failed no association\n", __func__);
5293 		return -EINVAL;
5294 	}
5295 
5296 	if (trans) {
5297 		/* Fetch transport values. */
5298 		params.spp_hbinterval = jiffies_to_msecs(trans->hbinterval);
5299 		params.spp_pathmtu    = trans->pathmtu;
5300 		params.spp_pathmaxrxt = trans->pathmaxrxt;
5301 		params.spp_sackdelay  = jiffies_to_msecs(trans->sackdelay);
5302 
5303 		/*draft-11 doesn't say what to return in spp_flags*/
5304 		params.spp_flags      = trans->param_flags;
5305 	} else if (asoc) {
5306 		/* Fetch association values. */
5307 		params.spp_hbinterval = jiffies_to_msecs(asoc->hbinterval);
5308 		params.spp_pathmtu    = asoc->pathmtu;
5309 		params.spp_pathmaxrxt = asoc->pathmaxrxt;
5310 		params.spp_sackdelay  = jiffies_to_msecs(asoc->sackdelay);
5311 
5312 		/*draft-11 doesn't say what to return in spp_flags*/
5313 		params.spp_flags      = asoc->param_flags;
5314 	} else {
5315 		/* Fetch socket values. */
5316 		params.spp_hbinterval = sp->hbinterval;
5317 		params.spp_pathmtu    = sp->pathmtu;
5318 		params.spp_sackdelay  = sp->sackdelay;
5319 		params.spp_pathmaxrxt = sp->pathmaxrxt;
5320 
5321 		/*draft-11 doesn't say what to return in spp_flags*/
5322 		params.spp_flags      = sp->param_flags;
5323 	}
5324 
5325 	if (copy_to_user(optval, &params, len))
5326 		return -EFAULT;
5327 
5328 	if (put_user(len, optlen))
5329 		return -EFAULT;
5330 
5331 	return 0;
5332 }
5333 
5334 /*
5335  * 7.1.23.  Get or set delayed ack timer (SCTP_DELAYED_SACK)
5336  *
5337  * This option will effect the way delayed acks are performed.  This
5338  * option allows you to get or set the delayed ack time, in
5339  * milliseconds.  It also allows changing the delayed ack frequency.
5340  * Changing the frequency to 1 disables the delayed sack algorithm.  If
5341  * the assoc_id is 0, then this sets or gets the endpoints default
5342  * values.  If the assoc_id field is non-zero, then the set or get
5343  * effects the specified association for the one to many model (the
5344  * assoc_id field is ignored by the one to one model).  Note that if
5345  * sack_delay or sack_freq are 0 when setting this option, then the
5346  * current values will remain unchanged.
5347  *
5348  * struct sctp_sack_info {
5349  *     sctp_assoc_t            sack_assoc_id;
5350  *     uint32_t                sack_delay;
5351  *     uint32_t                sack_freq;
5352  * };
5353  *
5354  * sack_assoc_id -  This parameter, indicates which association the user
5355  *    is performing an action upon.  Note that if this field's value is
5356  *    zero then the endpoints default value is changed (effecting future
5357  *    associations only).
5358  *
5359  * sack_delay -  This parameter contains the number of milliseconds that
5360  *    the user is requesting the delayed ACK timer be set to.  Note that
5361  *    this value is defined in the standard to be between 200 and 500
5362  *    milliseconds.
5363  *
5364  * sack_freq -  This parameter contains the number of packets that must
5365  *    be received before a sack is sent without waiting for the delay
5366  *    timer to expire.  The default value for this is 2, setting this
5367  *    value to 1 will disable the delayed sack algorithm.
5368  */
5369 static int sctp_getsockopt_delayed_ack(struct sock *sk, int len,
5370 					    char __user *optval,
5371 					    int __user *optlen)
5372 {
5373 	struct sctp_sack_info    params;
5374 	struct sctp_association *asoc = NULL;
5375 	struct sctp_sock        *sp = sctp_sk(sk);
5376 
5377 	if (len >= sizeof(struct sctp_sack_info)) {
5378 		len = sizeof(struct sctp_sack_info);
5379 
5380 		if (copy_from_user(&params, optval, len))
5381 			return -EFAULT;
5382 	} else if (len == sizeof(struct sctp_assoc_value)) {
5383 		pr_warn_ratelimited(DEPRECATED
5384 				    "%s (pid %d) "
5385 				    "Use of struct sctp_assoc_value in delayed_ack socket option.\n"
5386 				    "Use struct sctp_sack_info instead\n",
5387 				    current->comm, task_pid_nr(current));
5388 		if (copy_from_user(&params, optval, len))
5389 			return -EFAULT;
5390 	} else
5391 		return -EINVAL;
5392 
5393 	/* Get association, if sack_assoc_id != 0 and the socket is a one
5394 	 * to many style socket, and an association was not found, then
5395 	 * the id was invalid.
5396 	 */
5397 	asoc = sctp_id2assoc(sk, params.sack_assoc_id);
5398 	if (!asoc && params.sack_assoc_id && sctp_style(sk, UDP))
5399 		return -EINVAL;
5400 
5401 	if (asoc) {
5402 		/* Fetch association values. */
5403 		if (asoc->param_flags & SPP_SACKDELAY_ENABLE) {
5404 			params.sack_delay = jiffies_to_msecs(
5405 				asoc->sackdelay);
5406 			params.sack_freq = asoc->sackfreq;
5407 
5408 		} else {
5409 			params.sack_delay = 0;
5410 			params.sack_freq = 1;
5411 		}
5412 	} else {
5413 		/* Fetch socket values. */
5414 		if (sp->param_flags & SPP_SACKDELAY_ENABLE) {
5415 			params.sack_delay  = sp->sackdelay;
5416 			params.sack_freq = sp->sackfreq;
5417 		} else {
5418 			params.sack_delay  = 0;
5419 			params.sack_freq = 1;
5420 		}
5421 	}
5422 
5423 	if (copy_to_user(optval, &params, len))
5424 		return -EFAULT;
5425 
5426 	if (put_user(len, optlen))
5427 		return -EFAULT;
5428 
5429 	return 0;
5430 }
5431 
5432 /* 7.1.3 Initialization Parameters (SCTP_INITMSG)
5433  *
5434  * Applications can specify protocol parameters for the default association
5435  * initialization.  The option name argument to setsockopt() and getsockopt()
5436  * is SCTP_INITMSG.
5437  *
5438  * Setting initialization parameters is effective only on an unconnected
5439  * socket (for UDP-style sockets only future associations are effected
5440  * by the change).  With TCP-style sockets, this option is inherited by
5441  * sockets derived from a listener socket.
5442  */
5443 static int sctp_getsockopt_initmsg(struct sock *sk, int len, char __user *optval, int __user *optlen)
5444 {
5445 	if (len < sizeof(struct sctp_initmsg))
5446 		return -EINVAL;
5447 	len = sizeof(struct sctp_initmsg);
5448 	if (put_user(len, optlen))
5449 		return -EFAULT;
5450 	if (copy_to_user(optval, &sctp_sk(sk)->initmsg, len))
5451 		return -EFAULT;
5452 	return 0;
5453 }
5454 
5455 
5456 static int sctp_getsockopt_peer_addrs(struct sock *sk, int len,
5457 				      char __user *optval, int __user *optlen)
5458 {
5459 	struct sctp_association *asoc;
5460 	int cnt = 0;
5461 	struct sctp_getaddrs getaddrs;
5462 	struct sctp_transport *from;
5463 	void __user *to;
5464 	union sctp_addr temp;
5465 	struct sctp_sock *sp = sctp_sk(sk);
5466 	int addrlen;
5467 	size_t space_left;
5468 	int bytes_copied;
5469 
5470 	if (len < sizeof(struct sctp_getaddrs))
5471 		return -EINVAL;
5472 
5473 	if (copy_from_user(&getaddrs, optval, sizeof(struct sctp_getaddrs)))
5474 		return -EFAULT;
5475 
5476 	/* For UDP-style sockets, id specifies the association to query.  */
5477 	asoc = sctp_id2assoc(sk, getaddrs.assoc_id);
5478 	if (!asoc)
5479 		return -EINVAL;
5480 
5481 	to = optval + offsetof(struct sctp_getaddrs, addrs);
5482 	space_left = len - offsetof(struct sctp_getaddrs, addrs);
5483 
5484 	list_for_each_entry(from, &asoc->peer.transport_addr_list,
5485 				transports) {
5486 		memcpy(&temp, &from->ipaddr, sizeof(temp));
5487 		addrlen = sctp_get_pf_specific(sk->sk_family)
5488 			      ->addr_to_user(sp, &temp);
5489 		if (space_left < addrlen)
5490 			return -ENOMEM;
5491 		if (copy_to_user(to, &temp, addrlen))
5492 			return -EFAULT;
5493 		to += addrlen;
5494 		cnt++;
5495 		space_left -= addrlen;
5496 	}
5497 
5498 	if (put_user(cnt, &((struct sctp_getaddrs __user *)optval)->addr_num))
5499 		return -EFAULT;
5500 	bytes_copied = ((char __user *)to) - optval;
5501 	if (put_user(bytes_copied, optlen))
5502 		return -EFAULT;
5503 
5504 	return 0;
5505 }
5506 
5507 static int sctp_copy_laddrs(struct sock *sk, __u16 port, void *to,
5508 			    size_t space_left, int *bytes_copied)
5509 {
5510 	struct sctp_sockaddr_entry *addr;
5511 	union sctp_addr temp;
5512 	int cnt = 0;
5513 	int addrlen;
5514 	struct net *net = sock_net(sk);
5515 
5516 	rcu_read_lock();
5517 	list_for_each_entry_rcu(addr, &net->sctp.local_addr_list, list) {
5518 		if (!addr->valid)
5519 			continue;
5520 
5521 		if ((PF_INET == sk->sk_family) &&
5522 		    (AF_INET6 == addr->a.sa.sa_family))
5523 			continue;
5524 		if ((PF_INET6 == sk->sk_family) &&
5525 		    inet_v6_ipv6only(sk) &&
5526 		    (AF_INET == addr->a.sa.sa_family))
5527 			continue;
5528 		memcpy(&temp, &addr->a, sizeof(temp));
5529 		if (!temp.v4.sin_port)
5530 			temp.v4.sin_port = htons(port);
5531 
5532 		addrlen = sctp_get_pf_specific(sk->sk_family)
5533 			      ->addr_to_user(sctp_sk(sk), &temp);
5534 
5535 		if (space_left < addrlen) {
5536 			cnt =  -ENOMEM;
5537 			break;
5538 		}
5539 		memcpy(to, &temp, addrlen);
5540 
5541 		to += addrlen;
5542 		cnt++;
5543 		space_left -= addrlen;
5544 		*bytes_copied += addrlen;
5545 	}
5546 	rcu_read_unlock();
5547 
5548 	return cnt;
5549 }
5550 
5551 
5552 static int sctp_getsockopt_local_addrs(struct sock *sk, int len,
5553 				       char __user *optval, int __user *optlen)
5554 {
5555 	struct sctp_bind_addr *bp;
5556 	struct sctp_association *asoc;
5557 	int cnt = 0;
5558 	struct sctp_getaddrs getaddrs;
5559 	struct sctp_sockaddr_entry *addr;
5560 	void __user *to;
5561 	union sctp_addr temp;
5562 	struct sctp_sock *sp = sctp_sk(sk);
5563 	int addrlen;
5564 	int err = 0;
5565 	size_t space_left;
5566 	int bytes_copied = 0;
5567 	void *addrs;
5568 	void *buf;
5569 
5570 	if (len < sizeof(struct sctp_getaddrs))
5571 		return -EINVAL;
5572 
5573 	if (copy_from_user(&getaddrs, optval, sizeof(struct sctp_getaddrs)))
5574 		return -EFAULT;
5575 
5576 	/*
5577 	 *  For UDP-style sockets, id specifies the association to query.
5578 	 *  If the id field is set to the value '0' then the locally bound
5579 	 *  addresses are returned without regard to any particular
5580 	 *  association.
5581 	 */
5582 	if (0 == getaddrs.assoc_id) {
5583 		bp = &sctp_sk(sk)->ep->base.bind_addr;
5584 	} else {
5585 		asoc = sctp_id2assoc(sk, getaddrs.assoc_id);
5586 		if (!asoc)
5587 			return -EINVAL;
5588 		bp = &asoc->base.bind_addr;
5589 	}
5590 
5591 	to = optval + offsetof(struct sctp_getaddrs, addrs);
5592 	space_left = len - offsetof(struct sctp_getaddrs, addrs);
5593 
5594 	addrs = kmalloc(space_left, GFP_USER | __GFP_NOWARN);
5595 	if (!addrs)
5596 		return -ENOMEM;
5597 
5598 	/* If the endpoint is bound to 0.0.0.0 or ::0, get the valid
5599 	 * addresses from the global local address list.
5600 	 */
5601 	if (sctp_list_single_entry(&bp->address_list)) {
5602 		addr = list_entry(bp->address_list.next,
5603 				  struct sctp_sockaddr_entry, list);
5604 		if (sctp_is_any(sk, &addr->a)) {
5605 			cnt = sctp_copy_laddrs(sk, bp->port, addrs,
5606 						space_left, &bytes_copied);
5607 			if (cnt < 0) {
5608 				err = cnt;
5609 				goto out;
5610 			}
5611 			goto copy_getaddrs;
5612 		}
5613 	}
5614 
5615 	buf = addrs;
5616 	/* Protection on the bound address list is not needed since
5617 	 * in the socket option context we hold a socket lock and
5618 	 * thus the bound address list can't change.
5619 	 */
5620 	list_for_each_entry(addr, &bp->address_list, list) {
5621 		memcpy(&temp, &addr->a, sizeof(temp));
5622 		addrlen = sctp_get_pf_specific(sk->sk_family)
5623 			      ->addr_to_user(sp, &temp);
5624 		if (space_left < addrlen) {
5625 			err =  -ENOMEM; /*fixme: right error?*/
5626 			goto out;
5627 		}
5628 		memcpy(buf, &temp, addrlen);
5629 		buf += addrlen;
5630 		bytes_copied += addrlen;
5631 		cnt++;
5632 		space_left -= addrlen;
5633 	}
5634 
5635 copy_getaddrs:
5636 	if (copy_to_user(to, addrs, bytes_copied)) {
5637 		err = -EFAULT;
5638 		goto out;
5639 	}
5640 	if (put_user(cnt, &((struct sctp_getaddrs __user *)optval)->addr_num)) {
5641 		err = -EFAULT;
5642 		goto out;
5643 	}
5644 	if (put_user(bytes_copied, optlen))
5645 		err = -EFAULT;
5646 out:
5647 	kfree(addrs);
5648 	return err;
5649 }
5650 
5651 /* 7.1.10 Set Primary Address (SCTP_PRIMARY_ADDR)
5652  *
5653  * Requests that the local SCTP stack use the enclosed peer address as
5654  * the association primary.  The enclosed address must be one of the
5655  * association peer's addresses.
5656  */
5657 static int sctp_getsockopt_primary_addr(struct sock *sk, int len,
5658 					char __user *optval, int __user *optlen)
5659 {
5660 	struct sctp_prim prim;
5661 	struct sctp_association *asoc;
5662 	struct sctp_sock *sp = sctp_sk(sk);
5663 
5664 	if (len < sizeof(struct sctp_prim))
5665 		return -EINVAL;
5666 
5667 	len = sizeof(struct sctp_prim);
5668 
5669 	if (copy_from_user(&prim, optval, len))
5670 		return -EFAULT;
5671 
5672 	asoc = sctp_id2assoc(sk, prim.ssp_assoc_id);
5673 	if (!asoc)
5674 		return -EINVAL;
5675 
5676 	if (!asoc->peer.primary_path)
5677 		return -ENOTCONN;
5678 
5679 	memcpy(&prim.ssp_addr, &asoc->peer.primary_path->ipaddr,
5680 		asoc->peer.primary_path->af_specific->sockaddr_len);
5681 
5682 	sctp_get_pf_specific(sk->sk_family)->addr_to_user(sp,
5683 			(union sctp_addr *)&prim.ssp_addr);
5684 
5685 	if (put_user(len, optlen))
5686 		return -EFAULT;
5687 	if (copy_to_user(optval, &prim, len))
5688 		return -EFAULT;
5689 
5690 	return 0;
5691 }
5692 
5693 /*
5694  * 7.1.11  Set Adaptation Layer Indicator (SCTP_ADAPTATION_LAYER)
5695  *
5696  * Requests that the local endpoint set the specified Adaptation Layer
5697  * Indication parameter for all future INIT and INIT-ACK exchanges.
5698  */
5699 static int sctp_getsockopt_adaptation_layer(struct sock *sk, int len,
5700 				  char __user *optval, int __user *optlen)
5701 {
5702 	struct sctp_setadaptation adaptation;
5703 
5704 	if (len < sizeof(struct sctp_setadaptation))
5705 		return -EINVAL;
5706 
5707 	len = sizeof(struct sctp_setadaptation);
5708 
5709 	adaptation.ssb_adaptation_ind = sctp_sk(sk)->adaptation_ind;
5710 
5711 	if (put_user(len, optlen))
5712 		return -EFAULT;
5713 	if (copy_to_user(optval, &adaptation, len))
5714 		return -EFAULT;
5715 
5716 	return 0;
5717 }
5718 
5719 /*
5720  *
5721  * 7.1.14 Set default send parameters (SCTP_DEFAULT_SEND_PARAM)
5722  *
5723  *   Applications that wish to use the sendto() system call may wish to
5724  *   specify a default set of parameters that would normally be supplied
5725  *   through the inclusion of ancillary data.  This socket option allows
5726  *   such an application to set the default sctp_sndrcvinfo structure.
5727 
5728 
5729  *   The application that wishes to use this socket option simply passes
5730  *   in to this call the sctp_sndrcvinfo structure defined in Section
5731  *   5.2.2) The input parameters accepted by this call include
5732  *   sinfo_stream, sinfo_flags, sinfo_ppid, sinfo_context,
5733  *   sinfo_timetolive.  The user must provide the sinfo_assoc_id field in
5734  *   to this call if the caller is using the UDP model.
5735  *
5736  *   For getsockopt, it get the default sctp_sndrcvinfo structure.
5737  */
5738 static int sctp_getsockopt_default_send_param(struct sock *sk,
5739 					int len, char __user *optval,
5740 					int __user *optlen)
5741 {
5742 	struct sctp_sock *sp = sctp_sk(sk);
5743 	struct sctp_association *asoc;
5744 	struct sctp_sndrcvinfo info;
5745 
5746 	if (len < sizeof(info))
5747 		return -EINVAL;
5748 
5749 	len = sizeof(info);
5750 
5751 	if (copy_from_user(&info, optval, len))
5752 		return -EFAULT;
5753 
5754 	asoc = sctp_id2assoc(sk, info.sinfo_assoc_id);
5755 	if (!asoc && info.sinfo_assoc_id && sctp_style(sk, UDP))
5756 		return -EINVAL;
5757 	if (asoc) {
5758 		info.sinfo_stream = asoc->default_stream;
5759 		info.sinfo_flags = asoc->default_flags;
5760 		info.sinfo_ppid = asoc->default_ppid;
5761 		info.sinfo_context = asoc->default_context;
5762 		info.sinfo_timetolive = asoc->default_timetolive;
5763 	} else {
5764 		info.sinfo_stream = sp->default_stream;
5765 		info.sinfo_flags = sp->default_flags;
5766 		info.sinfo_ppid = sp->default_ppid;
5767 		info.sinfo_context = sp->default_context;
5768 		info.sinfo_timetolive = sp->default_timetolive;
5769 	}
5770 
5771 	if (put_user(len, optlen))
5772 		return -EFAULT;
5773 	if (copy_to_user(optval, &info, len))
5774 		return -EFAULT;
5775 
5776 	return 0;
5777 }
5778 
5779 /* RFC6458, Section 8.1.31. Set/get Default Send Parameters
5780  * (SCTP_DEFAULT_SNDINFO)
5781  */
5782 static int sctp_getsockopt_default_sndinfo(struct sock *sk, int len,
5783 					   char __user *optval,
5784 					   int __user *optlen)
5785 {
5786 	struct sctp_sock *sp = sctp_sk(sk);
5787 	struct sctp_association *asoc;
5788 	struct sctp_sndinfo info;
5789 
5790 	if (len < sizeof(info))
5791 		return -EINVAL;
5792 
5793 	len = sizeof(info);
5794 
5795 	if (copy_from_user(&info, optval, len))
5796 		return -EFAULT;
5797 
5798 	asoc = sctp_id2assoc(sk, info.snd_assoc_id);
5799 	if (!asoc && info.snd_assoc_id && sctp_style(sk, UDP))
5800 		return -EINVAL;
5801 	if (asoc) {
5802 		info.snd_sid = asoc->default_stream;
5803 		info.snd_flags = asoc->default_flags;
5804 		info.snd_ppid = asoc->default_ppid;
5805 		info.snd_context = asoc->default_context;
5806 	} else {
5807 		info.snd_sid = sp->default_stream;
5808 		info.snd_flags = sp->default_flags;
5809 		info.snd_ppid = sp->default_ppid;
5810 		info.snd_context = sp->default_context;
5811 	}
5812 
5813 	if (put_user(len, optlen))
5814 		return -EFAULT;
5815 	if (copy_to_user(optval, &info, len))
5816 		return -EFAULT;
5817 
5818 	return 0;
5819 }
5820 
5821 /*
5822  *
5823  * 7.1.5 SCTP_NODELAY
5824  *
5825  * Turn on/off any Nagle-like algorithm.  This means that packets are
5826  * generally sent as soon as possible and no unnecessary delays are
5827  * introduced, at the cost of more packets in the network.  Expects an
5828  * integer boolean flag.
5829  */
5830 
5831 static int sctp_getsockopt_nodelay(struct sock *sk, int len,
5832 				   char __user *optval, int __user *optlen)
5833 {
5834 	int val;
5835 
5836 	if (len < sizeof(int))
5837 		return -EINVAL;
5838 
5839 	len = sizeof(int);
5840 	val = (sctp_sk(sk)->nodelay == 1);
5841 	if (put_user(len, optlen))
5842 		return -EFAULT;
5843 	if (copy_to_user(optval, &val, len))
5844 		return -EFAULT;
5845 	return 0;
5846 }
5847 
5848 /*
5849  *
5850  * 7.1.1 SCTP_RTOINFO
5851  *
5852  * The protocol parameters used to initialize and bound retransmission
5853  * timeout (RTO) are tunable. sctp_rtoinfo structure is used to access
5854  * and modify these parameters.
5855  * All parameters are time values, in milliseconds.  A value of 0, when
5856  * modifying the parameters, indicates that the current value should not
5857  * be changed.
5858  *
5859  */
5860 static int sctp_getsockopt_rtoinfo(struct sock *sk, int len,
5861 				char __user *optval,
5862 				int __user *optlen) {
5863 	struct sctp_rtoinfo rtoinfo;
5864 	struct sctp_association *asoc;
5865 
5866 	if (len < sizeof (struct sctp_rtoinfo))
5867 		return -EINVAL;
5868 
5869 	len = sizeof(struct sctp_rtoinfo);
5870 
5871 	if (copy_from_user(&rtoinfo, optval, len))
5872 		return -EFAULT;
5873 
5874 	asoc = sctp_id2assoc(sk, rtoinfo.srto_assoc_id);
5875 
5876 	if (!asoc && rtoinfo.srto_assoc_id && sctp_style(sk, UDP))
5877 		return -EINVAL;
5878 
5879 	/* Values corresponding to the specific association. */
5880 	if (asoc) {
5881 		rtoinfo.srto_initial = jiffies_to_msecs(asoc->rto_initial);
5882 		rtoinfo.srto_max = jiffies_to_msecs(asoc->rto_max);
5883 		rtoinfo.srto_min = jiffies_to_msecs(asoc->rto_min);
5884 	} else {
5885 		/* Values corresponding to the endpoint. */
5886 		struct sctp_sock *sp = sctp_sk(sk);
5887 
5888 		rtoinfo.srto_initial = sp->rtoinfo.srto_initial;
5889 		rtoinfo.srto_max = sp->rtoinfo.srto_max;
5890 		rtoinfo.srto_min = sp->rtoinfo.srto_min;
5891 	}
5892 
5893 	if (put_user(len, optlen))
5894 		return -EFAULT;
5895 
5896 	if (copy_to_user(optval, &rtoinfo, len))
5897 		return -EFAULT;
5898 
5899 	return 0;
5900 }
5901 
5902 /*
5903  *
5904  * 7.1.2 SCTP_ASSOCINFO
5905  *
5906  * This option is used to tune the maximum retransmission attempts
5907  * of the association.
5908  * Returns an error if the new association retransmission value is
5909  * greater than the sum of the retransmission value  of the peer.
5910  * See [SCTP] for more information.
5911  *
5912  */
5913 static int sctp_getsockopt_associnfo(struct sock *sk, int len,
5914 				     char __user *optval,
5915 				     int __user *optlen)
5916 {
5917 
5918 	struct sctp_assocparams assocparams;
5919 	struct sctp_association *asoc;
5920 	struct list_head *pos;
5921 	int cnt = 0;
5922 
5923 	if (len < sizeof (struct sctp_assocparams))
5924 		return -EINVAL;
5925 
5926 	len = sizeof(struct sctp_assocparams);
5927 
5928 	if (copy_from_user(&assocparams, optval, len))
5929 		return -EFAULT;
5930 
5931 	asoc = sctp_id2assoc(sk, assocparams.sasoc_assoc_id);
5932 
5933 	if (!asoc && assocparams.sasoc_assoc_id && sctp_style(sk, UDP))
5934 		return -EINVAL;
5935 
5936 	/* Values correspoinding to the specific association */
5937 	if (asoc) {
5938 		assocparams.sasoc_asocmaxrxt = asoc->max_retrans;
5939 		assocparams.sasoc_peer_rwnd = asoc->peer.rwnd;
5940 		assocparams.sasoc_local_rwnd = asoc->a_rwnd;
5941 		assocparams.sasoc_cookie_life = ktime_to_ms(asoc->cookie_life);
5942 
5943 		list_for_each(pos, &asoc->peer.transport_addr_list) {
5944 			cnt++;
5945 		}
5946 
5947 		assocparams.sasoc_number_peer_destinations = cnt;
5948 	} else {
5949 		/* Values corresponding to the endpoint */
5950 		struct sctp_sock *sp = sctp_sk(sk);
5951 
5952 		assocparams.sasoc_asocmaxrxt = sp->assocparams.sasoc_asocmaxrxt;
5953 		assocparams.sasoc_peer_rwnd = sp->assocparams.sasoc_peer_rwnd;
5954 		assocparams.sasoc_local_rwnd = sp->assocparams.sasoc_local_rwnd;
5955 		assocparams.sasoc_cookie_life =
5956 					sp->assocparams.sasoc_cookie_life;
5957 		assocparams.sasoc_number_peer_destinations =
5958 					sp->assocparams.
5959 					sasoc_number_peer_destinations;
5960 	}
5961 
5962 	if (put_user(len, optlen))
5963 		return -EFAULT;
5964 
5965 	if (copy_to_user(optval, &assocparams, len))
5966 		return -EFAULT;
5967 
5968 	return 0;
5969 }
5970 
5971 /*
5972  * 7.1.16 Set/clear IPv4 mapped addresses (SCTP_I_WANT_MAPPED_V4_ADDR)
5973  *
5974  * This socket option is a boolean flag which turns on or off mapped V4
5975  * addresses.  If this option is turned on and the socket is type
5976  * PF_INET6, then IPv4 addresses will be mapped to V6 representation.
5977  * If this option is turned off, then no mapping will be done of V4
5978  * addresses and a user will receive both PF_INET6 and PF_INET type
5979  * addresses on the socket.
5980  */
5981 static int sctp_getsockopt_mappedv4(struct sock *sk, int len,
5982 				    char __user *optval, int __user *optlen)
5983 {
5984 	int val;
5985 	struct sctp_sock *sp = sctp_sk(sk);
5986 
5987 	if (len < sizeof(int))
5988 		return -EINVAL;
5989 
5990 	len = sizeof(int);
5991 	val = sp->v4mapped;
5992 	if (put_user(len, optlen))
5993 		return -EFAULT;
5994 	if (copy_to_user(optval, &val, len))
5995 		return -EFAULT;
5996 
5997 	return 0;
5998 }
5999 
6000 /*
6001  * 7.1.29.  Set or Get the default context (SCTP_CONTEXT)
6002  * (chapter and verse is quoted at sctp_setsockopt_context())
6003  */
6004 static int sctp_getsockopt_context(struct sock *sk, int len,
6005 				   char __user *optval, int __user *optlen)
6006 {
6007 	struct sctp_assoc_value params;
6008 	struct sctp_sock *sp;
6009 	struct sctp_association *asoc;
6010 
6011 	if (len < sizeof(struct sctp_assoc_value))
6012 		return -EINVAL;
6013 
6014 	len = sizeof(struct sctp_assoc_value);
6015 
6016 	if (copy_from_user(&params, optval, len))
6017 		return -EFAULT;
6018 
6019 	sp = sctp_sk(sk);
6020 
6021 	if (params.assoc_id != 0) {
6022 		asoc = sctp_id2assoc(sk, params.assoc_id);
6023 		if (!asoc)
6024 			return -EINVAL;
6025 		params.assoc_value = asoc->default_rcv_context;
6026 	} else {
6027 		params.assoc_value = sp->default_rcv_context;
6028 	}
6029 
6030 	if (put_user(len, optlen))
6031 		return -EFAULT;
6032 	if (copy_to_user(optval, &params, len))
6033 		return -EFAULT;
6034 
6035 	return 0;
6036 }
6037 
6038 /*
6039  * 8.1.16.  Get or Set the Maximum Fragmentation Size (SCTP_MAXSEG)
6040  * This option will get or set the maximum size to put in any outgoing
6041  * SCTP DATA chunk.  If a message is larger than this size it will be
6042  * fragmented by SCTP into the specified size.  Note that the underlying
6043  * SCTP implementation may fragment into smaller sized chunks when the
6044  * PMTU of the underlying association is smaller than the value set by
6045  * the user.  The default value for this option is '0' which indicates
6046  * the user is NOT limiting fragmentation and only the PMTU will effect
6047  * SCTP's choice of DATA chunk size.  Note also that values set larger
6048  * than the maximum size of an IP datagram will effectively let SCTP
6049  * control fragmentation (i.e. the same as setting this option to 0).
6050  *
6051  * The following structure is used to access and modify this parameter:
6052  *
6053  * struct sctp_assoc_value {
6054  *   sctp_assoc_t assoc_id;
6055  *   uint32_t assoc_value;
6056  * };
6057  *
6058  * assoc_id:  This parameter is ignored for one-to-one style sockets.
6059  *    For one-to-many style sockets this parameter indicates which
6060  *    association the user is performing an action upon.  Note that if
6061  *    this field's value is zero then the endpoints default value is
6062  *    changed (effecting future associations only).
6063  * assoc_value:  This parameter specifies the maximum size in bytes.
6064  */
6065 static int sctp_getsockopt_maxseg(struct sock *sk, int len,
6066 				  char __user *optval, int __user *optlen)
6067 {
6068 	struct sctp_assoc_value params;
6069 	struct sctp_association *asoc;
6070 
6071 	if (len == sizeof(int)) {
6072 		pr_warn_ratelimited(DEPRECATED
6073 				    "%s (pid %d) "
6074 				    "Use of int in maxseg socket option.\n"
6075 				    "Use struct sctp_assoc_value instead\n",
6076 				    current->comm, task_pid_nr(current));
6077 		params.assoc_id = 0;
6078 	} else if (len >= sizeof(struct sctp_assoc_value)) {
6079 		len = sizeof(struct sctp_assoc_value);
6080 		if (copy_from_user(&params, optval, sizeof(params)))
6081 			return -EFAULT;
6082 	} else
6083 		return -EINVAL;
6084 
6085 	asoc = sctp_id2assoc(sk, params.assoc_id);
6086 	if (!asoc && params.assoc_id && sctp_style(sk, UDP))
6087 		return -EINVAL;
6088 
6089 	if (asoc)
6090 		params.assoc_value = asoc->frag_point;
6091 	else
6092 		params.assoc_value = sctp_sk(sk)->user_frag;
6093 
6094 	if (put_user(len, optlen))
6095 		return -EFAULT;
6096 	if (len == sizeof(int)) {
6097 		if (copy_to_user(optval, &params.assoc_value, len))
6098 			return -EFAULT;
6099 	} else {
6100 		if (copy_to_user(optval, &params, len))
6101 			return -EFAULT;
6102 	}
6103 
6104 	return 0;
6105 }
6106 
6107 /*
6108  * 7.1.24.  Get or set fragmented interleave (SCTP_FRAGMENT_INTERLEAVE)
6109  * (chapter and verse is quoted at sctp_setsockopt_fragment_interleave())
6110  */
6111 static int sctp_getsockopt_fragment_interleave(struct sock *sk, int len,
6112 					       char __user *optval, int __user *optlen)
6113 {
6114 	int val;
6115 
6116 	if (len < sizeof(int))
6117 		return -EINVAL;
6118 
6119 	len = sizeof(int);
6120 
6121 	val = sctp_sk(sk)->frag_interleave;
6122 	if (put_user(len, optlen))
6123 		return -EFAULT;
6124 	if (copy_to_user(optval, &val, len))
6125 		return -EFAULT;
6126 
6127 	return 0;
6128 }
6129 
6130 /*
6131  * 7.1.25.  Set or Get the sctp partial delivery point
6132  * (chapter and verse is quoted at sctp_setsockopt_partial_delivery_point())
6133  */
6134 static int sctp_getsockopt_partial_delivery_point(struct sock *sk, int len,
6135 						  char __user *optval,
6136 						  int __user *optlen)
6137 {
6138 	u32 val;
6139 
6140 	if (len < sizeof(u32))
6141 		return -EINVAL;
6142 
6143 	len = sizeof(u32);
6144 
6145 	val = sctp_sk(sk)->pd_point;
6146 	if (put_user(len, optlen))
6147 		return -EFAULT;
6148 	if (copy_to_user(optval, &val, len))
6149 		return -EFAULT;
6150 
6151 	return 0;
6152 }
6153 
6154 /*
6155  * 7.1.28.  Set or Get the maximum burst (SCTP_MAX_BURST)
6156  * (chapter and verse is quoted at sctp_setsockopt_maxburst())
6157  */
6158 static int sctp_getsockopt_maxburst(struct sock *sk, int len,
6159 				    char __user *optval,
6160 				    int __user *optlen)
6161 {
6162 	struct sctp_assoc_value params;
6163 	struct sctp_sock *sp;
6164 	struct sctp_association *asoc;
6165 
6166 	if (len == sizeof(int)) {
6167 		pr_warn_ratelimited(DEPRECATED
6168 				    "%s (pid %d) "
6169 				    "Use of int in max_burst socket option.\n"
6170 				    "Use struct sctp_assoc_value instead\n",
6171 				    current->comm, task_pid_nr(current));
6172 		params.assoc_id = 0;
6173 	} else if (len >= sizeof(struct sctp_assoc_value)) {
6174 		len = sizeof(struct sctp_assoc_value);
6175 		if (copy_from_user(&params, optval, len))
6176 			return -EFAULT;
6177 	} else
6178 		return -EINVAL;
6179 
6180 	sp = sctp_sk(sk);
6181 
6182 	if (params.assoc_id != 0) {
6183 		asoc = sctp_id2assoc(sk, params.assoc_id);
6184 		if (!asoc)
6185 			return -EINVAL;
6186 		params.assoc_value = asoc->max_burst;
6187 	} else
6188 		params.assoc_value = sp->max_burst;
6189 
6190 	if (len == sizeof(int)) {
6191 		if (copy_to_user(optval, &params.assoc_value, len))
6192 			return -EFAULT;
6193 	} else {
6194 		if (copy_to_user(optval, &params, len))
6195 			return -EFAULT;
6196 	}
6197 
6198 	return 0;
6199 
6200 }
6201 
6202 static int sctp_getsockopt_hmac_ident(struct sock *sk, int len,
6203 				    char __user *optval, int __user *optlen)
6204 {
6205 	struct sctp_endpoint *ep = sctp_sk(sk)->ep;
6206 	struct sctp_hmacalgo  __user *p = (void __user *)optval;
6207 	struct sctp_hmac_algo_param *hmacs;
6208 	__u16 data_len = 0;
6209 	u32 num_idents;
6210 	int i;
6211 
6212 	if (!ep->auth_enable)
6213 		return -EACCES;
6214 
6215 	hmacs = ep->auth_hmacs_list;
6216 	data_len = ntohs(hmacs->param_hdr.length) -
6217 		   sizeof(struct sctp_paramhdr);
6218 
6219 	if (len < sizeof(struct sctp_hmacalgo) + data_len)
6220 		return -EINVAL;
6221 
6222 	len = sizeof(struct sctp_hmacalgo) + data_len;
6223 	num_idents = data_len / sizeof(u16);
6224 
6225 	if (put_user(len, optlen))
6226 		return -EFAULT;
6227 	if (put_user(num_idents, &p->shmac_num_idents))
6228 		return -EFAULT;
6229 	for (i = 0; i < num_idents; i++) {
6230 		__u16 hmacid = ntohs(hmacs->hmac_ids[i]);
6231 
6232 		if (copy_to_user(&p->shmac_idents[i], &hmacid, sizeof(__u16)))
6233 			return -EFAULT;
6234 	}
6235 	return 0;
6236 }
6237 
6238 static int sctp_getsockopt_active_key(struct sock *sk, int len,
6239 				    char __user *optval, int __user *optlen)
6240 {
6241 	struct sctp_endpoint *ep = sctp_sk(sk)->ep;
6242 	struct sctp_authkeyid val;
6243 	struct sctp_association *asoc;
6244 
6245 	if (!ep->auth_enable)
6246 		return -EACCES;
6247 
6248 	if (len < sizeof(struct sctp_authkeyid))
6249 		return -EINVAL;
6250 	if (copy_from_user(&val, optval, sizeof(struct sctp_authkeyid)))
6251 		return -EFAULT;
6252 
6253 	asoc = sctp_id2assoc(sk, val.scact_assoc_id);
6254 	if (!asoc && val.scact_assoc_id && sctp_style(sk, UDP))
6255 		return -EINVAL;
6256 
6257 	if (asoc)
6258 		val.scact_keynumber = asoc->active_key_id;
6259 	else
6260 		val.scact_keynumber = ep->active_key_id;
6261 
6262 	len = sizeof(struct sctp_authkeyid);
6263 	if (put_user(len, optlen))
6264 		return -EFAULT;
6265 	if (copy_to_user(optval, &val, len))
6266 		return -EFAULT;
6267 
6268 	return 0;
6269 }
6270 
6271 static int sctp_getsockopt_peer_auth_chunks(struct sock *sk, int len,
6272 				    char __user *optval, int __user *optlen)
6273 {
6274 	struct sctp_endpoint *ep = sctp_sk(sk)->ep;
6275 	struct sctp_authchunks __user *p = (void __user *)optval;
6276 	struct sctp_authchunks val;
6277 	struct sctp_association *asoc;
6278 	struct sctp_chunks_param *ch;
6279 	u32    num_chunks = 0;
6280 	char __user *to;
6281 
6282 	if (!ep->auth_enable)
6283 		return -EACCES;
6284 
6285 	if (len < sizeof(struct sctp_authchunks))
6286 		return -EINVAL;
6287 
6288 	if (copy_from_user(&val, optval, sizeof(struct sctp_authchunks)))
6289 		return -EFAULT;
6290 
6291 	to = p->gauth_chunks;
6292 	asoc = sctp_id2assoc(sk, val.gauth_assoc_id);
6293 	if (!asoc)
6294 		return -EINVAL;
6295 
6296 	ch = asoc->peer.peer_chunks;
6297 	if (!ch)
6298 		goto num;
6299 
6300 	/* See if the user provided enough room for all the data */
6301 	num_chunks = ntohs(ch->param_hdr.length) - sizeof(struct sctp_paramhdr);
6302 	if (len < num_chunks)
6303 		return -EINVAL;
6304 
6305 	if (copy_to_user(to, ch->chunks, num_chunks))
6306 		return -EFAULT;
6307 num:
6308 	len = sizeof(struct sctp_authchunks) + num_chunks;
6309 	if (put_user(len, optlen))
6310 		return -EFAULT;
6311 	if (put_user(num_chunks, &p->gauth_number_of_chunks))
6312 		return -EFAULT;
6313 	return 0;
6314 }
6315 
6316 static int sctp_getsockopt_local_auth_chunks(struct sock *sk, int len,
6317 				    char __user *optval, int __user *optlen)
6318 {
6319 	struct sctp_endpoint *ep = sctp_sk(sk)->ep;
6320 	struct sctp_authchunks __user *p = (void __user *)optval;
6321 	struct sctp_authchunks val;
6322 	struct sctp_association *asoc;
6323 	struct sctp_chunks_param *ch;
6324 	u32    num_chunks = 0;
6325 	char __user *to;
6326 
6327 	if (!ep->auth_enable)
6328 		return -EACCES;
6329 
6330 	if (len < sizeof(struct sctp_authchunks))
6331 		return -EINVAL;
6332 
6333 	if (copy_from_user(&val, optval, sizeof(struct sctp_authchunks)))
6334 		return -EFAULT;
6335 
6336 	to = p->gauth_chunks;
6337 	asoc = sctp_id2assoc(sk, val.gauth_assoc_id);
6338 	if (!asoc && val.gauth_assoc_id && sctp_style(sk, UDP))
6339 		return -EINVAL;
6340 
6341 	if (asoc)
6342 		ch = (struct sctp_chunks_param *)asoc->c.auth_chunks;
6343 	else
6344 		ch = ep->auth_chunk_list;
6345 
6346 	if (!ch)
6347 		goto num;
6348 
6349 	num_chunks = ntohs(ch->param_hdr.length) - sizeof(struct sctp_paramhdr);
6350 	if (len < sizeof(struct sctp_authchunks) + num_chunks)
6351 		return -EINVAL;
6352 
6353 	if (copy_to_user(to, ch->chunks, num_chunks))
6354 		return -EFAULT;
6355 num:
6356 	len = sizeof(struct sctp_authchunks) + num_chunks;
6357 	if (put_user(len, optlen))
6358 		return -EFAULT;
6359 	if (put_user(num_chunks, &p->gauth_number_of_chunks))
6360 		return -EFAULT;
6361 
6362 	return 0;
6363 }
6364 
6365 /*
6366  * 8.2.5.  Get the Current Number of Associations (SCTP_GET_ASSOC_NUMBER)
6367  * This option gets the current number of associations that are attached
6368  * to a one-to-many style socket.  The option value is an uint32_t.
6369  */
6370 static int sctp_getsockopt_assoc_number(struct sock *sk, int len,
6371 				    char __user *optval, int __user *optlen)
6372 {
6373 	struct sctp_sock *sp = sctp_sk(sk);
6374 	struct sctp_association *asoc;
6375 	u32 val = 0;
6376 
6377 	if (sctp_style(sk, TCP))
6378 		return -EOPNOTSUPP;
6379 
6380 	if (len < sizeof(u32))
6381 		return -EINVAL;
6382 
6383 	len = sizeof(u32);
6384 
6385 	list_for_each_entry(asoc, &(sp->ep->asocs), asocs) {
6386 		val++;
6387 	}
6388 
6389 	if (put_user(len, optlen))
6390 		return -EFAULT;
6391 	if (copy_to_user(optval, &val, len))
6392 		return -EFAULT;
6393 
6394 	return 0;
6395 }
6396 
6397 /*
6398  * 8.1.23 SCTP_AUTO_ASCONF
6399  * See the corresponding setsockopt entry as description
6400  */
6401 static int sctp_getsockopt_auto_asconf(struct sock *sk, int len,
6402 				   char __user *optval, int __user *optlen)
6403 {
6404 	int val = 0;
6405 
6406 	if (len < sizeof(int))
6407 		return -EINVAL;
6408 
6409 	len = sizeof(int);
6410 	if (sctp_sk(sk)->do_auto_asconf && sctp_is_ep_boundall(sk))
6411 		val = 1;
6412 	if (put_user(len, optlen))
6413 		return -EFAULT;
6414 	if (copy_to_user(optval, &val, len))
6415 		return -EFAULT;
6416 	return 0;
6417 }
6418 
6419 /*
6420  * 8.2.6. Get the Current Identifiers of Associations
6421  *        (SCTP_GET_ASSOC_ID_LIST)
6422  *
6423  * This option gets the current list of SCTP association identifiers of
6424  * the SCTP associations handled by a one-to-many style socket.
6425  */
6426 static int sctp_getsockopt_assoc_ids(struct sock *sk, int len,
6427 				    char __user *optval, int __user *optlen)
6428 {
6429 	struct sctp_sock *sp = sctp_sk(sk);
6430 	struct sctp_association *asoc;
6431 	struct sctp_assoc_ids *ids;
6432 	u32 num = 0;
6433 
6434 	if (sctp_style(sk, TCP))
6435 		return -EOPNOTSUPP;
6436 
6437 	if (len < sizeof(struct sctp_assoc_ids))
6438 		return -EINVAL;
6439 
6440 	list_for_each_entry(asoc, &(sp->ep->asocs), asocs) {
6441 		num++;
6442 	}
6443 
6444 	if (len < sizeof(struct sctp_assoc_ids) + sizeof(sctp_assoc_t) * num)
6445 		return -EINVAL;
6446 
6447 	len = sizeof(struct sctp_assoc_ids) + sizeof(sctp_assoc_t) * num;
6448 
6449 	ids = kmalloc(len, GFP_USER | __GFP_NOWARN);
6450 	if (unlikely(!ids))
6451 		return -ENOMEM;
6452 
6453 	ids->gaids_number_of_ids = num;
6454 	num = 0;
6455 	list_for_each_entry(asoc, &(sp->ep->asocs), asocs) {
6456 		ids->gaids_assoc_id[num++] = asoc->assoc_id;
6457 	}
6458 
6459 	if (put_user(len, optlen) || copy_to_user(optval, ids, len)) {
6460 		kfree(ids);
6461 		return -EFAULT;
6462 	}
6463 
6464 	kfree(ids);
6465 	return 0;
6466 }
6467 
6468 /*
6469  * SCTP_PEER_ADDR_THLDS
6470  *
6471  * This option allows us to fetch the partially failed threshold for one or all
6472  * transports in an association.  See Section 6.1 of:
6473  * http://www.ietf.org/id/draft-nishida-tsvwg-sctp-failover-05.txt
6474  */
6475 static int sctp_getsockopt_paddr_thresholds(struct sock *sk,
6476 					    char __user *optval,
6477 					    int len,
6478 					    int __user *optlen)
6479 {
6480 	struct sctp_paddrthlds val;
6481 	struct sctp_transport *trans;
6482 	struct sctp_association *asoc;
6483 
6484 	if (len < sizeof(struct sctp_paddrthlds))
6485 		return -EINVAL;
6486 	len = sizeof(struct sctp_paddrthlds);
6487 	if (copy_from_user(&val, (struct sctp_paddrthlds __user *)optval, len))
6488 		return -EFAULT;
6489 
6490 	if (sctp_is_any(sk, (const union sctp_addr *)&val.spt_address)) {
6491 		asoc = sctp_id2assoc(sk, val.spt_assoc_id);
6492 		if (!asoc)
6493 			return -ENOENT;
6494 
6495 		val.spt_pathpfthld = asoc->pf_retrans;
6496 		val.spt_pathmaxrxt = asoc->pathmaxrxt;
6497 	} else {
6498 		trans = sctp_addr_id2transport(sk, &val.spt_address,
6499 					       val.spt_assoc_id);
6500 		if (!trans)
6501 			return -ENOENT;
6502 
6503 		val.spt_pathmaxrxt = trans->pathmaxrxt;
6504 		val.spt_pathpfthld = trans->pf_retrans;
6505 	}
6506 
6507 	if (put_user(len, optlen) || copy_to_user(optval, &val, len))
6508 		return -EFAULT;
6509 
6510 	return 0;
6511 }
6512 
6513 /*
6514  * SCTP_GET_ASSOC_STATS
6515  *
6516  * This option retrieves local per endpoint statistics. It is modeled
6517  * after OpenSolaris' implementation
6518  */
6519 static int sctp_getsockopt_assoc_stats(struct sock *sk, int len,
6520 				       char __user *optval,
6521 				       int __user *optlen)
6522 {
6523 	struct sctp_assoc_stats sas;
6524 	struct sctp_association *asoc = NULL;
6525 
6526 	/* User must provide at least the assoc id */
6527 	if (len < sizeof(sctp_assoc_t))
6528 		return -EINVAL;
6529 
6530 	/* Allow the struct to grow and fill in as much as possible */
6531 	len = min_t(size_t, len, sizeof(sas));
6532 
6533 	if (copy_from_user(&sas, optval, len))
6534 		return -EFAULT;
6535 
6536 	asoc = sctp_id2assoc(sk, sas.sas_assoc_id);
6537 	if (!asoc)
6538 		return -EINVAL;
6539 
6540 	sas.sas_rtxchunks = asoc->stats.rtxchunks;
6541 	sas.sas_gapcnt = asoc->stats.gapcnt;
6542 	sas.sas_outofseqtsns = asoc->stats.outofseqtsns;
6543 	sas.sas_osacks = asoc->stats.osacks;
6544 	sas.sas_isacks = asoc->stats.isacks;
6545 	sas.sas_octrlchunks = asoc->stats.octrlchunks;
6546 	sas.sas_ictrlchunks = asoc->stats.ictrlchunks;
6547 	sas.sas_oodchunks = asoc->stats.oodchunks;
6548 	sas.sas_iodchunks = asoc->stats.iodchunks;
6549 	sas.sas_ouodchunks = asoc->stats.ouodchunks;
6550 	sas.sas_iuodchunks = asoc->stats.iuodchunks;
6551 	sas.sas_idupchunks = asoc->stats.idupchunks;
6552 	sas.sas_opackets = asoc->stats.opackets;
6553 	sas.sas_ipackets = asoc->stats.ipackets;
6554 
6555 	/* New high max rto observed, will return 0 if not a single
6556 	 * RTO update took place. obs_rto_ipaddr will be bogus
6557 	 * in such a case
6558 	 */
6559 	sas.sas_maxrto = asoc->stats.max_obs_rto;
6560 	memcpy(&sas.sas_obs_rto_ipaddr, &asoc->stats.obs_rto_ipaddr,
6561 		sizeof(struct sockaddr_storage));
6562 
6563 	/* Mark beginning of a new observation period */
6564 	asoc->stats.max_obs_rto = asoc->rto_min;
6565 
6566 	if (put_user(len, optlen))
6567 		return -EFAULT;
6568 
6569 	pr_debug("%s: len:%d, assoc_id:%d\n", __func__, len, sas.sas_assoc_id);
6570 
6571 	if (copy_to_user(optval, &sas, len))
6572 		return -EFAULT;
6573 
6574 	return 0;
6575 }
6576 
6577 static int sctp_getsockopt_recvrcvinfo(struct sock *sk,	int len,
6578 				       char __user *optval,
6579 				       int __user *optlen)
6580 {
6581 	int val = 0;
6582 
6583 	if (len < sizeof(int))
6584 		return -EINVAL;
6585 
6586 	len = sizeof(int);
6587 	if (sctp_sk(sk)->recvrcvinfo)
6588 		val = 1;
6589 	if (put_user(len, optlen))
6590 		return -EFAULT;
6591 	if (copy_to_user(optval, &val, len))
6592 		return -EFAULT;
6593 
6594 	return 0;
6595 }
6596 
6597 static int sctp_getsockopt_recvnxtinfo(struct sock *sk,	int len,
6598 				       char __user *optval,
6599 				       int __user *optlen)
6600 {
6601 	int val = 0;
6602 
6603 	if (len < sizeof(int))
6604 		return -EINVAL;
6605 
6606 	len = sizeof(int);
6607 	if (sctp_sk(sk)->recvnxtinfo)
6608 		val = 1;
6609 	if (put_user(len, optlen))
6610 		return -EFAULT;
6611 	if (copy_to_user(optval, &val, len))
6612 		return -EFAULT;
6613 
6614 	return 0;
6615 }
6616 
6617 static int sctp_getsockopt_pr_supported(struct sock *sk, int len,
6618 					char __user *optval,
6619 					int __user *optlen)
6620 {
6621 	struct sctp_assoc_value params;
6622 	struct sctp_association *asoc;
6623 	int retval = -EFAULT;
6624 
6625 	if (len < sizeof(params)) {
6626 		retval = -EINVAL;
6627 		goto out;
6628 	}
6629 
6630 	len = sizeof(params);
6631 	if (copy_from_user(&params, optval, len))
6632 		goto out;
6633 
6634 	asoc = sctp_id2assoc(sk, params.assoc_id);
6635 	if (asoc) {
6636 		params.assoc_value = asoc->prsctp_enable;
6637 	} else if (!params.assoc_id) {
6638 		struct sctp_sock *sp = sctp_sk(sk);
6639 
6640 		params.assoc_value = sp->ep->prsctp_enable;
6641 	} else {
6642 		retval = -EINVAL;
6643 		goto out;
6644 	}
6645 
6646 	if (put_user(len, optlen))
6647 		goto out;
6648 
6649 	if (copy_to_user(optval, &params, len))
6650 		goto out;
6651 
6652 	retval = 0;
6653 
6654 out:
6655 	return retval;
6656 }
6657 
6658 static int sctp_getsockopt_default_prinfo(struct sock *sk, int len,
6659 					  char __user *optval,
6660 					  int __user *optlen)
6661 {
6662 	struct sctp_default_prinfo info;
6663 	struct sctp_association *asoc;
6664 	int retval = -EFAULT;
6665 
6666 	if (len < sizeof(info)) {
6667 		retval = -EINVAL;
6668 		goto out;
6669 	}
6670 
6671 	len = sizeof(info);
6672 	if (copy_from_user(&info, optval, len))
6673 		goto out;
6674 
6675 	asoc = sctp_id2assoc(sk, info.pr_assoc_id);
6676 	if (asoc) {
6677 		info.pr_policy = SCTP_PR_POLICY(asoc->default_flags);
6678 		info.pr_value = asoc->default_timetolive;
6679 	} else if (!info.pr_assoc_id) {
6680 		struct sctp_sock *sp = sctp_sk(sk);
6681 
6682 		info.pr_policy = SCTP_PR_POLICY(sp->default_flags);
6683 		info.pr_value = sp->default_timetolive;
6684 	} else {
6685 		retval = -EINVAL;
6686 		goto out;
6687 	}
6688 
6689 	if (put_user(len, optlen))
6690 		goto out;
6691 
6692 	if (copy_to_user(optval, &info, len))
6693 		goto out;
6694 
6695 	retval = 0;
6696 
6697 out:
6698 	return retval;
6699 }
6700 
6701 static int sctp_getsockopt_pr_assocstatus(struct sock *sk, int len,
6702 					  char __user *optval,
6703 					  int __user *optlen)
6704 {
6705 	struct sctp_prstatus params;
6706 	struct sctp_association *asoc;
6707 	int policy;
6708 	int retval = -EINVAL;
6709 
6710 	if (len < sizeof(params))
6711 		goto out;
6712 
6713 	len = sizeof(params);
6714 	if (copy_from_user(&params, optval, len)) {
6715 		retval = -EFAULT;
6716 		goto out;
6717 	}
6718 
6719 	policy = params.sprstat_policy;
6720 	if (policy & ~SCTP_PR_SCTP_MASK)
6721 		goto out;
6722 
6723 	asoc = sctp_id2assoc(sk, params.sprstat_assoc_id);
6724 	if (!asoc)
6725 		goto out;
6726 
6727 	if (policy == SCTP_PR_SCTP_NONE) {
6728 		params.sprstat_abandoned_unsent = 0;
6729 		params.sprstat_abandoned_sent = 0;
6730 		for (policy = 0; policy <= SCTP_PR_INDEX(MAX); policy++) {
6731 			params.sprstat_abandoned_unsent +=
6732 				asoc->abandoned_unsent[policy];
6733 			params.sprstat_abandoned_sent +=
6734 				asoc->abandoned_sent[policy];
6735 		}
6736 	} else {
6737 		params.sprstat_abandoned_unsent =
6738 			asoc->abandoned_unsent[__SCTP_PR_INDEX(policy)];
6739 		params.sprstat_abandoned_sent =
6740 			asoc->abandoned_sent[__SCTP_PR_INDEX(policy)];
6741 	}
6742 
6743 	if (put_user(len, optlen)) {
6744 		retval = -EFAULT;
6745 		goto out;
6746 	}
6747 
6748 	if (copy_to_user(optval, &params, len)) {
6749 		retval = -EFAULT;
6750 		goto out;
6751 	}
6752 
6753 	retval = 0;
6754 
6755 out:
6756 	return retval;
6757 }
6758 
6759 static int sctp_getsockopt_pr_streamstatus(struct sock *sk, int len,
6760 					   char __user *optval,
6761 					   int __user *optlen)
6762 {
6763 	struct sctp_stream_out_ext *streamoute;
6764 	struct sctp_association *asoc;
6765 	struct sctp_prstatus params;
6766 	int retval = -EINVAL;
6767 	int policy;
6768 
6769 	if (len < sizeof(params))
6770 		goto out;
6771 
6772 	len = sizeof(params);
6773 	if (copy_from_user(&params, optval, len)) {
6774 		retval = -EFAULT;
6775 		goto out;
6776 	}
6777 
6778 	policy = params.sprstat_policy;
6779 	if (policy & ~SCTP_PR_SCTP_MASK)
6780 		goto out;
6781 
6782 	asoc = sctp_id2assoc(sk, params.sprstat_assoc_id);
6783 	if (!asoc || params.sprstat_sid >= asoc->stream.outcnt)
6784 		goto out;
6785 
6786 	streamoute = asoc->stream.out[params.sprstat_sid].ext;
6787 	if (!streamoute) {
6788 		/* Not allocated yet, means all stats are 0 */
6789 		params.sprstat_abandoned_unsent = 0;
6790 		params.sprstat_abandoned_sent = 0;
6791 		retval = 0;
6792 		goto out;
6793 	}
6794 
6795 	if (policy == SCTP_PR_SCTP_NONE) {
6796 		params.sprstat_abandoned_unsent = 0;
6797 		params.sprstat_abandoned_sent = 0;
6798 		for (policy = 0; policy <= SCTP_PR_INDEX(MAX); policy++) {
6799 			params.sprstat_abandoned_unsent +=
6800 				streamoute->abandoned_unsent[policy];
6801 			params.sprstat_abandoned_sent +=
6802 				streamoute->abandoned_sent[policy];
6803 		}
6804 	} else {
6805 		params.sprstat_abandoned_unsent =
6806 			streamoute->abandoned_unsent[__SCTP_PR_INDEX(policy)];
6807 		params.sprstat_abandoned_sent =
6808 			streamoute->abandoned_sent[__SCTP_PR_INDEX(policy)];
6809 	}
6810 
6811 	if (put_user(len, optlen) || copy_to_user(optval, &params, len)) {
6812 		retval = -EFAULT;
6813 		goto out;
6814 	}
6815 
6816 	retval = 0;
6817 
6818 out:
6819 	return retval;
6820 }
6821 
6822 static int sctp_getsockopt_reconfig_supported(struct sock *sk, int len,
6823 					      char __user *optval,
6824 					      int __user *optlen)
6825 {
6826 	struct sctp_assoc_value params;
6827 	struct sctp_association *asoc;
6828 	int retval = -EFAULT;
6829 
6830 	if (len < sizeof(params)) {
6831 		retval = -EINVAL;
6832 		goto out;
6833 	}
6834 
6835 	len = sizeof(params);
6836 	if (copy_from_user(&params, optval, len))
6837 		goto out;
6838 
6839 	asoc = sctp_id2assoc(sk, params.assoc_id);
6840 	if (asoc) {
6841 		params.assoc_value = asoc->reconf_enable;
6842 	} else if (!params.assoc_id) {
6843 		struct sctp_sock *sp = sctp_sk(sk);
6844 
6845 		params.assoc_value = sp->ep->reconf_enable;
6846 	} else {
6847 		retval = -EINVAL;
6848 		goto out;
6849 	}
6850 
6851 	if (put_user(len, optlen))
6852 		goto out;
6853 
6854 	if (copy_to_user(optval, &params, len))
6855 		goto out;
6856 
6857 	retval = 0;
6858 
6859 out:
6860 	return retval;
6861 }
6862 
6863 static int sctp_getsockopt_enable_strreset(struct sock *sk, int len,
6864 					   char __user *optval,
6865 					   int __user *optlen)
6866 {
6867 	struct sctp_assoc_value params;
6868 	struct sctp_association *asoc;
6869 	int retval = -EFAULT;
6870 
6871 	if (len < sizeof(params)) {
6872 		retval = -EINVAL;
6873 		goto out;
6874 	}
6875 
6876 	len = sizeof(params);
6877 	if (copy_from_user(&params, optval, len))
6878 		goto out;
6879 
6880 	asoc = sctp_id2assoc(sk, params.assoc_id);
6881 	if (asoc) {
6882 		params.assoc_value = asoc->strreset_enable;
6883 	} else if (!params.assoc_id) {
6884 		struct sctp_sock *sp = sctp_sk(sk);
6885 
6886 		params.assoc_value = sp->ep->strreset_enable;
6887 	} else {
6888 		retval = -EINVAL;
6889 		goto out;
6890 	}
6891 
6892 	if (put_user(len, optlen))
6893 		goto out;
6894 
6895 	if (copy_to_user(optval, &params, len))
6896 		goto out;
6897 
6898 	retval = 0;
6899 
6900 out:
6901 	return retval;
6902 }
6903 
6904 static int sctp_getsockopt_scheduler(struct sock *sk, int len,
6905 				     char __user *optval,
6906 				     int __user *optlen)
6907 {
6908 	struct sctp_assoc_value params;
6909 	struct sctp_association *asoc;
6910 	int retval = -EFAULT;
6911 
6912 	if (len < sizeof(params)) {
6913 		retval = -EINVAL;
6914 		goto out;
6915 	}
6916 
6917 	len = sizeof(params);
6918 	if (copy_from_user(&params, optval, len))
6919 		goto out;
6920 
6921 	asoc = sctp_id2assoc(sk, params.assoc_id);
6922 	if (!asoc) {
6923 		retval = -EINVAL;
6924 		goto out;
6925 	}
6926 
6927 	params.assoc_value = sctp_sched_get_sched(asoc);
6928 
6929 	if (put_user(len, optlen))
6930 		goto out;
6931 
6932 	if (copy_to_user(optval, &params, len))
6933 		goto out;
6934 
6935 	retval = 0;
6936 
6937 out:
6938 	return retval;
6939 }
6940 
6941 static int sctp_getsockopt_scheduler_value(struct sock *sk, int len,
6942 					   char __user *optval,
6943 					   int __user *optlen)
6944 {
6945 	struct sctp_stream_value params;
6946 	struct sctp_association *asoc;
6947 	int retval = -EFAULT;
6948 
6949 	if (len < sizeof(params)) {
6950 		retval = -EINVAL;
6951 		goto out;
6952 	}
6953 
6954 	len = sizeof(params);
6955 	if (copy_from_user(&params, optval, len))
6956 		goto out;
6957 
6958 	asoc = sctp_id2assoc(sk, params.assoc_id);
6959 	if (!asoc) {
6960 		retval = -EINVAL;
6961 		goto out;
6962 	}
6963 
6964 	retval = sctp_sched_get_value(asoc, params.stream_id,
6965 				      &params.stream_value);
6966 	if (retval)
6967 		goto out;
6968 
6969 	if (put_user(len, optlen)) {
6970 		retval = -EFAULT;
6971 		goto out;
6972 	}
6973 
6974 	if (copy_to_user(optval, &params, len)) {
6975 		retval = -EFAULT;
6976 		goto out;
6977 	}
6978 
6979 out:
6980 	return retval;
6981 }
6982 
6983 static int sctp_getsockopt(struct sock *sk, int level, int optname,
6984 			   char __user *optval, int __user *optlen)
6985 {
6986 	int retval = 0;
6987 	int len;
6988 
6989 	pr_debug("%s: sk:%p, optname:%d\n", __func__, sk, optname);
6990 
6991 	/* I can hardly begin to describe how wrong this is.  This is
6992 	 * so broken as to be worse than useless.  The API draft
6993 	 * REALLY is NOT helpful here...  I am not convinced that the
6994 	 * semantics of getsockopt() with a level OTHER THAN SOL_SCTP
6995 	 * are at all well-founded.
6996 	 */
6997 	if (level != SOL_SCTP) {
6998 		struct sctp_af *af = sctp_sk(sk)->pf->af;
6999 
7000 		retval = af->getsockopt(sk, level, optname, optval, optlen);
7001 		return retval;
7002 	}
7003 
7004 	if (get_user(len, optlen))
7005 		return -EFAULT;
7006 
7007 	if (len < 0)
7008 		return -EINVAL;
7009 
7010 	lock_sock(sk);
7011 
7012 	switch (optname) {
7013 	case SCTP_STATUS:
7014 		retval = sctp_getsockopt_sctp_status(sk, len, optval, optlen);
7015 		break;
7016 	case SCTP_DISABLE_FRAGMENTS:
7017 		retval = sctp_getsockopt_disable_fragments(sk, len, optval,
7018 							   optlen);
7019 		break;
7020 	case SCTP_EVENTS:
7021 		retval = sctp_getsockopt_events(sk, len, optval, optlen);
7022 		break;
7023 	case SCTP_AUTOCLOSE:
7024 		retval = sctp_getsockopt_autoclose(sk, len, optval, optlen);
7025 		break;
7026 	case SCTP_SOCKOPT_PEELOFF:
7027 		retval = sctp_getsockopt_peeloff(sk, len, optval, optlen);
7028 		break;
7029 	case SCTP_SOCKOPT_PEELOFF_FLAGS:
7030 		retval = sctp_getsockopt_peeloff_flags(sk, len, optval, optlen);
7031 		break;
7032 	case SCTP_PEER_ADDR_PARAMS:
7033 		retval = sctp_getsockopt_peer_addr_params(sk, len, optval,
7034 							  optlen);
7035 		break;
7036 	case SCTP_DELAYED_SACK:
7037 		retval = sctp_getsockopt_delayed_ack(sk, len, optval,
7038 							  optlen);
7039 		break;
7040 	case SCTP_INITMSG:
7041 		retval = sctp_getsockopt_initmsg(sk, len, optval, optlen);
7042 		break;
7043 	case SCTP_GET_PEER_ADDRS:
7044 		retval = sctp_getsockopt_peer_addrs(sk, len, optval,
7045 						    optlen);
7046 		break;
7047 	case SCTP_GET_LOCAL_ADDRS:
7048 		retval = sctp_getsockopt_local_addrs(sk, len, optval,
7049 						     optlen);
7050 		break;
7051 	case SCTP_SOCKOPT_CONNECTX3:
7052 		retval = sctp_getsockopt_connectx3(sk, len, optval, optlen);
7053 		break;
7054 	case SCTP_DEFAULT_SEND_PARAM:
7055 		retval = sctp_getsockopt_default_send_param(sk, len,
7056 							    optval, optlen);
7057 		break;
7058 	case SCTP_DEFAULT_SNDINFO:
7059 		retval = sctp_getsockopt_default_sndinfo(sk, len,
7060 							 optval, optlen);
7061 		break;
7062 	case SCTP_PRIMARY_ADDR:
7063 		retval = sctp_getsockopt_primary_addr(sk, len, optval, optlen);
7064 		break;
7065 	case SCTP_NODELAY:
7066 		retval = sctp_getsockopt_nodelay(sk, len, optval, optlen);
7067 		break;
7068 	case SCTP_RTOINFO:
7069 		retval = sctp_getsockopt_rtoinfo(sk, len, optval, optlen);
7070 		break;
7071 	case SCTP_ASSOCINFO:
7072 		retval = sctp_getsockopt_associnfo(sk, len, optval, optlen);
7073 		break;
7074 	case SCTP_I_WANT_MAPPED_V4_ADDR:
7075 		retval = sctp_getsockopt_mappedv4(sk, len, optval, optlen);
7076 		break;
7077 	case SCTP_MAXSEG:
7078 		retval = sctp_getsockopt_maxseg(sk, len, optval, optlen);
7079 		break;
7080 	case SCTP_GET_PEER_ADDR_INFO:
7081 		retval = sctp_getsockopt_peer_addr_info(sk, len, optval,
7082 							optlen);
7083 		break;
7084 	case SCTP_ADAPTATION_LAYER:
7085 		retval = sctp_getsockopt_adaptation_layer(sk, len, optval,
7086 							optlen);
7087 		break;
7088 	case SCTP_CONTEXT:
7089 		retval = sctp_getsockopt_context(sk, len, optval, optlen);
7090 		break;
7091 	case SCTP_FRAGMENT_INTERLEAVE:
7092 		retval = sctp_getsockopt_fragment_interleave(sk, len, optval,
7093 							     optlen);
7094 		break;
7095 	case SCTP_PARTIAL_DELIVERY_POINT:
7096 		retval = sctp_getsockopt_partial_delivery_point(sk, len, optval,
7097 								optlen);
7098 		break;
7099 	case SCTP_MAX_BURST:
7100 		retval = sctp_getsockopt_maxburst(sk, len, optval, optlen);
7101 		break;
7102 	case SCTP_AUTH_KEY:
7103 	case SCTP_AUTH_CHUNK:
7104 	case SCTP_AUTH_DELETE_KEY:
7105 		retval = -EOPNOTSUPP;
7106 		break;
7107 	case SCTP_HMAC_IDENT:
7108 		retval = sctp_getsockopt_hmac_ident(sk, len, optval, optlen);
7109 		break;
7110 	case SCTP_AUTH_ACTIVE_KEY:
7111 		retval = sctp_getsockopt_active_key(sk, len, optval, optlen);
7112 		break;
7113 	case SCTP_PEER_AUTH_CHUNKS:
7114 		retval = sctp_getsockopt_peer_auth_chunks(sk, len, optval,
7115 							optlen);
7116 		break;
7117 	case SCTP_LOCAL_AUTH_CHUNKS:
7118 		retval = sctp_getsockopt_local_auth_chunks(sk, len, optval,
7119 							optlen);
7120 		break;
7121 	case SCTP_GET_ASSOC_NUMBER:
7122 		retval = sctp_getsockopt_assoc_number(sk, len, optval, optlen);
7123 		break;
7124 	case SCTP_GET_ASSOC_ID_LIST:
7125 		retval = sctp_getsockopt_assoc_ids(sk, len, optval, optlen);
7126 		break;
7127 	case SCTP_AUTO_ASCONF:
7128 		retval = sctp_getsockopt_auto_asconf(sk, len, optval, optlen);
7129 		break;
7130 	case SCTP_PEER_ADDR_THLDS:
7131 		retval = sctp_getsockopt_paddr_thresholds(sk, optval, len, optlen);
7132 		break;
7133 	case SCTP_GET_ASSOC_STATS:
7134 		retval = sctp_getsockopt_assoc_stats(sk, len, optval, optlen);
7135 		break;
7136 	case SCTP_RECVRCVINFO:
7137 		retval = sctp_getsockopt_recvrcvinfo(sk, len, optval, optlen);
7138 		break;
7139 	case SCTP_RECVNXTINFO:
7140 		retval = sctp_getsockopt_recvnxtinfo(sk, len, optval, optlen);
7141 		break;
7142 	case SCTP_PR_SUPPORTED:
7143 		retval = sctp_getsockopt_pr_supported(sk, len, optval, optlen);
7144 		break;
7145 	case SCTP_DEFAULT_PRINFO:
7146 		retval = sctp_getsockopt_default_prinfo(sk, len, optval,
7147 							optlen);
7148 		break;
7149 	case SCTP_PR_ASSOC_STATUS:
7150 		retval = sctp_getsockopt_pr_assocstatus(sk, len, optval,
7151 							optlen);
7152 		break;
7153 	case SCTP_PR_STREAM_STATUS:
7154 		retval = sctp_getsockopt_pr_streamstatus(sk, len, optval,
7155 							 optlen);
7156 		break;
7157 	case SCTP_RECONFIG_SUPPORTED:
7158 		retval = sctp_getsockopt_reconfig_supported(sk, len, optval,
7159 							    optlen);
7160 		break;
7161 	case SCTP_ENABLE_STREAM_RESET:
7162 		retval = sctp_getsockopt_enable_strreset(sk, len, optval,
7163 							 optlen);
7164 		break;
7165 	case SCTP_STREAM_SCHEDULER:
7166 		retval = sctp_getsockopt_scheduler(sk, len, optval,
7167 						   optlen);
7168 		break;
7169 	case SCTP_STREAM_SCHEDULER_VALUE:
7170 		retval = sctp_getsockopt_scheduler_value(sk, len, optval,
7171 							 optlen);
7172 		break;
7173 	default:
7174 		retval = -ENOPROTOOPT;
7175 		break;
7176 	}
7177 
7178 	release_sock(sk);
7179 	return retval;
7180 }
7181 
7182 static int sctp_hash(struct sock *sk)
7183 {
7184 	/* STUB */
7185 	return 0;
7186 }
7187 
7188 static void sctp_unhash(struct sock *sk)
7189 {
7190 	/* STUB */
7191 }
7192 
7193 /* Check if port is acceptable.  Possibly find first available port.
7194  *
7195  * The port hash table (contained in the 'global' SCTP protocol storage
7196  * returned by struct sctp_protocol *sctp_get_protocol()). The hash
7197  * table is an array of 4096 lists (sctp_bind_hashbucket). Each
7198  * list (the list number is the port number hashed out, so as you
7199  * would expect from a hash function, all the ports in a given list have
7200  * such a number that hashes out to the same list number; you were
7201  * expecting that, right?); so each list has a set of ports, with a
7202  * link to the socket (struct sock) that uses it, the port number and
7203  * a fastreuse flag (FIXME: NPI ipg).
7204  */
7205 static struct sctp_bind_bucket *sctp_bucket_create(
7206 	struct sctp_bind_hashbucket *head, struct net *, unsigned short snum);
7207 
7208 static long sctp_get_port_local(struct sock *sk, union sctp_addr *addr)
7209 {
7210 	struct sctp_bind_hashbucket *head; /* hash list */
7211 	struct sctp_bind_bucket *pp;
7212 	unsigned short snum;
7213 	int ret;
7214 
7215 	snum = ntohs(addr->v4.sin_port);
7216 
7217 	pr_debug("%s: begins, snum:%d\n", __func__, snum);
7218 
7219 	local_bh_disable();
7220 
7221 	if (snum == 0) {
7222 		/* Search for an available port. */
7223 		int low, high, remaining, index;
7224 		unsigned int rover;
7225 		struct net *net = sock_net(sk);
7226 
7227 		inet_get_local_port_range(net, &low, &high);
7228 		remaining = (high - low) + 1;
7229 		rover = prandom_u32() % remaining + low;
7230 
7231 		do {
7232 			rover++;
7233 			if ((rover < low) || (rover > high))
7234 				rover = low;
7235 			if (inet_is_local_reserved_port(net, rover))
7236 				continue;
7237 			index = sctp_phashfn(sock_net(sk), rover);
7238 			head = &sctp_port_hashtable[index];
7239 			spin_lock(&head->lock);
7240 			sctp_for_each_hentry(pp, &head->chain)
7241 				if ((pp->port == rover) &&
7242 				    net_eq(sock_net(sk), pp->net))
7243 					goto next;
7244 			break;
7245 		next:
7246 			spin_unlock(&head->lock);
7247 		} while (--remaining > 0);
7248 
7249 		/* Exhausted local port range during search? */
7250 		ret = 1;
7251 		if (remaining <= 0)
7252 			goto fail;
7253 
7254 		/* OK, here is the one we will use.  HEAD (the port
7255 		 * hash table list entry) is non-NULL and we hold it's
7256 		 * mutex.
7257 		 */
7258 		snum = rover;
7259 	} else {
7260 		/* We are given an specific port number; we verify
7261 		 * that it is not being used. If it is used, we will
7262 		 * exahust the search in the hash list corresponding
7263 		 * to the port number (snum) - we detect that with the
7264 		 * port iterator, pp being NULL.
7265 		 */
7266 		head = &sctp_port_hashtable[sctp_phashfn(sock_net(sk), snum)];
7267 		spin_lock(&head->lock);
7268 		sctp_for_each_hentry(pp, &head->chain) {
7269 			if ((pp->port == snum) && net_eq(pp->net, sock_net(sk)))
7270 				goto pp_found;
7271 		}
7272 	}
7273 	pp = NULL;
7274 	goto pp_not_found;
7275 pp_found:
7276 	if (!hlist_empty(&pp->owner)) {
7277 		/* We had a port hash table hit - there is an
7278 		 * available port (pp != NULL) and it is being
7279 		 * used by other socket (pp->owner not empty); that other
7280 		 * socket is going to be sk2.
7281 		 */
7282 		int reuse = sk->sk_reuse;
7283 		struct sock *sk2;
7284 
7285 		pr_debug("%s: found a possible match\n", __func__);
7286 
7287 		if (pp->fastreuse && sk->sk_reuse &&
7288 			sk->sk_state != SCTP_SS_LISTENING)
7289 			goto success;
7290 
7291 		/* Run through the list of sockets bound to the port
7292 		 * (pp->port) [via the pointers bind_next and
7293 		 * bind_pprev in the struct sock *sk2 (pp->sk)]. On each one,
7294 		 * we get the endpoint they describe and run through
7295 		 * the endpoint's list of IP (v4 or v6) addresses,
7296 		 * comparing each of the addresses with the address of
7297 		 * the socket sk. If we find a match, then that means
7298 		 * that this port/socket (sk) combination are already
7299 		 * in an endpoint.
7300 		 */
7301 		sk_for_each_bound(sk2, &pp->owner) {
7302 			struct sctp_endpoint *ep2;
7303 			ep2 = sctp_sk(sk2)->ep;
7304 
7305 			if (sk == sk2 ||
7306 			    (reuse && sk2->sk_reuse &&
7307 			     sk2->sk_state != SCTP_SS_LISTENING))
7308 				continue;
7309 
7310 			if (sctp_bind_addr_conflict(&ep2->base.bind_addr, addr,
7311 						 sctp_sk(sk2), sctp_sk(sk))) {
7312 				ret = (long)sk2;
7313 				goto fail_unlock;
7314 			}
7315 		}
7316 
7317 		pr_debug("%s: found a match\n", __func__);
7318 	}
7319 pp_not_found:
7320 	/* If there was a hash table miss, create a new port.  */
7321 	ret = 1;
7322 	if (!pp && !(pp = sctp_bucket_create(head, sock_net(sk), snum)))
7323 		goto fail_unlock;
7324 
7325 	/* In either case (hit or miss), make sure fastreuse is 1 only
7326 	 * if sk->sk_reuse is too (that is, if the caller requested
7327 	 * SO_REUSEADDR on this socket -sk-).
7328 	 */
7329 	if (hlist_empty(&pp->owner)) {
7330 		if (sk->sk_reuse && sk->sk_state != SCTP_SS_LISTENING)
7331 			pp->fastreuse = 1;
7332 		else
7333 			pp->fastreuse = 0;
7334 	} else if (pp->fastreuse &&
7335 		(!sk->sk_reuse || sk->sk_state == SCTP_SS_LISTENING))
7336 		pp->fastreuse = 0;
7337 
7338 	/* We are set, so fill up all the data in the hash table
7339 	 * entry, tie the socket list information with the rest of the
7340 	 * sockets FIXME: Blurry, NPI (ipg).
7341 	 */
7342 success:
7343 	if (!sctp_sk(sk)->bind_hash) {
7344 		inet_sk(sk)->inet_num = snum;
7345 		sk_add_bind_node(sk, &pp->owner);
7346 		sctp_sk(sk)->bind_hash = pp;
7347 	}
7348 	ret = 0;
7349 
7350 fail_unlock:
7351 	spin_unlock(&head->lock);
7352 
7353 fail:
7354 	local_bh_enable();
7355 	return ret;
7356 }
7357 
7358 /* Assign a 'snum' port to the socket.  If snum == 0, an ephemeral
7359  * port is requested.
7360  */
7361 static int sctp_get_port(struct sock *sk, unsigned short snum)
7362 {
7363 	union sctp_addr addr;
7364 	struct sctp_af *af = sctp_sk(sk)->pf->af;
7365 
7366 	/* Set up a dummy address struct from the sk. */
7367 	af->from_sk(&addr, sk);
7368 	addr.v4.sin_port = htons(snum);
7369 
7370 	/* Note: sk->sk_num gets filled in if ephemeral port request. */
7371 	return !!sctp_get_port_local(sk, &addr);
7372 }
7373 
7374 /*
7375  *  Move a socket to LISTENING state.
7376  */
7377 static int sctp_listen_start(struct sock *sk, int backlog)
7378 {
7379 	struct sctp_sock *sp = sctp_sk(sk);
7380 	struct sctp_endpoint *ep = sp->ep;
7381 	struct crypto_shash *tfm = NULL;
7382 	char alg[32];
7383 
7384 	/* Allocate HMAC for generating cookie. */
7385 	if (!sp->hmac && sp->sctp_hmac_alg) {
7386 		sprintf(alg, "hmac(%s)", sp->sctp_hmac_alg);
7387 		tfm = crypto_alloc_shash(alg, 0, 0);
7388 		if (IS_ERR(tfm)) {
7389 			net_info_ratelimited("failed to load transform for %s: %ld\n",
7390 					     sp->sctp_hmac_alg, PTR_ERR(tfm));
7391 			return -ENOSYS;
7392 		}
7393 		sctp_sk(sk)->hmac = tfm;
7394 	}
7395 
7396 	/*
7397 	 * If a bind() or sctp_bindx() is not called prior to a listen()
7398 	 * call that allows new associations to be accepted, the system
7399 	 * picks an ephemeral port and will choose an address set equivalent
7400 	 * to binding with a wildcard address.
7401 	 *
7402 	 * This is not currently spelled out in the SCTP sockets
7403 	 * extensions draft, but follows the practice as seen in TCP
7404 	 * sockets.
7405 	 *
7406 	 */
7407 	sk->sk_state = SCTP_SS_LISTENING;
7408 	if (!ep->base.bind_addr.port) {
7409 		if (sctp_autobind(sk))
7410 			return -EAGAIN;
7411 	} else {
7412 		if (sctp_get_port(sk, inet_sk(sk)->inet_num)) {
7413 			sk->sk_state = SCTP_SS_CLOSED;
7414 			return -EADDRINUSE;
7415 		}
7416 	}
7417 
7418 	sk->sk_max_ack_backlog = backlog;
7419 	sctp_hash_endpoint(ep);
7420 	return 0;
7421 }
7422 
7423 /*
7424  * 4.1.3 / 5.1.3 listen()
7425  *
7426  *   By default, new associations are not accepted for UDP style sockets.
7427  *   An application uses listen() to mark a socket as being able to
7428  *   accept new associations.
7429  *
7430  *   On TCP style sockets, applications use listen() to ready the SCTP
7431  *   endpoint for accepting inbound associations.
7432  *
7433  *   On both types of endpoints a backlog of '0' disables listening.
7434  *
7435  *  Move a socket to LISTENING state.
7436  */
7437 int sctp_inet_listen(struct socket *sock, int backlog)
7438 {
7439 	struct sock *sk = sock->sk;
7440 	struct sctp_endpoint *ep = sctp_sk(sk)->ep;
7441 	int err = -EINVAL;
7442 
7443 	if (unlikely(backlog < 0))
7444 		return err;
7445 
7446 	lock_sock(sk);
7447 
7448 	/* Peeled-off sockets are not allowed to listen().  */
7449 	if (sctp_style(sk, UDP_HIGH_BANDWIDTH))
7450 		goto out;
7451 
7452 	if (sock->state != SS_UNCONNECTED)
7453 		goto out;
7454 
7455 	if (!sctp_sstate(sk, LISTENING) && !sctp_sstate(sk, CLOSED))
7456 		goto out;
7457 
7458 	/* If backlog is zero, disable listening. */
7459 	if (!backlog) {
7460 		if (sctp_sstate(sk, CLOSED))
7461 			goto out;
7462 
7463 		err = 0;
7464 		sctp_unhash_endpoint(ep);
7465 		sk->sk_state = SCTP_SS_CLOSED;
7466 		if (sk->sk_reuse)
7467 			sctp_sk(sk)->bind_hash->fastreuse = 1;
7468 		goto out;
7469 	}
7470 
7471 	/* If we are already listening, just update the backlog */
7472 	if (sctp_sstate(sk, LISTENING))
7473 		sk->sk_max_ack_backlog = backlog;
7474 	else {
7475 		err = sctp_listen_start(sk, backlog);
7476 		if (err)
7477 			goto out;
7478 	}
7479 
7480 	err = 0;
7481 out:
7482 	release_sock(sk);
7483 	return err;
7484 }
7485 
7486 /*
7487  * This function is done by modeling the current datagram_poll() and the
7488  * tcp_poll().  Note that, based on these implementations, we don't
7489  * lock the socket in this function, even though it seems that,
7490  * ideally, locking or some other mechanisms can be used to ensure
7491  * the integrity of the counters (sndbuf and wmem_alloc) used
7492  * in this place.  We assume that we don't need locks either until proven
7493  * otherwise.
7494  *
7495  * Another thing to note is that we include the Async I/O support
7496  * here, again, by modeling the current TCP/UDP code.  We don't have
7497  * a good way to test with it yet.
7498  */
7499 unsigned int sctp_poll(struct file *file, struct socket *sock, poll_table *wait)
7500 {
7501 	struct sock *sk = sock->sk;
7502 	struct sctp_sock *sp = sctp_sk(sk);
7503 	unsigned int mask;
7504 
7505 	poll_wait(file, sk_sleep(sk), wait);
7506 
7507 	sock_rps_record_flow(sk);
7508 
7509 	/* A TCP-style listening socket becomes readable when the accept queue
7510 	 * is not empty.
7511 	 */
7512 	if (sctp_style(sk, TCP) && sctp_sstate(sk, LISTENING))
7513 		return (!list_empty(&sp->ep->asocs)) ?
7514 			(POLLIN | POLLRDNORM) : 0;
7515 
7516 	mask = 0;
7517 
7518 	/* Is there any exceptional events?  */
7519 	if (sk->sk_err || !skb_queue_empty(&sk->sk_error_queue))
7520 		mask |= POLLERR |
7521 			(sock_flag(sk, SOCK_SELECT_ERR_QUEUE) ? POLLPRI : 0);
7522 	if (sk->sk_shutdown & RCV_SHUTDOWN)
7523 		mask |= POLLRDHUP | POLLIN | POLLRDNORM;
7524 	if (sk->sk_shutdown == SHUTDOWN_MASK)
7525 		mask |= POLLHUP;
7526 
7527 	/* Is it readable?  Reconsider this code with TCP-style support.  */
7528 	if (!skb_queue_empty(&sk->sk_receive_queue))
7529 		mask |= POLLIN | POLLRDNORM;
7530 
7531 	/* The association is either gone or not ready.  */
7532 	if (!sctp_style(sk, UDP) && sctp_sstate(sk, CLOSED))
7533 		return mask;
7534 
7535 	/* Is it writable?  */
7536 	if (sctp_writeable(sk)) {
7537 		mask |= POLLOUT | POLLWRNORM;
7538 	} else {
7539 		sk_set_bit(SOCKWQ_ASYNC_NOSPACE, sk);
7540 		/*
7541 		 * Since the socket is not locked, the buffer
7542 		 * might be made available after the writeable check and
7543 		 * before the bit is set.  This could cause a lost I/O
7544 		 * signal.  tcp_poll() has a race breaker for this race
7545 		 * condition.  Based on their implementation, we put
7546 		 * in the following code to cover it as well.
7547 		 */
7548 		if (sctp_writeable(sk))
7549 			mask |= POLLOUT | POLLWRNORM;
7550 	}
7551 	return mask;
7552 }
7553 
7554 /********************************************************************
7555  * 2nd Level Abstractions
7556  ********************************************************************/
7557 
7558 static struct sctp_bind_bucket *sctp_bucket_create(
7559 	struct sctp_bind_hashbucket *head, struct net *net, unsigned short snum)
7560 {
7561 	struct sctp_bind_bucket *pp;
7562 
7563 	pp = kmem_cache_alloc(sctp_bucket_cachep, GFP_ATOMIC);
7564 	if (pp) {
7565 		SCTP_DBG_OBJCNT_INC(bind_bucket);
7566 		pp->port = snum;
7567 		pp->fastreuse = 0;
7568 		INIT_HLIST_HEAD(&pp->owner);
7569 		pp->net = net;
7570 		hlist_add_head(&pp->node, &head->chain);
7571 	}
7572 	return pp;
7573 }
7574 
7575 /* Caller must hold hashbucket lock for this tb with local BH disabled */
7576 static void sctp_bucket_destroy(struct sctp_bind_bucket *pp)
7577 {
7578 	if (pp && hlist_empty(&pp->owner)) {
7579 		__hlist_del(&pp->node);
7580 		kmem_cache_free(sctp_bucket_cachep, pp);
7581 		SCTP_DBG_OBJCNT_DEC(bind_bucket);
7582 	}
7583 }
7584 
7585 /* Release this socket's reference to a local port.  */
7586 static inline void __sctp_put_port(struct sock *sk)
7587 {
7588 	struct sctp_bind_hashbucket *head =
7589 		&sctp_port_hashtable[sctp_phashfn(sock_net(sk),
7590 						  inet_sk(sk)->inet_num)];
7591 	struct sctp_bind_bucket *pp;
7592 
7593 	spin_lock(&head->lock);
7594 	pp = sctp_sk(sk)->bind_hash;
7595 	__sk_del_bind_node(sk);
7596 	sctp_sk(sk)->bind_hash = NULL;
7597 	inet_sk(sk)->inet_num = 0;
7598 	sctp_bucket_destroy(pp);
7599 	spin_unlock(&head->lock);
7600 }
7601 
7602 void sctp_put_port(struct sock *sk)
7603 {
7604 	local_bh_disable();
7605 	__sctp_put_port(sk);
7606 	local_bh_enable();
7607 }
7608 
7609 /*
7610  * The system picks an ephemeral port and choose an address set equivalent
7611  * to binding with a wildcard address.
7612  * One of those addresses will be the primary address for the association.
7613  * This automatically enables the multihoming capability of SCTP.
7614  */
7615 static int sctp_autobind(struct sock *sk)
7616 {
7617 	union sctp_addr autoaddr;
7618 	struct sctp_af *af;
7619 	__be16 port;
7620 
7621 	/* Initialize a local sockaddr structure to INADDR_ANY. */
7622 	af = sctp_sk(sk)->pf->af;
7623 
7624 	port = htons(inet_sk(sk)->inet_num);
7625 	af->inaddr_any(&autoaddr, port);
7626 
7627 	return sctp_do_bind(sk, &autoaddr, af->sockaddr_len);
7628 }
7629 
7630 /* Parse out IPPROTO_SCTP CMSG headers.  Perform only minimal validation.
7631  *
7632  * From RFC 2292
7633  * 4.2 The cmsghdr Structure *
7634  *
7635  * When ancillary data is sent or received, any number of ancillary data
7636  * objects can be specified by the msg_control and msg_controllen members of
7637  * the msghdr structure, because each object is preceded by
7638  * a cmsghdr structure defining the object's length (the cmsg_len member).
7639  * Historically Berkeley-derived implementations have passed only one object
7640  * at a time, but this API allows multiple objects to be
7641  * passed in a single call to sendmsg() or recvmsg(). The following example
7642  * shows two ancillary data objects in a control buffer.
7643  *
7644  *   |<--------------------------- msg_controllen -------------------------->|
7645  *   |                                                                       |
7646  *
7647  *   |<----- ancillary data object ----->|<----- ancillary data object ----->|
7648  *
7649  *   |<---------- CMSG_SPACE() --------->|<---------- CMSG_SPACE() --------->|
7650  *   |                                   |                                   |
7651  *
7652  *   |<---------- cmsg_len ---------->|  |<--------- cmsg_len ----------->|  |
7653  *
7654  *   |<--------- CMSG_LEN() --------->|  |<-------- CMSG_LEN() ---------->|  |
7655  *   |                                |  |                                |  |
7656  *
7657  *   +-----+-----+-----+--+-----------+--+-----+-----+-----+--+-----------+--+
7658  *   |cmsg_|cmsg_|cmsg_|XX|           |XX|cmsg_|cmsg_|cmsg_|XX|           |XX|
7659  *
7660  *   |len  |level|type |XX|cmsg_data[]|XX|len  |level|type |XX|cmsg_data[]|XX|
7661  *
7662  *   +-----+-----+-----+--+-----------+--+-----+-----+-----+--+-----------+--+
7663  *    ^
7664  *    |
7665  *
7666  * msg_control
7667  * points here
7668  */
7669 static int sctp_msghdr_parse(const struct msghdr *msg, struct sctp_cmsgs *cmsgs)
7670 {
7671 	struct msghdr *my_msg = (struct msghdr *)msg;
7672 	struct cmsghdr *cmsg;
7673 
7674 	for_each_cmsghdr(cmsg, my_msg) {
7675 		if (!CMSG_OK(my_msg, cmsg))
7676 			return -EINVAL;
7677 
7678 		/* Should we parse this header or ignore?  */
7679 		if (cmsg->cmsg_level != IPPROTO_SCTP)
7680 			continue;
7681 
7682 		/* Strictly check lengths following example in SCM code.  */
7683 		switch (cmsg->cmsg_type) {
7684 		case SCTP_INIT:
7685 			/* SCTP Socket API Extension
7686 			 * 5.3.1 SCTP Initiation Structure (SCTP_INIT)
7687 			 *
7688 			 * This cmsghdr structure provides information for
7689 			 * initializing new SCTP associations with sendmsg().
7690 			 * The SCTP_INITMSG socket option uses this same data
7691 			 * structure.  This structure is not used for
7692 			 * recvmsg().
7693 			 *
7694 			 * cmsg_level    cmsg_type      cmsg_data[]
7695 			 * ------------  ------------   ----------------------
7696 			 * IPPROTO_SCTP  SCTP_INIT      struct sctp_initmsg
7697 			 */
7698 			if (cmsg->cmsg_len != CMSG_LEN(sizeof(struct sctp_initmsg)))
7699 				return -EINVAL;
7700 
7701 			cmsgs->init = CMSG_DATA(cmsg);
7702 			break;
7703 
7704 		case SCTP_SNDRCV:
7705 			/* SCTP Socket API Extension
7706 			 * 5.3.2 SCTP Header Information Structure(SCTP_SNDRCV)
7707 			 *
7708 			 * This cmsghdr structure specifies SCTP options for
7709 			 * sendmsg() and describes SCTP header information
7710 			 * about a received message through recvmsg().
7711 			 *
7712 			 * cmsg_level    cmsg_type      cmsg_data[]
7713 			 * ------------  ------------   ----------------------
7714 			 * IPPROTO_SCTP  SCTP_SNDRCV    struct sctp_sndrcvinfo
7715 			 */
7716 			if (cmsg->cmsg_len != CMSG_LEN(sizeof(struct sctp_sndrcvinfo)))
7717 				return -EINVAL;
7718 
7719 			cmsgs->srinfo = CMSG_DATA(cmsg);
7720 
7721 			if (cmsgs->srinfo->sinfo_flags &
7722 			    ~(SCTP_UNORDERED | SCTP_ADDR_OVER |
7723 			      SCTP_SACK_IMMEDIATELY | SCTP_PR_SCTP_MASK |
7724 			      SCTP_ABORT | SCTP_EOF))
7725 				return -EINVAL;
7726 			break;
7727 
7728 		case SCTP_SNDINFO:
7729 			/* SCTP Socket API Extension
7730 			 * 5.3.4 SCTP Send Information Structure (SCTP_SNDINFO)
7731 			 *
7732 			 * This cmsghdr structure specifies SCTP options for
7733 			 * sendmsg(). This structure and SCTP_RCVINFO replaces
7734 			 * SCTP_SNDRCV which has been deprecated.
7735 			 *
7736 			 * cmsg_level    cmsg_type      cmsg_data[]
7737 			 * ------------  ------------   ---------------------
7738 			 * IPPROTO_SCTP  SCTP_SNDINFO    struct sctp_sndinfo
7739 			 */
7740 			if (cmsg->cmsg_len != CMSG_LEN(sizeof(struct sctp_sndinfo)))
7741 				return -EINVAL;
7742 
7743 			cmsgs->sinfo = CMSG_DATA(cmsg);
7744 
7745 			if (cmsgs->sinfo->snd_flags &
7746 			    ~(SCTP_UNORDERED | SCTP_ADDR_OVER |
7747 			      SCTP_SACK_IMMEDIATELY | SCTP_PR_SCTP_MASK |
7748 			      SCTP_ABORT | SCTP_EOF))
7749 				return -EINVAL;
7750 			break;
7751 		default:
7752 			return -EINVAL;
7753 		}
7754 	}
7755 
7756 	return 0;
7757 }
7758 
7759 /*
7760  * Wait for a packet..
7761  * Note: This function is the same function as in core/datagram.c
7762  * with a few modifications to make lksctp work.
7763  */
7764 static int sctp_wait_for_packet(struct sock *sk, int *err, long *timeo_p)
7765 {
7766 	int error;
7767 	DEFINE_WAIT(wait);
7768 
7769 	prepare_to_wait_exclusive(sk_sleep(sk), &wait, TASK_INTERRUPTIBLE);
7770 
7771 	/* Socket errors? */
7772 	error = sock_error(sk);
7773 	if (error)
7774 		goto out;
7775 
7776 	if (!skb_queue_empty(&sk->sk_receive_queue))
7777 		goto ready;
7778 
7779 	/* Socket shut down?  */
7780 	if (sk->sk_shutdown & RCV_SHUTDOWN)
7781 		goto out;
7782 
7783 	/* Sequenced packets can come disconnected.  If so we report the
7784 	 * problem.
7785 	 */
7786 	error = -ENOTCONN;
7787 
7788 	/* Is there a good reason to think that we may receive some data?  */
7789 	if (list_empty(&sctp_sk(sk)->ep->asocs) && !sctp_sstate(sk, LISTENING))
7790 		goto out;
7791 
7792 	/* Handle signals.  */
7793 	if (signal_pending(current))
7794 		goto interrupted;
7795 
7796 	/* Let another process have a go.  Since we are going to sleep
7797 	 * anyway.  Note: This may cause odd behaviors if the message
7798 	 * does not fit in the user's buffer, but this seems to be the
7799 	 * only way to honor MSG_DONTWAIT realistically.
7800 	 */
7801 	release_sock(sk);
7802 	*timeo_p = schedule_timeout(*timeo_p);
7803 	lock_sock(sk);
7804 
7805 ready:
7806 	finish_wait(sk_sleep(sk), &wait);
7807 	return 0;
7808 
7809 interrupted:
7810 	error = sock_intr_errno(*timeo_p);
7811 
7812 out:
7813 	finish_wait(sk_sleep(sk), &wait);
7814 	*err = error;
7815 	return error;
7816 }
7817 
7818 /* Receive a datagram.
7819  * Note: This is pretty much the same routine as in core/datagram.c
7820  * with a few changes to make lksctp work.
7821  */
7822 struct sk_buff *sctp_skb_recv_datagram(struct sock *sk, int flags,
7823 				       int noblock, int *err)
7824 {
7825 	int error;
7826 	struct sk_buff *skb;
7827 	long timeo;
7828 
7829 	timeo = sock_rcvtimeo(sk, noblock);
7830 
7831 	pr_debug("%s: timeo:%ld, max:%ld\n", __func__, timeo,
7832 		 MAX_SCHEDULE_TIMEOUT);
7833 
7834 	do {
7835 		/* Again only user level code calls this function,
7836 		 * so nothing interrupt level
7837 		 * will suddenly eat the receive_queue.
7838 		 *
7839 		 *  Look at current nfs client by the way...
7840 		 *  However, this function was correct in any case. 8)
7841 		 */
7842 		if (flags & MSG_PEEK) {
7843 			skb = skb_peek(&sk->sk_receive_queue);
7844 			if (skb)
7845 				refcount_inc(&skb->users);
7846 		} else {
7847 			skb = __skb_dequeue(&sk->sk_receive_queue);
7848 		}
7849 
7850 		if (skb)
7851 			return skb;
7852 
7853 		/* Caller is allowed not to check sk->sk_err before calling. */
7854 		error = sock_error(sk);
7855 		if (error)
7856 			goto no_packet;
7857 
7858 		if (sk->sk_shutdown & RCV_SHUTDOWN)
7859 			break;
7860 
7861 		if (sk_can_busy_loop(sk)) {
7862 			sk_busy_loop(sk, noblock);
7863 
7864 			if (!skb_queue_empty(&sk->sk_receive_queue))
7865 				continue;
7866 		}
7867 
7868 		/* User doesn't want to wait.  */
7869 		error = -EAGAIN;
7870 		if (!timeo)
7871 			goto no_packet;
7872 	} while (sctp_wait_for_packet(sk, err, &timeo) == 0);
7873 
7874 	return NULL;
7875 
7876 no_packet:
7877 	*err = error;
7878 	return NULL;
7879 }
7880 
7881 /* If sndbuf has changed, wake up per association sndbuf waiters.  */
7882 static void __sctp_write_space(struct sctp_association *asoc)
7883 {
7884 	struct sock *sk = asoc->base.sk;
7885 
7886 	if (sctp_wspace(asoc) <= 0)
7887 		return;
7888 
7889 	if (waitqueue_active(&asoc->wait))
7890 		wake_up_interruptible(&asoc->wait);
7891 
7892 	if (sctp_writeable(sk)) {
7893 		struct socket_wq *wq;
7894 
7895 		rcu_read_lock();
7896 		wq = rcu_dereference(sk->sk_wq);
7897 		if (wq) {
7898 			if (waitqueue_active(&wq->wait))
7899 				wake_up_interruptible(&wq->wait);
7900 
7901 			/* Note that we try to include the Async I/O support
7902 			 * here by modeling from the current TCP/UDP code.
7903 			 * We have not tested with it yet.
7904 			 */
7905 			if (!(sk->sk_shutdown & SEND_SHUTDOWN))
7906 				sock_wake_async(wq, SOCK_WAKE_SPACE, POLL_OUT);
7907 		}
7908 		rcu_read_unlock();
7909 	}
7910 }
7911 
7912 static void sctp_wake_up_waiters(struct sock *sk,
7913 				 struct sctp_association *asoc)
7914 {
7915 	struct sctp_association *tmp = asoc;
7916 
7917 	/* We do accounting for the sndbuf space per association,
7918 	 * so we only need to wake our own association.
7919 	 */
7920 	if (asoc->ep->sndbuf_policy)
7921 		return __sctp_write_space(asoc);
7922 
7923 	/* If association goes down and is just flushing its
7924 	 * outq, then just normally notify others.
7925 	 */
7926 	if (asoc->base.dead)
7927 		return sctp_write_space(sk);
7928 
7929 	/* Accounting for the sndbuf space is per socket, so we
7930 	 * need to wake up others, try to be fair and in case of
7931 	 * other associations, let them have a go first instead
7932 	 * of just doing a sctp_write_space() call.
7933 	 *
7934 	 * Note that we reach sctp_wake_up_waiters() only when
7935 	 * associations free up queued chunks, thus we are under
7936 	 * lock and the list of associations on a socket is
7937 	 * guaranteed not to change.
7938 	 */
7939 	for (tmp = list_next_entry(tmp, asocs); 1;
7940 	     tmp = list_next_entry(tmp, asocs)) {
7941 		/* Manually skip the head element. */
7942 		if (&tmp->asocs == &((sctp_sk(sk))->ep->asocs))
7943 			continue;
7944 		/* Wake up association. */
7945 		__sctp_write_space(tmp);
7946 		/* We've reached the end. */
7947 		if (tmp == asoc)
7948 			break;
7949 	}
7950 }
7951 
7952 /* Do accounting for the sndbuf space.
7953  * Decrement the used sndbuf space of the corresponding association by the
7954  * data size which was just transmitted(freed).
7955  */
7956 static void sctp_wfree(struct sk_buff *skb)
7957 {
7958 	struct sctp_chunk *chunk = skb_shinfo(skb)->destructor_arg;
7959 	struct sctp_association *asoc = chunk->asoc;
7960 	struct sock *sk = asoc->base.sk;
7961 
7962 	asoc->sndbuf_used -= SCTP_DATA_SNDSIZE(chunk) +
7963 				sizeof(struct sk_buff) +
7964 				sizeof(struct sctp_chunk);
7965 
7966 	WARN_ON(refcount_sub_and_test(sizeof(struct sctp_chunk), &sk->sk_wmem_alloc));
7967 
7968 	/*
7969 	 * This undoes what is done via sctp_set_owner_w and sk_mem_charge
7970 	 */
7971 	sk->sk_wmem_queued   -= skb->truesize;
7972 	sk_mem_uncharge(sk, skb->truesize);
7973 
7974 	sock_wfree(skb);
7975 	sctp_wake_up_waiters(sk, asoc);
7976 
7977 	sctp_association_put(asoc);
7978 }
7979 
7980 /* Do accounting for the receive space on the socket.
7981  * Accounting for the association is done in ulpevent.c
7982  * We set this as a destructor for the cloned data skbs so that
7983  * accounting is done at the correct time.
7984  */
7985 void sctp_sock_rfree(struct sk_buff *skb)
7986 {
7987 	struct sock *sk = skb->sk;
7988 	struct sctp_ulpevent *event = sctp_skb2event(skb);
7989 
7990 	atomic_sub(event->rmem_len, &sk->sk_rmem_alloc);
7991 
7992 	/*
7993 	 * Mimic the behavior of sock_rfree
7994 	 */
7995 	sk_mem_uncharge(sk, event->rmem_len);
7996 }
7997 
7998 
7999 /* Helper function to wait for space in the sndbuf.  */
8000 static int sctp_wait_for_sndbuf(struct sctp_association *asoc, long *timeo_p,
8001 				size_t msg_len, struct sock **orig_sk)
8002 {
8003 	struct sock *sk = asoc->base.sk;
8004 	int err = 0;
8005 	long current_timeo = *timeo_p;
8006 	DEFINE_WAIT(wait);
8007 
8008 	pr_debug("%s: asoc:%p, timeo:%ld, msg_len:%zu\n", __func__, asoc,
8009 		 *timeo_p, msg_len);
8010 
8011 	/* Increment the association's refcnt.  */
8012 	sctp_association_hold(asoc);
8013 
8014 	/* Wait on the association specific sndbuf space. */
8015 	for (;;) {
8016 		prepare_to_wait_exclusive(&asoc->wait, &wait,
8017 					  TASK_INTERRUPTIBLE);
8018 		if (asoc->base.dead)
8019 			goto do_dead;
8020 		if (!*timeo_p)
8021 			goto do_nonblock;
8022 		if (sk->sk_err || asoc->state >= SCTP_STATE_SHUTDOWN_PENDING)
8023 			goto do_error;
8024 		if (signal_pending(current))
8025 			goto do_interrupted;
8026 		if (msg_len <= sctp_wspace(asoc))
8027 			break;
8028 
8029 		/* Let another process have a go.  Since we are going
8030 		 * to sleep anyway.
8031 		 */
8032 		release_sock(sk);
8033 		current_timeo = schedule_timeout(current_timeo);
8034 		lock_sock(sk);
8035 		if (sk != asoc->base.sk) {
8036 			release_sock(sk);
8037 			sk = asoc->base.sk;
8038 			lock_sock(sk);
8039 		}
8040 
8041 		*timeo_p = current_timeo;
8042 	}
8043 
8044 out:
8045 	*orig_sk = sk;
8046 	finish_wait(&asoc->wait, &wait);
8047 
8048 	/* Release the association's refcnt.  */
8049 	sctp_association_put(asoc);
8050 
8051 	return err;
8052 
8053 do_dead:
8054 	err = -ESRCH;
8055 	goto out;
8056 
8057 do_error:
8058 	err = -EPIPE;
8059 	goto out;
8060 
8061 do_interrupted:
8062 	err = sock_intr_errno(*timeo_p);
8063 	goto out;
8064 
8065 do_nonblock:
8066 	err = -EAGAIN;
8067 	goto out;
8068 }
8069 
8070 void sctp_data_ready(struct sock *sk)
8071 {
8072 	struct socket_wq *wq;
8073 
8074 	rcu_read_lock();
8075 	wq = rcu_dereference(sk->sk_wq);
8076 	if (skwq_has_sleeper(wq))
8077 		wake_up_interruptible_sync_poll(&wq->wait, POLLIN |
8078 						POLLRDNORM | POLLRDBAND);
8079 	sk_wake_async(sk, SOCK_WAKE_WAITD, POLL_IN);
8080 	rcu_read_unlock();
8081 }
8082 
8083 /* If socket sndbuf has changed, wake up all per association waiters.  */
8084 void sctp_write_space(struct sock *sk)
8085 {
8086 	struct sctp_association *asoc;
8087 
8088 	/* Wake up the tasks in each wait queue.  */
8089 	list_for_each_entry(asoc, &((sctp_sk(sk))->ep->asocs), asocs) {
8090 		__sctp_write_space(asoc);
8091 	}
8092 }
8093 
8094 /* Is there any sndbuf space available on the socket?
8095  *
8096  * Note that sk_wmem_alloc is the sum of the send buffers on all of the
8097  * associations on the same socket.  For a UDP-style socket with
8098  * multiple associations, it is possible for it to be "unwriteable"
8099  * prematurely.  I assume that this is acceptable because
8100  * a premature "unwriteable" is better than an accidental "writeable" which
8101  * would cause an unwanted block under certain circumstances.  For the 1-1
8102  * UDP-style sockets or TCP-style sockets, this code should work.
8103  *  - Daisy
8104  */
8105 static int sctp_writeable(struct sock *sk)
8106 {
8107 	int amt = 0;
8108 
8109 	amt = sk->sk_sndbuf - sk_wmem_alloc_get(sk);
8110 	if (amt < 0)
8111 		amt = 0;
8112 	return amt;
8113 }
8114 
8115 /* Wait for an association to go into ESTABLISHED state. If timeout is 0,
8116  * returns immediately with EINPROGRESS.
8117  */
8118 static int sctp_wait_for_connect(struct sctp_association *asoc, long *timeo_p)
8119 {
8120 	struct sock *sk = asoc->base.sk;
8121 	int err = 0;
8122 	long current_timeo = *timeo_p;
8123 	DEFINE_WAIT(wait);
8124 
8125 	pr_debug("%s: asoc:%p, timeo:%ld\n", __func__, asoc, *timeo_p);
8126 
8127 	/* Increment the association's refcnt.  */
8128 	sctp_association_hold(asoc);
8129 
8130 	for (;;) {
8131 		prepare_to_wait_exclusive(&asoc->wait, &wait,
8132 					  TASK_INTERRUPTIBLE);
8133 		if (!*timeo_p)
8134 			goto do_nonblock;
8135 		if (sk->sk_shutdown & RCV_SHUTDOWN)
8136 			break;
8137 		if (sk->sk_err || asoc->state >= SCTP_STATE_SHUTDOWN_PENDING ||
8138 		    asoc->base.dead)
8139 			goto do_error;
8140 		if (signal_pending(current))
8141 			goto do_interrupted;
8142 
8143 		if (sctp_state(asoc, ESTABLISHED))
8144 			break;
8145 
8146 		/* Let another process have a go.  Since we are going
8147 		 * to sleep anyway.
8148 		 */
8149 		release_sock(sk);
8150 		current_timeo = schedule_timeout(current_timeo);
8151 		lock_sock(sk);
8152 
8153 		*timeo_p = current_timeo;
8154 	}
8155 
8156 out:
8157 	finish_wait(&asoc->wait, &wait);
8158 
8159 	/* Release the association's refcnt.  */
8160 	sctp_association_put(asoc);
8161 
8162 	return err;
8163 
8164 do_error:
8165 	if (asoc->init_err_counter + 1 > asoc->max_init_attempts)
8166 		err = -ETIMEDOUT;
8167 	else
8168 		err = -ECONNREFUSED;
8169 	goto out;
8170 
8171 do_interrupted:
8172 	err = sock_intr_errno(*timeo_p);
8173 	goto out;
8174 
8175 do_nonblock:
8176 	err = -EINPROGRESS;
8177 	goto out;
8178 }
8179 
8180 static int sctp_wait_for_accept(struct sock *sk, long timeo)
8181 {
8182 	struct sctp_endpoint *ep;
8183 	int err = 0;
8184 	DEFINE_WAIT(wait);
8185 
8186 	ep = sctp_sk(sk)->ep;
8187 
8188 
8189 	for (;;) {
8190 		prepare_to_wait_exclusive(sk_sleep(sk), &wait,
8191 					  TASK_INTERRUPTIBLE);
8192 
8193 		if (list_empty(&ep->asocs)) {
8194 			release_sock(sk);
8195 			timeo = schedule_timeout(timeo);
8196 			lock_sock(sk);
8197 		}
8198 
8199 		err = -EINVAL;
8200 		if (!sctp_sstate(sk, LISTENING))
8201 			break;
8202 
8203 		err = 0;
8204 		if (!list_empty(&ep->asocs))
8205 			break;
8206 
8207 		err = sock_intr_errno(timeo);
8208 		if (signal_pending(current))
8209 			break;
8210 
8211 		err = -EAGAIN;
8212 		if (!timeo)
8213 			break;
8214 	}
8215 
8216 	finish_wait(sk_sleep(sk), &wait);
8217 
8218 	return err;
8219 }
8220 
8221 static void sctp_wait_for_close(struct sock *sk, long timeout)
8222 {
8223 	DEFINE_WAIT(wait);
8224 
8225 	do {
8226 		prepare_to_wait(sk_sleep(sk), &wait, TASK_INTERRUPTIBLE);
8227 		if (list_empty(&sctp_sk(sk)->ep->asocs))
8228 			break;
8229 		release_sock(sk);
8230 		timeout = schedule_timeout(timeout);
8231 		lock_sock(sk);
8232 	} while (!signal_pending(current) && timeout);
8233 
8234 	finish_wait(sk_sleep(sk), &wait);
8235 }
8236 
8237 static void sctp_skb_set_owner_r_frag(struct sk_buff *skb, struct sock *sk)
8238 {
8239 	struct sk_buff *frag;
8240 
8241 	if (!skb->data_len)
8242 		goto done;
8243 
8244 	/* Don't forget the fragments. */
8245 	skb_walk_frags(skb, frag)
8246 		sctp_skb_set_owner_r_frag(frag, sk);
8247 
8248 done:
8249 	sctp_skb_set_owner_r(skb, sk);
8250 }
8251 
8252 void sctp_copy_sock(struct sock *newsk, struct sock *sk,
8253 		    struct sctp_association *asoc)
8254 {
8255 	struct inet_sock *inet = inet_sk(sk);
8256 	struct inet_sock *newinet;
8257 
8258 	newsk->sk_type = sk->sk_type;
8259 	newsk->sk_bound_dev_if = sk->sk_bound_dev_if;
8260 	newsk->sk_flags = sk->sk_flags;
8261 	newsk->sk_tsflags = sk->sk_tsflags;
8262 	newsk->sk_no_check_tx = sk->sk_no_check_tx;
8263 	newsk->sk_no_check_rx = sk->sk_no_check_rx;
8264 	newsk->sk_reuse = sk->sk_reuse;
8265 
8266 	newsk->sk_shutdown = sk->sk_shutdown;
8267 	newsk->sk_destruct = sctp_destruct_sock;
8268 	newsk->sk_family = sk->sk_family;
8269 	newsk->sk_protocol = IPPROTO_SCTP;
8270 	newsk->sk_backlog_rcv = sk->sk_prot->backlog_rcv;
8271 	newsk->sk_sndbuf = sk->sk_sndbuf;
8272 	newsk->sk_rcvbuf = sk->sk_rcvbuf;
8273 	newsk->sk_lingertime = sk->sk_lingertime;
8274 	newsk->sk_rcvtimeo = sk->sk_rcvtimeo;
8275 	newsk->sk_sndtimeo = sk->sk_sndtimeo;
8276 	newsk->sk_rxhash = sk->sk_rxhash;
8277 
8278 	newinet = inet_sk(newsk);
8279 
8280 	/* Initialize sk's sport, dport, rcv_saddr and daddr for
8281 	 * getsockname() and getpeername()
8282 	 */
8283 	newinet->inet_sport = inet->inet_sport;
8284 	newinet->inet_saddr = inet->inet_saddr;
8285 	newinet->inet_rcv_saddr = inet->inet_rcv_saddr;
8286 	newinet->inet_dport = htons(asoc->peer.port);
8287 	newinet->pmtudisc = inet->pmtudisc;
8288 	newinet->inet_id = asoc->next_tsn ^ jiffies;
8289 
8290 	newinet->uc_ttl = inet->uc_ttl;
8291 	newinet->mc_loop = 1;
8292 	newinet->mc_ttl = 1;
8293 	newinet->mc_index = 0;
8294 	newinet->mc_list = NULL;
8295 
8296 	if (newsk->sk_flags & SK_FLAGS_TIMESTAMP)
8297 		net_enable_timestamp();
8298 
8299 	security_sk_clone(sk, newsk);
8300 }
8301 
8302 static inline void sctp_copy_descendant(struct sock *sk_to,
8303 					const struct sock *sk_from)
8304 {
8305 	int ancestor_size = sizeof(struct inet_sock) +
8306 			    sizeof(struct sctp_sock) -
8307 			    offsetof(struct sctp_sock, auto_asconf_list);
8308 
8309 	if (sk_from->sk_family == PF_INET6)
8310 		ancestor_size += sizeof(struct ipv6_pinfo);
8311 
8312 	__inet_sk_copy_descendant(sk_to, sk_from, ancestor_size);
8313 }
8314 
8315 /* Populate the fields of the newsk from the oldsk and migrate the assoc
8316  * and its messages to the newsk.
8317  */
8318 static void sctp_sock_migrate(struct sock *oldsk, struct sock *newsk,
8319 			      struct sctp_association *assoc,
8320 			      enum sctp_socket_type type)
8321 {
8322 	struct sctp_sock *oldsp = sctp_sk(oldsk);
8323 	struct sctp_sock *newsp = sctp_sk(newsk);
8324 	struct sctp_bind_bucket *pp; /* hash list port iterator */
8325 	struct sctp_endpoint *newep = newsp->ep;
8326 	struct sk_buff *skb, *tmp;
8327 	struct sctp_ulpevent *event;
8328 	struct sctp_bind_hashbucket *head;
8329 
8330 	/* Migrate socket buffer sizes and all the socket level options to the
8331 	 * new socket.
8332 	 */
8333 	newsk->sk_sndbuf = oldsk->sk_sndbuf;
8334 	newsk->sk_rcvbuf = oldsk->sk_rcvbuf;
8335 	/* Brute force copy old sctp opt. */
8336 	sctp_copy_descendant(newsk, oldsk);
8337 
8338 	/* Restore the ep value that was overwritten with the above structure
8339 	 * copy.
8340 	 */
8341 	newsp->ep = newep;
8342 	newsp->hmac = NULL;
8343 
8344 	/* Hook this new socket in to the bind_hash list. */
8345 	head = &sctp_port_hashtable[sctp_phashfn(sock_net(oldsk),
8346 						 inet_sk(oldsk)->inet_num)];
8347 	spin_lock_bh(&head->lock);
8348 	pp = sctp_sk(oldsk)->bind_hash;
8349 	sk_add_bind_node(newsk, &pp->owner);
8350 	sctp_sk(newsk)->bind_hash = pp;
8351 	inet_sk(newsk)->inet_num = inet_sk(oldsk)->inet_num;
8352 	spin_unlock_bh(&head->lock);
8353 
8354 	/* Copy the bind_addr list from the original endpoint to the new
8355 	 * endpoint so that we can handle restarts properly
8356 	 */
8357 	sctp_bind_addr_dup(&newsp->ep->base.bind_addr,
8358 				&oldsp->ep->base.bind_addr, GFP_KERNEL);
8359 
8360 	/* Move any messages in the old socket's receive queue that are for the
8361 	 * peeled off association to the new socket's receive queue.
8362 	 */
8363 	sctp_skb_for_each(skb, &oldsk->sk_receive_queue, tmp) {
8364 		event = sctp_skb2event(skb);
8365 		if (event->asoc == assoc) {
8366 			__skb_unlink(skb, &oldsk->sk_receive_queue);
8367 			__skb_queue_tail(&newsk->sk_receive_queue, skb);
8368 			sctp_skb_set_owner_r_frag(skb, newsk);
8369 		}
8370 	}
8371 
8372 	/* Clean up any messages pending delivery due to partial
8373 	 * delivery.   Three cases:
8374 	 * 1) No partial deliver;  no work.
8375 	 * 2) Peeling off partial delivery; keep pd_lobby in new pd_lobby.
8376 	 * 3) Peeling off non-partial delivery; move pd_lobby to receive_queue.
8377 	 */
8378 	skb_queue_head_init(&newsp->pd_lobby);
8379 	atomic_set(&sctp_sk(newsk)->pd_mode, assoc->ulpq.pd_mode);
8380 
8381 	if (atomic_read(&sctp_sk(oldsk)->pd_mode)) {
8382 		struct sk_buff_head *queue;
8383 
8384 		/* Decide which queue to move pd_lobby skbs to. */
8385 		if (assoc->ulpq.pd_mode) {
8386 			queue = &newsp->pd_lobby;
8387 		} else
8388 			queue = &newsk->sk_receive_queue;
8389 
8390 		/* Walk through the pd_lobby, looking for skbs that
8391 		 * need moved to the new socket.
8392 		 */
8393 		sctp_skb_for_each(skb, &oldsp->pd_lobby, tmp) {
8394 			event = sctp_skb2event(skb);
8395 			if (event->asoc == assoc) {
8396 				__skb_unlink(skb, &oldsp->pd_lobby);
8397 				__skb_queue_tail(queue, skb);
8398 				sctp_skb_set_owner_r_frag(skb, newsk);
8399 			}
8400 		}
8401 
8402 		/* Clear up any skbs waiting for the partial
8403 		 * delivery to finish.
8404 		 */
8405 		if (assoc->ulpq.pd_mode)
8406 			sctp_clear_pd(oldsk, NULL);
8407 
8408 	}
8409 
8410 	sctp_skb_for_each(skb, &assoc->ulpq.reasm, tmp)
8411 		sctp_skb_set_owner_r_frag(skb, newsk);
8412 
8413 	sctp_skb_for_each(skb, &assoc->ulpq.lobby, tmp)
8414 		sctp_skb_set_owner_r_frag(skb, newsk);
8415 
8416 	/* Set the type of socket to indicate that it is peeled off from the
8417 	 * original UDP-style socket or created with the accept() call on a
8418 	 * TCP-style socket..
8419 	 */
8420 	newsp->type = type;
8421 
8422 	/* Mark the new socket "in-use" by the user so that any packets
8423 	 * that may arrive on the association after we've moved it are
8424 	 * queued to the backlog.  This prevents a potential race between
8425 	 * backlog processing on the old socket and new-packet processing
8426 	 * on the new socket.
8427 	 *
8428 	 * The caller has just allocated newsk so we can guarantee that other
8429 	 * paths won't try to lock it and then oldsk.
8430 	 */
8431 	lock_sock_nested(newsk, SINGLE_DEPTH_NESTING);
8432 	sctp_for_each_tx_datachunk(assoc, sctp_clear_owner_w);
8433 	sctp_assoc_migrate(assoc, newsk);
8434 	sctp_for_each_tx_datachunk(assoc, sctp_set_owner_w);
8435 
8436 	/* If the association on the newsk is already closed before accept()
8437 	 * is called, set RCV_SHUTDOWN flag.
8438 	 */
8439 	if (sctp_state(assoc, CLOSED) && sctp_style(newsk, TCP)) {
8440 		newsk->sk_state = SCTP_SS_CLOSED;
8441 		newsk->sk_shutdown |= RCV_SHUTDOWN;
8442 	} else {
8443 		newsk->sk_state = SCTP_SS_ESTABLISHED;
8444 	}
8445 
8446 	release_sock(newsk);
8447 }
8448 
8449 
8450 /* This proto struct describes the ULP interface for SCTP.  */
8451 struct proto sctp_prot = {
8452 	.name        =	"SCTP",
8453 	.owner       =	THIS_MODULE,
8454 	.close       =	sctp_close,
8455 	.connect     =	sctp_connect,
8456 	.disconnect  =	sctp_disconnect,
8457 	.accept      =	sctp_accept,
8458 	.ioctl       =	sctp_ioctl,
8459 	.init        =	sctp_init_sock,
8460 	.destroy     =	sctp_destroy_sock,
8461 	.shutdown    =	sctp_shutdown,
8462 	.setsockopt  =	sctp_setsockopt,
8463 	.getsockopt  =	sctp_getsockopt,
8464 	.sendmsg     =	sctp_sendmsg,
8465 	.recvmsg     =	sctp_recvmsg,
8466 	.bind        =	sctp_bind,
8467 	.backlog_rcv =	sctp_backlog_rcv,
8468 	.hash        =	sctp_hash,
8469 	.unhash      =	sctp_unhash,
8470 	.get_port    =	sctp_get_port,
8471 	.obj_size    =  sizeof(struct sctp_sock),
8472 	.sysctl_mem  =  sysctl_sctp_mem,
8473 	.sysctl_rmem =  sysctl_sctp_rmem,
8474 	.sysctl_wmem =  sysctl_sctp_wmem,
8475 	.memory_pressure = &sctp_memory_pressure,
8476 	.enter_memory_pressure = sctp_enter_memory_pressure,
8477 	.memory_allocated = &sctp_memory_allocated,
8478 	.sockets_allocated = &sctp_sockets_allocated,
8479 };
8480 
8481 #if IS_ENABLED(CONFIG_IPV6)
8482 
8483 #include <net/transp_v6.h>
8484 static void sctp_v6_destroy_sock(struct sock *sk)
8485 {
8486 	sctp_destroy_sock(sk);
8487 	inet6_destroy_sock(sk);
8488 }
8489 
8490 struct proto sctpv6_prot = {
8491 	.name		= "SCTPv6",
8492 	.owner		= THIS_MODULE,
8493 	.close		= sctp_close,
8494 	.connect	= sctp_connect,
8495 	.disconnect	= sctp_disconnect,
8496 	.accept		= sctp_accept,
8497 	.ioctl		= sctp_ioctl,
8498 	.init		= sctp_init_sock,
8499 	.destroy	= sctp_v6_destroy_sock,
8500 	.shutdown	= sctp_shutdown,
8501 	.setsockopt	= sctp_setsockopt,
8502 	.getsockopt	= sctp_getsockopt,
8503 	.sendmsg	= sctp_sendmsg,
8504 	.recvmsg	= sctp_recvmsg,
8505 	.bind		= sctp_bind,
8506 	.backlog_rcv	= sctp_backlog_rcv,
8507 	.hash		= sctp_hash,
8508 	.unhash		= sctp_unhash,
8509 	.get_port	= sctp_get_port,
8510 	.obj_size	= sizeof(struct sctp6_sock),
8511 	.sysctl_mem	= sysctl_sctp_mem,
8512 	.sysctl_rmem	= sysctl_sctp_rmem,
8513 	.sysctl_wmem	= sysctl_sctp_wmem,
8514 	.memory_pressure = &sctp_memory_pressure,
8515 	.enter_memory_pressure = sctp_enter_memory_pressure,
8516 	.memory_allocated = &sctp_memory_allocated,
8517 	.sockets_allocated = &sctp_sockets_allocated,
8518 };
8519 #endif /* IS_ENABLED(CONFIG_IPV6) */
8520