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