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