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