sctp: add sockopt to get/set stream scheduler
[linux-2.6-microblaze.git] / net / sctp / socket.c
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 /* API 6.2 setsockopt(), getsockopt()
3949  *
3950  * Applications use setsockopt() and getsockopt() to set or retrieve
3951  * socket options.  Socket options are used to change the default
3952  * behavior of sockets calls.  They are described in Section 7.
3953  *
3954  * The syntax is:
3955  *
3956  *   ret = getsockopt(int sd, int level, int optname, void __user *optval,
3957  *                    int __user *optlen);
3958  *   ret = setsockopt(int sd, int level, int optname, const void __user *optval,
3959  *                    int optlen);
3960  *
3961  *   sd      - the socket descript.
3962  *   level   - set to IPPROTO_SCTP for all SCTP options.
3963  *   optname - the option name.
3964  *   optval  - the buffer to store the value of the option.
3965  *   optlen  - the size of the buffer.
3966  */
3967 static int sctp_setsockopt(struct sock *sk, int level, int optname,
3968                            char __user *optval, unsigned int optlen)
3969 {
3970         int retval = 0;
3971
3972         pr_debug("%s: sk:%p, optname:%d\n", __func__, sk, optname);
3973
3974         /* I can hardly begin to describe how wrong this is.  This is
3975          * so broken as to be worse than useless.  The API draft
3976          * REALLY is NOT helpful here...  I am not convinced that the
3977          * semantics of setsockopt() with a level OTHER THAN SOL_SCTP
3978          * are at all well-founded.
3979          */
3980         if (level != SOL_SCTP) {
3981                 struct sctp_af *af = sctp_sk(sk)->pf->af;
3982                 retval = af->setsockopt(sk, level, optname, optval, optlen);
3983                 goto out_nounlock;
3984         }
3985
3986         lock_sock(sk);
3987
3988         switch (optname) {
3989         case SCTP_SOCKOPT_BINDX_ADD:
3990                 /* 'optlen' is the size of the addresses buffer. */
3991                 retval = sctp_setsockopt_bindx(sk, (struct sockaddr __user *)optval,
3992                                                optlen, SCTP_BINDX_ADD_ADDR);
3993                 break;
3994
3995         case SCTP_SOCKOPT_BINDX_REM:
3996                 /* 'optlen' is the size of the addresses buffer. */
3997                 retval = sctp_setsockopt_bindx(sk, (struct sockaddr __user *)optval,
3998                                                optlen, SCTP_BINDX_REM_ADDR);
3999                 break;
4000
4001         case SCTP_SOCKOPT_CONNECTX_OLD:
4002                 /* 'optlen' is the size of the addresses buffer. */
4003                 retval = sctp_setsockopt_connectx_old(sk,
4004                                             (struct sockaddr __user *)optval,
4005                                             optlen);
4006                 break;
4007
4008         case SCTP_SOCKOPT_CONNECTX:
4009                 /* 'optlen' is the size of the addresses buffer. */
4010                 retval = sctp_setsockopt_connectx(sk,
4011                                             (struct sockaddr __user *)optval,
4012                                             optlen);
4013                 break;
4014
4015         case SCTP_DISABLE_FRAGMENTS:
4016                 retval = sctp_setsockopt_disable_fragments(sk, optval, optlen);
4017                 break;
4018
4019         case SCTP_EVENTS:
4020                 retval = sctp_setsockopt_events(sk, optval, optlen);
4021                 break;
4022
4023         case SCTP_AUTOCLOSE:
4024                 retval = sctp_setsockopt_autoclose(sk, optval, optlen);
4025                 break;
4026
4027         case SCTP_PEER_ADDR_PARAMS:
4028                 retval = sctp_setsockopt_peer_addr_params(sk, optval, optlen);
4029                 break;
4030
4031         case SCTP_DELAYED_SACK:
4032                 retval = sctp_setsockopt_delayed_ack(sk, optval, optlen);
4033                 break;
4034         case SCTP_PARTIAL_DELIVERY_POINT:
4035                 retval = sctp_setsockopt_partial_delivery_point(sk, optval, optlen);
4036                 break;
4037
4038         case SCTP_INITMSG:
4039                 retval = sctp_setsockopt_initmsg(sk, optval, optlen);
4040                 break;
4041         case SCTP_DEFAULT_SEND_PARAM:
4042                 retval = sctp_setsockopt_default_send_param(sk, optval,
4043                                                             optlen);
4044                 break;
4045         case SCTP_DEFAULT_SNDINFO:
4046                 retval = sctp_setsockopt_default_sndinfo(sk, optval, optlen);
4047                 break;
4048         case SCTP_PRIMARY_ADDR:
4049                 retval = sctp_setsockopt_primary_addr(sk, optval, optlen);
4050                 break;
4051         case SCTP_SET_PEER_PRIMARY_ADDR:
4052                 retval = sctp_setsockopt_peer_primary_addr(sk, optval, optlen);
4053                 break;
4054         case SCTP_NODELAY:
4055                 retval = sctp_setsockopt_nodelay(sk, optval, optlen);
4056                 break;
4057         case SCTP_RTOINFO:
4058                 retval = sctp_setsockopt_rtoinfo(sk, optval, optlen);
4059                 break;
4060         case SCTP_ASSOCINFO:
4061                 retval = sctp_setsockopt_associnfo(sk, optval, optlen);
4062                 break;
4063         case SCTP_I_WANT_MAPPED_V4_ADDR:
4064                 retval = sctp_setsockopt_mappedv4(sk, optval, optlen);
4065                 break;
4066         case SCTP_MAXSEG:
4067                 retval = sctp_setsockopt_maxseg(sk, optval, optlen);
4068                 break;
4069         case SCTP_ADAPTATION_LAYER:
4070                 retval = sctp_setsockopt_adaptation_layer(sk, optval, optlen);
4071                 break;
4072         case SCTP_CONTEXT:
4073                 retval = sctp_setsockopt_context(sk, optval, optlen);
4074                 break;
4075         case SCTP_FRAGMENT_INTERLEAVE:
4076                 retval = sctp_setsockopt_fragment_interleave(sk, optval, optlen);
4077                 break;
4078         case SCTP_MAX_BURST:
4079                 retval = sctp_setsockopt_maxburst(sk, optval, optlen);
4080                 break;
4081         case SCTP_AUTH_CHUNK:
4082                 retval = sctp_setsockopt_auth_chunk(sk, optval, optlen);
4083                 break;
4084         case SCTP_HMAC_IDENT:
4085                 retval = sctp_setsockopt_hmac_ident(sk, optval, optlen);
4086                 break;
4087         case SCTP_AUTH_KEY:
4088                 retval = sctp_setsockopt_auth_key(sk, optval, optlen);
4089                 break;
4090         case SCTP_AUTH_ACTIVE_KEY:
4091                 retval = sctp_setsockopt_active_key(sk, optval, optlen);
4092                 break;
4093         case SCTP_AUTH_DELETE_KEY:
4094                 retval = sctp_setsockopt_del_key(sk, optval, optlen);
4095                 break;
4096         case SCTP_AUTO_ASCONF:
4097                 retval = sctp_setsockopt_auto_asconf(sk, optval, optlen);
4098                 break;
4099         case SCTP_PEER_ADDR_THLDS:
4100                 retval = sctp_setsockopt_paddr_thresholds(sk, optval, optlen);
4101                 break;
4102         case SCTP_RECVRCVINFO:
4103                 retval = sctp_setsockopt_recvrcvinfo(sk, optval, optlen);
4104                 break;
4105         case SCTP_RECVNXTINFO:
4106                 retval = sctp_setsockopt_recvnxtinfo(sk, optval, optlen);
4107                 break;
4108         case SCTP_PR_SUPPORTED:
4109                 retval = sctp_setsockopt_pr_supported(sk, optval, optlen);
4110                 break;
4111         case SCTP_DEFAULT_PRINFO:
4112                 retval = sctp_setsockopt_default_prinfo(sk, optval, optlen);
4113                 break;
4114         case SCTP_RECONFIG_SUPPORTED:
4115                 retval = sctp_setsockopt_reconfig_supported(sk, optval, optlen);
4116                 break;
4117         case SCTP_ENABLE_STREAM_RESET:
4118                 retval = sctp_setsockopt_enable_strreset(sk, optval, optlen);
4119                 break;
4120         case SCTP_RESET_STREAMS:
4121                 retval = sctp_setsockopt_reset_streams(sk, optval, optlen);
4122                 break;
4123         case SCTP_RESET_ASSOC:
4124                 retval = sctp_setsockopt_reset_assoc(sk, optval, optlen);
4125                 break;
4126         case SCTP_ADD_STREAMS:
4127                 retval = sctp_setsockopt_add_streams(sk, optval, optlen);
4128                 break;
4129         case SCTP_STREAM_SCHEDULER:
4130                 retval = sctp_setsockopt_scheduler(sk, optval, optlen);
4131                 break;
4132         default:
4133                 retval = -ENOPROTOOPT;
4134                 break;
4135         }
4136
4137         release_sock(sk);
4138
4139 out_nounlock:
4140         return retval;
4141 }
4142
4143 /* API 3.1.6 connect() - UDP Style Syntax
4144  *
4145  * An application may use the connect() call in the UDP model to initiate an
4146  * association without sending data.
4147  *
4148  * The syntax is:
4149  *
4150  * ret = connect(int sd, const struct sockaddr *nam, socklen_t len);
4151  *
4152  * sd: the socket descriptor to have a new association added to.
4153  *
4154  * nam: the address structure (either struct sockaddr_in or struct
4155  *    sockaddr_in6 defined in RFC2553 [7]).
4156  *
4157  * len: the size of the address.
4158  */
4159 static int sctp_connect(struct sock *sk, struct sockaddr *addr,
4160                         int addr_len)
4161 {
4162         int err = 0;
4163         struct sctp_af *af;
4164
4165         lock_sock(sk);
4166
4167         pr_debug("%s: sk:%p, sockaddr:%p, addr_len:%d\n", __func__, sk,
4168                  addr, addr_len);
4169
4170         /* Validate addr_len before calling common connect/connectx routine. */
4171         af = sctp_get_af_specific(addr->sa_family);
4172         if (!af || addr_len < af->sockaddr_len) {
4173                 err = -EINVAL;
4174         } else {
4175                 /* Pass correct addr len to common routine (so it knows there
4176                  * is only one address being passed.
4177                  */
4178                 err = __sctp_connect(sk, addr, af->sockaddr_len, NULL);
4179         }
4180
4181         release_sock(sk);
4182         return err;
4183 }
4184
4185 /* FIXME: Write comments. */
4186 static int sctp_disconnect(struct sock *sk, int flags)
4187 {
4188         return -EOPNOTSUPP; /* STUB */
4189 }
4190
4191 /* 4.1.4 accept() - TCP Style Syntax
4192  *
4193  * Applications use accept() call to remove an established SCTP
4194  * association from the accept queue of the endpoint.  A new socket
4195  * descriptor will be returned from accept() to represent the newly
4196  * formed association.
4197  */
4198 static struct sock *sctp_accept(struct sock *sk, int flags, int *err, bool kern)
4199 {
4200         struct sctp_sock *sp;
4201         struct sctp_endpoint *ep;
4202         struct sock *newsk = NULL;
4203         struct sctp_association *asoc;
4204         long timeo;
4205         int error = 0;
4206
4207         lock_sock(sk);
4208
4209         sp = sctp_sk(sk);
4210         ep = sp->ep;
4211
4212         if (!sctp_style(sk, TCP)) {
4213                 error = -EOPNOTSUPP;
4214                 goto out;
4215         }
4216
4217         if (!sctp_sstate(sk, LISTENING)) {
4218                 error = -EINVAL;
4219                 goto out;
4220         }
4221
4222         timeo = sock_rcvtimeo(sk, flags & O_NONBLOCK);
4223
4224         error = sctp_wait_for_accept(sk, timeo);
4225         if (error)
4226                 goto out;
4227
4228         /* We treat the list of associations on the endpoint as the accept
4229          * queue and pick the first association on the list.
4230          */
4231         asoc = list_entry(ep->asocs.next, struct sctp_association, asocs);
4232
4233         newsk = sp->pf->create_accept_sk(sk, asoc, kern);
4234         if (!newsk) {
4235                 error = -ENOMEM;
4236                 goto out;
4237         }
4238
4239         /* Populate the fields of the newsk from the oldsk and migrate the
4240          * asoc to the newsk.
4241          */
4242         sctp_sock_migrate(sk, newsk, asoc, SCTP_SOCKET_TCP);
4243
4244 out:
4245         release_sock(sk);
4246         *err = error;
4247         return newsk;
4248 }
4249
4250 /* The SCTP ioctl handler. */
4251 static int sctp_ioctl(struct sock *sk, int cmd, unsigned long arg)
4252 {
4253         int rc = -ENOTCONN;
4254
4255         lock_sock(sk);
4256
4257         /*
4258          * SEQPACKET-style sockets in LISTENING state are valid, for
4259          * SCTP, so only discard TCP-style sockets in LISTENING state.
4260          */
4261         if (sctp_style(sk, TCP) && sctp_sstate(sk, LISTENING))
4262                 goto out;
4263
4264         switch (cmd) {
4265         case SIOCINQ: {
4266                 struct sk_buff *skb;
4267                 unsigned int amount = 0;
4268
4269                 skb = skb_peek(&sk->sk_receive_queue);
4270                 if (skb != NULL) {
4271                         /*
4272                          * We will only return the amount of this packet since
4273                          * that is all that will be read.
4274                          */
4275                         amount = skb->len;
4276                 }
4277                 rc = put_user(amount, (int __user *)arg);
4278                 break;
4279         }
4280         default:
4281                 rc = -ENOIOCTLCMD;
4282                 break;
4283         }
4284 out:
4285         release_sock(sk);
4286         return rc;
4287 }
4288
4289 /* This is the function which gets called during socket creation to
4290  * initialized the SCTP-specific portion of the sock.
4291  * The sock structure should already be zero-filled memory.
4292  */
4293 static int sctp_init_sock(struct sock *sk)
4294 {
4295         struct net *net = sock_net(sk);
4296         struct sctp_sock *sp;
4297
4298         pr_debug("%s: sk:%p\n", __func__, sk);
4299
4300         sp = sctp_sk(sk);
4301
4302         /* Initialize the SCTP per socket area.  */
4303         switch (sk->sk_type) {
4304         case SOCK_SEQPACKET:
4305                 sp->type = SCTP_SOCKET_UDP;
4306                 break;
4307         case SOCK_STREAM:
4308                 sp->type = SCTP_SOCKET_TCP;
4309                 break;
4310         default:
4311                 return -ESOCKTNOSUPPORT;
4312         }
4313
4314         sk->sk_gso_type = SKB_GSO_SCTP;
4315
4316         /* Initialize default send parameters. These parameters can be
4317          * modified with the SCTP_DEFAULT_SEND_PARAM socket option.
4318          */
4319         sp->default_stream = 0;
4320         sp->default_ppid = 0;
4321         sp->default_flags = 0;
4322         sp->default_context = 0;
4323         sp->default_timetolive = 0;
4324
4325         sp->default_rcv_context = 0;
4326         sp->max_burst = net->sctp.max_burst;
4327
4328         sp->sctp_hmac_alg = net->sctp.sctp_hmac_alg;
4329
4330         /* Initialize default setup parameters. These parameters
4331          * can be modified with the SCTP_INITMSG socket option or
4332          * overridden by the SCTP_INIT CMSG.
4333          */
4334         sp->initmsg.sinit_num_ostreams   = sctp_max_outstreams;
4335         sp->initmsg.sinit_max_instreams  = sctp_max_instreams;
4336         sp->initmsg.sinit_max_attempts   = net->sctp.max_retrans_init;
4337         sp->initmsg.sinit_max_init_timeo = net->sctp.rto_max;
4338
4339         /* Initialize default RTO related parameters.  These parameters can
4340          * be modified for with the SCTP_RTOINFO socket option.
4341          */
4342         sp->rtoinfo.srto_initial = net->sctp.rto_initial;
4343         sp->rtoinfo.srto_max     = net->sctp.rto_max;
4344         sp->rtoinfo.srto_min     = net->sctp.rto_min;
4345
4346         /* Initialize default association related parameters. These parameters
4347          * can be modified with the SCTP_ASSOCINFO socket option.
4348          */
4349         sp->assocparams.sasoc_asocmaxrxt = net->sctp.max_retrans_association;
4350         sp->assocparams.sasoc_number_peer_destinations = 0;
4351         sp->assocparams.sasoc_peer_rwnd = 0;
4352         sp->assocparams.sasoc_local_rwnd = 0;
4353         sp->assocparams.sasoc_cookie_life = net->sctp.valid_cookie_life;
4354
4355         /* Initialize default event subscriptions. By default, all the
4356          * options are off.
4357          */
4358         memset(&sp->subscribe, 0, sizeof(struct sctp_event_subscribe));
4359
4360         /* Default Peer Address Parameters.  These defaults can
4361          * be modified via SCTP_PEER_ADDR_PARAMS
4362          */
4363         sp->hbinterval  = net->sctp.hb_interval;
4364         sp->pathmaxrxt  = net->sctp.max_retrans_path;
4365         sp->pathmtu     = 0; /* allow default discovery */
4366         sp->sackdelay   = net->sctp.sack_timeout;
4367         sp->sackfreq    = 2;
4368         sp->param_flags = SPP_HB_ENABLE |
4369                           SPP_PMTUD_ENABLE |
4370                           SPP_SACKDELAY_ENABLE;
4371
4372         /* If enabled no SCTP message fragmentation will be performed.
4373          * Configure through SCTP_DISABLE_FRAGMENTS socket option.
4374          */
4375         sp->disable_fragments = 0;
4376
4377         /* Enable Nagle algorithm by default.  */
4378         sp->nodelay           = 0;
4379
4380         sp->recvrcvinfo = 0;
4381         sp->recvnxtinfo = 0;
4382
4383         /* Enable by default. */
4384         sp->v4mapped          = 1;
4385
4386         /* Auto-close idle associations after the configured
4387          * number of seconds.  A value of 0 disables this
4388          * feature.  Configure through the SCTP_AUTOCLOSE socket option,
4389          * for UDP-style sockets only.
4390          */
4391         sp->autoclose         = 0;
4392
4393         /* User specified fragmentation limit. */
4394         sp->user_frag         = 0;
4395
4396         sp->adaptation_ind = 0;
4397
4398         sp->pf = sctp_get_pf_specific(sk->sk_family);
4399
4400         /* Control variables for partial data delivery. */
4401         atomic_set(&sp->pd_mode, 0);
4402         skb_queue_head_init(&sp->pd_lobby);
4403         sp->frag_interleave = 0;
4404
4405         /* Create a per socket endpoint structure.  Even if we
4406          * change the data structure relationships, this may still
4407          * be useful for storing pre-connect address information.
4408          */
4409         sp->ep = sctp_endpoint_new(sk, GFP_KERNEL);
4410         if (!sp->ep)
4411                 return -ENOMEM;
4412
4413         sp->hmac = NULL;
4414
4415         sk->sk_destruct = sctp_destruct_sock;
4416
4417         SCTP_DBG_OBJCNT_INC(sock);
4418
4419         local_bh_disable();
4420         percpu_counter_inc(&sctp_sockets_allocated);
4421         sock_prot_inuse_add(net, sk->sk_prot, 1);
4422
4423         /* Nothing can fail after this block, otherwise
4424          * sctp_destroy_sock() will be called without addr_wq_lock held
4425          */
4426         if (net->sctp.default_auto_asconf) {
4427                 spin_lock(&sock_net(sk)->sctp.addr_wq_lock);
4428                 list_add_tail(&sp->auto_asconf_list,
4429                     &net->sctp.auto_asconf_splist);
4430                 sp->do_auto_asconf = 1;
4431                 spin_unlock(&sock_net(sk)->sctp.addr_wq_lock);
4432         } else {
4433                 sp->do_auto_asconf = 0;
4434         }
4435
4436         local_bh_enable();
4437
4438         return 0;
4439 }
4440
4441 /* Cleanup any SCTP per socket resources. Must be called with
4442  * sock_net(sk)->sctp.addr_wq_lock held if sp->do_auto_asconf is true
4443  */
4444 static void sctp_destroy_sock(struct sock *sk)
4445 {
4446         struct sctp_sock *sp;
4447
4448         pr_debug("%s: sk:%p\n", __func__, sk);
4449
4450         /* Release our hold on the endpoint. */
4451         sp = sctp_sk(sk);
4452         /* This could happen during socket init, thus we bail out
4453          * early, since the rest of the below is not setup either.
4454          */
4455         if (sp->ep == NULL)
4456                 return;
4457
4458         if (sp->do_auto_asconf) {
4459                 sp->do_auto_asconf = 0;
4460                 list_del(&sp->auto_asconf_list);
4461         }
4462         sctp_endpoint_free(sp->ep);
4463         local_bh_disable();
4464         percpu_counter_dec(&sctp_sockets_allocated);
4465         sock_prot_inuse_add(sock_net(sk), sk->sk_prot, -1);
4466         local_bh_enable();
4467 }
4468
4469 /* Triggered when there are no references on the socket anymore */
4470 static void sctp_destruct_sock(struct sock *sk)
4471 {
4472         struct sctp_sock *sp = sctp_sk(sk);
4473
4474         /* Free up the HMAC transform. */
4475         crypto_free_shash(sp->hmac);
4476
4477         inet_sock_destruct(sk);
4478 }
4479
4480 /* API 4.1.7 shutdown() - TCP Style Syntax
4481  *     int shutdown(int socket, int how);
4482  *
4483  *     sd      - the socket descriptor of the association to be closed.
4484  *     how     - Specifies the type of shutdown.  The  values  are
4485  *               as follows:
4486  *               SHUT_RD
4487  *                     Disables further receive operations. No SCTP
4488  *                     protocol action is taken.
4489  *               SHUT_WR
4490  *                     Disables further send operations, and initiates
4491  *                     the SCTP shutdown sequence.
4492  *               SHUT_RDWR
4493  *                     Disables further send  and  receive  operations
4494  *                     and initiates the SCTP shutdown sequence.
4495  */
4496 static void sctp_shutdown(struct sock *sk, int how)
4497 {
4498         struct net *net = sock_net(sk);
4499         struct sctp_endpoint *ep;
4500
4501         if (!sctp_style(sk, TCP))
4502                 return;
4503
4504         ep = sctp_sk(sk)->ep;
4505         if (how & SEND_SHUTDOWN && !list_empty(&ep->asocs)) {
4506                 struct sctp_association *asoc;
4507
4508                 sk->sk_state = SCTP_SS_CLOSING;
4509                 asoc = list_entry(ep->asocs.next,
4510                                   struct sctp_association, asocs);
4511                 sctp_primitive_SHUTDOWN(net, asoc, NULL);
4512         }
4513 }
4514
4515 int sctp_get_sctp_info(struct sock *sk, struct sctp_association *asoc,
4516                        struct sctp_info *info)
4517 {
4518         struct sctp_transport *prim;
4519         struct list_head *pos;
4520         int mask;
4521
4522         memset(info, 0, sizeof(*info));
4523         if (!asoc) {
4524                 struct sctp_sock *sp = sctp_sk(sk);
4525
4526                 info->sctpi_s_autoclose = sp->autoclose;
4527                 info->sctpi_s_adaptation_ind = sp->adaptation_ind;
4528                 info->sctpi_s_pd_point = sp->pd_point;
4529                 info->sctpi_s_nodelay = sp->nodelay;
4530                 info->sctpi_s_disable_fragments = sp->disable_fragments;
4531                 info->sctpi_s_v4mapped = sp->v4mapped;
4532                 info->sctpi_s_frag_interleave = sp->frag_interleave;
4533                 info->sctpi_s_type = sp->type;
4534
4535                 return 0;
4536         }
4537
4538         info->sctpi_tag = asoc->c.my_vtag;
4539         info->sctpi_state = asoc->state;
4540         info->sctpi_rwnd = asoc->a_rwnd;
4541         info->sctpi_unackdata = asoc->unack_data;
4542         info->sctpi_penddata = sctp_tsnmap_pending(&asoc->peer.tsn_map);
4543         info->sctpi_instrms = asoc->stream.incnt;
4544         info->sctpi_outstrms = asoc->stream.outcnt;
4545         list_for_each(pos, &asoc->base.inqueue.in_chunk_list)
4546                 info->sctpi_inqueue++;
4547         list_for_each(pos, &asoc->outqueue.out_chunk_list)
4548                 info->sctpi_outqueue++;
4549         info->sctpi_overall_error = asoc->overall_error_count;
4550         info->sctpi_max_burst = asoc->max_burst;
4551         info->sctpi_maxseg = asoc->frag_point;
4552         info->sctpi_peer_rwnd = asoc->peer.rwnd;
4553         info->sctpi_peer_tag = asoc->c.peer_vtag;
4554
4555         mask = asoc->peer.ecn_capable << 1;
4556         mask = (mask | asoc->peer.ipv4_address) << 1;
4557         mask = (mask | asoc->peer.ipv6_address) << 1;
4558         mask = (mask | asoc->peer.hostname_address) << 1;
4559         mask = (mask | asoc->peer.asconf_capable) << 1;
4560         mask = (mask | asoc->peer.prsctp_capable) << 1;
4561         mask = (mask | asoc->peer.auth_capable);
4562         info->sctpi_peer_capable = mask;
4563         mask = asoc->peer.sack_needed << 1;
4564         mask = (mask | asoc->peer.sack_generation) << 1;
4565         mask = (mask | asoc->peer.zero_window_announced);
4566         info->sctpi_peer_sack = mask;
4567
4568         info->sctpi_isacks = asoc->stats.isacks;
4569         info->sctpi_osacks = asoc->stats.osacks;
4570         info->sctpi_opackets = asoc->stats.opackets;
4571         info->sctpi_ipackets = asoc->stats.ipackets;
4572         info->sctpi_rtxchunks = asoc->stats.rtxchunks;
4573         info->sctpi_outofseqtsns = asoc->stats.outofseqtsns;
4574         info->sctpi_idupchunks = asoc->stats.idupchunks;
4575         info->sctpi_gapcnt = asoc->stats.gapcnt;
4576         info->sctpi_ouodchunks = asoc->stats.ouodchunks;
4577         info->sctpi_iuodchunks = asoc->stats.iuodchunks;
4578         info->sctpi_oodchunks = asoc->stats.oodchunks;
4579         info->sctpi_iodchunks = asoc->stats.iodchunks;
4580         info->sctpi_octrlchunks = asoc->stats.octrlchunks;
4581         info->sctpi_ictrlchunks = asoc->stats.ictrlchunks;
4582
4583         prim = asoc->peer.primary_path;
4584         memcpy(&info->sctpi_p_address, &prim->ipaddr, sizeof(prim->ipaddr));
4585         info->sctpi_p_state = prim->state;
4586         info->sctpi_p_cwnd = prim->cwnd;
4587         info->sctpi_p_srtt = prim->srtt;
4588         info->sctpi_p_rto = jiffies_to_msecs(prim->rto);
4589         info->sctpi_p_hbinterval = prim->hbinterval;
4590         info->sctpi_p_pathmaxrxt = prim->pathmaxrxt;
4591         info->sctpi_p_sackdelay = jiffies_to_msecs(prim->sackdelay);
4592         info->sctpi_p_ssthresh = prim->ssthresh;
4593         info->sctpi_p_partial_bytes_acked = prim->partial_bytes_acked;
4594         info->sctpi_p_flight_size = prim->flight_size;
4595         info->sctpi_p_error = prim->error_count;
4596
4597         return 0;
4598 }
4599 EXPORT_SYMBOL_GPL(sctp_get_sctp_info);
4600
4601 /* use callback to avoid exporting the core structure */
4602 int sctp_transport_walk_start(struct rhashtable_iter *iter)
4603 {
4604         int err;
4605
4606         rhltable_walk_enter(&sctp_transport_hashtable, iter);
4607
4608         err = rhashtable_walk_start(iter);
4609         if (err && err != -EAGAIN) {
4610                 rhashtable_walk_stop(iter);
4611                 rhashtable_walk_exit(iter);
4612                 return err;
4613         }
4614
4615         return 0;
4616 }
4617
4618 void sctp_transport_walk_stop(struct rhashtable_iter *iter)
4619 {
4620         rhashtable_walk_stop(iter);
4621         rhashtable_walk_exit(iter);
4622 }
4623
4624 struct sctp_transport *sctp_transport_get_next(struct net *net,
4625                                                struct rhashtable_iter *iter)
4626 {
4627         struct sctp_transport *t;
4628
4629         t = rhashtable_walk_next(iter);
4630         for (; t; t = rhashtable_walk_next(iter)) {
4631                 if (IS_ERR(t)) {
4632                         if (PTR_ERR(t) == -EAGAIN)
4633                                 continue;
4634                         break;
4635                 }
4636
4637                 if (net_eq(sock_net(t->asoc->base.sk), net) &&
4638                     t->asoc->peer.primary_path == t)
4639                         break;
4640         }
4641
4642         return t;
4643 }
4644
4645 struct sctp_transport *sctp_transport_get_idx(struct net *net,
4646                                               struct rhashtable_iter *iter,
4647                                               int pos)
4648 {
4649         void *obj = SEQ_START_TOKEN;
4650
4651         while (pos && (obj = sctp_transport_get_next(net, iter)) &&
4652                !IS_ERR(obj))
4653                 pos--;
4654
4655         return obj;
4656 }
4657
4658 int sctp_for_each_endpoint(int (*cb)(struct sctp_endpoint *, void *),
4659                            void *p) {
4660         int err = 0;
4661         int hash = 0;
4662         struct sctp_ep_common *epb;
4663         struct sctp_hashbucket *head;
4664
4665         for (head = sctp_ep_hashtable; hash < sctp_ep_hashsize;
4666              hash++, head++) {
4667                 read_lock_bh(&head->lock);
4668                 sctp_for_each_hentry(epb, &head->chain) {
4669                         err = cb(sctp_ep(epb), p);
4670                         if (err)
4671                                 break;
4672                 }
4673                 read_unlock_bh(&head->lock);
4674         }
4675
4676         return err;
4677 }
4678 EXPORT_SYMBOL_GPL(sctp_for_each_endpoint);
4679
4680 int sctp_transport_lookup_process(int (*cb)(struct sctp_transport *, void *),
4681                                   struct net *net,
4682                                   const union sctp_addr *laddr,
4683                                   const union sctp_addr *paddr, void *p)
4684 {
4685         struct sctp_transport *transport;
4686         int err;
4687
4688         rcu_read_lock();
4689         transport = sctp_addrs_lookup_transport(net, laddr, paddr);
4690         rcu_read_unlock();
4691         if (!transport)
4692                 return -ENOENT;
4693
4694         err = cb(transport, p);
4695         sctp_transport_put(transport);
4696
4697         return err;
4698 }
4699 EXPORT_SYMBOL_GPL(sctp_transport_lookup_process);
4700
4701 int sctp_for_each_transport(int (*cb)(struct sctp_transport *, void *),
4702                             int (*cb_done)(struct sctp_transport *, void *),
4703                             struct net *net, int *pos, void *p) {
4704         struct rhashtable_iter hti;
4705         struct sctp_transport *tsp;
4706         int ret;
4707
4708 again:
4709         ret = sctp_transport_walk_start(&hti);
4710         if (ret)
4711                 return ret;
4712
4713         tsp = sctp_transport_get_idx(net, &hti, *pos + 1);
4714         for (; !IS_ERR_OR_NULL(tsp); tsp = sctp_transport_get_next(net, &hti)) {
4715                 if (!sctp_transport_hold(tsp))
4716                         continue;
4717                 ret = cb(tsp, p);
4718                 if (ret)
4719                         break;
4720                 (*pos)++;
4721                 sctp_transport_put(tsp);
4722         }
4723         sctp_transport_walk_stop(&hti);
4724
4725         if (ret) {
4726                 if (cb_done && !cb_done(tsp, p)) {
4727                         (*pos)++;
4728                         sctp_transport_put(tsp);
4729                         goto again;
4730                 }
4731                 sctp_transport_put(tsp);
4732         }
4733
4734         return ret;
4735 }
4736 EXPORT_SYMBOL_GPL(sctp_for_each_transport);
4737
4738 /* 7.2.1 Association Status (SCTP_STATUS)
4739
4740  * Applications can retrieve current status information about an
4741  * association, including association state, peer receiver window size,
4742  * number of unacked data chunks, and number of data chunks pending
4743  * receipt.  This information is read-only.
4744  */
4745 static int sctp_getsockopt_sctp_status(struct sock *sk, int len,
4746                                        char __user *optval,
4747                                        int __user *optlen)
4748 {
4749         struct sctp_status status;
4750         struct sctp_association *asoc = NULL;
4751         struct sctp_transport *transport;
4752         sctp_assoc_t associd;
4753         int retval = 0;
4754
4755         if (len < sizeof(status)) {
4756                 retval = -EINVAL;
4757                 goto out;
4758         }
4759
4760         len = sizeof(status);
4761         if (copy_from_user(&status, optval, len)) {
4762                 retval = -EFAULT;
4763                 goto out;
4764         }
4765
4766         associd = status.sstat_assoc_id;
4767         asoc = sctp_id2assoc(sk, associd);
4768         if (!asoc) {
4769                 retval = -EINVAL;
4770                 goto out;
4771         }
4772
4773         transport = asoc->peer.primary_path;
4774
4775         status.sstat_assoc_id = sctp_assoc2id(asoc);
4776         status.sstat_state = sctp_assoc_to_state(asoc);
4777         status.sstat_rwnd =  asoc->peer.rwnd;
4778         status.sstat_unackdata = asoc->unack_data;
4779
4780         status.sstat_penddata = sctp_tsnmap_pending(&asoc->peer.tsn_map);
4781         status.sstat_instrms = asoc->stream.incnt;
4782         status.sstat_outstrms = asoc->stream.outcnt;
4783         status.sstat_fragmentation_point = asoc->frag_point;
4784         status.sstat_primary.spinfo_assoc_id = sctp_assoc2id(transport->asoc);
4785         memcpy(&status.sstat_primary.spinfo_address, &transport->ipaddr,
4786                         transport->af_specific->sockaddr_len);
4787         /* Map ipv4 address into v4-mapped-on-v6 address.  */
4788         sctp_get_pf_specific(sk->sk_family)->addr_to_user(sctp_sk(sk),
4789                 (union sctp_addr *)&status.sstat_primary.spinfo_address);
4790         status.sstat_primary.spinfo_state = transport->state;
4791         status.sstat_primary.spinfo_cwnd = transport->cwnd;
4792         status.sstat_primary.spinfo_srtt = transport->srtt;
4793         status.sstat_primary.spinfo_rto = jiffies_to_msecs(transport->rto);
4794         status.sstat_primary.spinfo_mtu = transport->pathmtu;
4795
4796         if (status.sstat_primary.spinfo_state == SCTP_UNKNOWN)
4797                 status.sstat_primary.spinfo_state = SCTP_ACTIVE;
4798
4799         if (put_user(len, optlen)) {
4800                 retval = -EFAULT;
4801                 goto out;
4802         }
4803
4804         pr_debug("%s: len:%d, state:%d, rwnd:%d, assoc_id:%d\n",
4805                  __func__, len, status.sstat_state, status.sstat_rwnd,
4806                  status.sstat_assoc_id);
4807
4808         if (copy_to_user(optval, &status, len)) {
4809                 retval = -EFAULT;
4810                 goto out;
4811         }
4812
4813 out:
4814         return retval;
4815 }
4816
4817
4818 /* 7.2.2 Peer Address Information (SCTP_GET_PEER_ADDR_INFO)
4819  *
4820  * Applications can retrieve information about a specific peer address
4821  * of an association, including its reachability state, congestion
4822  * window, and retransmission timer values.  This information is
4823  * read-only.
4824  */
4825 static int sctp_getsockopt_peer_addr_info(struct sock *sk, int len,
4826                                           char __user *optval,
4827                                           int __user *optlen)
4828 {
4829         struct sctp_paddrinfo pinfo;
4830         struct sctp_transport *transport;
4831         int retval = 0;
4832
4833         if (len < sizeof(pinfo)) {
4834                 retval = -EINVAL;
4835                 goto out;
4836         }
4837
4838         len = sizeof(pinfo);
4839         if (copy_from_user(&pinfo, optval, len)) {
4840                 retval = -EFAULT;
4841                 goto out;
4842         }
4843
4844         transport = sctp_addr_id2transport(sk, &pinfo.spinfo_address,
4845                                            pinfo.spinfo_assoc_id);
4846         if (!transport)
4847                 return -EINVAL;
4848
4849         pinfo.spinfo_assoc_id = sctp_assoc2id(transport->asoc);
4850         pinfo.spinfo_state = transport->state;
4851         pinfo.spinfo_cwnd = transport->cwnd;
4852         pinfo.spinfo_srtt = transport->srtt;
4853         pinfo.spinfo_rto = jiffies_to_msecs(transport->rto);
4854         pinfo.spinfo_mtu = transport->pathmtu;
4855
4856         if (pinfo.spinfo_state == SCTP_UNKNOWN)
4857                 pinfo.spinfo_state = SCTP_ACTIVE;
4858
4859         if (put_user(len, optlen)) {
4860                 retval = -EFAULT;
4861                 goto out;
4862         }
4863
4864         if (copy_to_user(optval, &pinfo, len)) {
4865                 retval = -EFAULT;
4866                 goto out;
4867         }
4868
4869 out:
4870         return retval;
4871 }
4872
4873 /* 7.1.12 Enable/Disable message fragmentation (SCTP_DISABLE_FRAGMENTS)
4874  *
4875  * This option is a on/off flag.  If enabled no SCTP message
4876  * fragmentation will be performed.  Instead if a message being sent
4877  * exceeds the current PMTU size, the message will NOT be sent and
4878  * instead a error will be indicated to the user.
4879  */
4880 static int sctp_getsockopt_disable_fragments(struct sock *sk, int len,
4881                                         char __user *optval, int __user *optlen)
4882 {
4883         int val;
4884
4885         if (len < sizeof(int))
4886                 return -EINVAL;
4887
4888         len = sizeof(int);
4889         val = (sctp_sk(sk)->disable_fragments == 1);
4890         if (put_user(len, optlen))
4891                 return -EFAULT;
4892         if (copy_to_user(optval, &val, len))
4893                 return -EFAULT;
4894         return 0;
4895 }
4896
4897 /* 7.1.15 Set notification and ancillary events (SCTP_EVENTS)
4898  *
4899  * This socket option is used to specify various notifications and
4900  * ancillary data the user wishes to receive.
4901  */
4902 static int sctp_getsockopt_events(struct sock *sk, int len, char __user *optval,
4903                                   int __user *optlen)
4904 {
4905         if (len == 0)
4906                 return -EINVAL;
4907         if (len > sizeof(struct sctp_event_subscribe))
4908                 len = sizeof(struct sctp_event_subscribe);
4909         if (put_user(len, optlen))
4910                 return -EFAULT;
4911         if (copy_to_user(optval, &sctp_sk(sk)->subscribe, len))
4912                 return -EFAULT;
4913         return 0;
4914 }
4915
4916 /* 7.1.8 Automatic Close of associations (SCTP_AUTOCLOSE)
4917  *
4918  * This socket option is applicable to the UDP-style socket only.  When
4919  * set it will cause associations that are idle for more than the
4920  * specified number of seconds to automatically close.  An association
4921  * being idle is defined an association that has NOT sent or received
4922  * user data.  The special value of '0' indicates that no automatic
4923  * close of any associations should be performed.  The option expects an
4924  * integer defining the number of seconds of idle time before an
4925  * association is closed.
4926  */
4927 static int sctp_getsockopt_autoclose(struct sock *sk, int len, char __user *optval, int __user *optlen)
4928 {
4929         /* Applicable to UDP-style socket only */
4930         if (sctp_style(sk, TCP))
4931                 return -EOPNOTSUPP;
4932         if (len < sizeof(int))
4933                 return -EINVAL;
4934         len = sizeof(int);
4935         if (put_user(len, optlen))
4936                 return -EFAULT;
4937         if (copy_to_user(optval, &sctp_sk(sk)->autoclose, sizeof(int)))
4938                 return -EFAULT;
4939         return 0;
4940 }
4941
4942 /* Helper routine to branch off an association to a new socket.  */
4943 int sctp_do_peeloff(struct sock *sk, sctp_assoc_t id, struct socket **sockp)
4944 {
4945         struct sctp_association *asoc = sctp_id2assoc(sk, id);
4946         struct sctp_sock *sp = sctp_sk(sk);
4947         struct socket *sock;
4948         int err = 0;
4949
4950         if (!asoc)
4951                 return -EINVAL;
4952
4953         /* If there is a thread waiting on more sndbuf space for
4954          * sending on this asoc, it cannot be peeled.
4955          */
4956         if (waitqueue_active(&asoc->wait))
4957                 return -EBUSY;
4958
4959         /* An association cannot be branched off from an already peeled-off
4960          * socket, nor is this supported for tcp style sockets.
4961          */
4962         if (!sctp_style(sk, UDP))
4963                 return -EINVAL;
4964
4965         /* Create a new socket.  */
4966         err = sock_create(sk->sk_family, SOCK_SEQPACKET, IPPROTO_SCTP, &sock);
4967         if (err < 0)
4968                 return err;
4969
4970         sctp_copy_sock(sock->sk, sk, asoc);
4971
4972         /* Make peeled-off sockets more like 1-1 accepted sockets.
4973          * Set the daddr and initialize id to something more random
4974          */
4975         sp->pf->to_sk_daddr(&asoc->peer.primary_addr, sk);
4976
4977         /* Populate the fields of the newsk from the oldsk and migrate the
4978          * asoc to the newsk.
4979          */
4980         sctp_sock_migrate(sk, sock->sk, asoc, SCTP_SOCKET_UDP_HIGH_BANDWIDTH);
4981
4982         *sockp = sock;
4983
4984         return err;
4985 }
4986 EXPORT_SYMBOL(sctp_do_peeloff);
4987
4988 static int sctp_getsockopt_peeloff_common(struct sock *sk, sctp_peeloff_arg_t *peeloff,
4989                                           struct file **newfile, unsigned flags)
4990 {
4991         struct socket *newsock;
4992         int retval;
4993
4994         retval = sctp_do_peeloff(sk, peeloff->associd, &newsock);
4995         if (retval < 0)
4996                 goto out;
4997
4998         /* Map the socket to an unused fd that can be returned to the user.  */
4999         retval = get_unused_fd_flags(flags & SOCK_CLOEXEC);
5000         if (retval < 0) {
5001                 sock_release(newsock);
5002                 goto out;
5003         }
5004
5005         *newfile = sock_alloc_file(newsock, 0, NULL);
5006         if (IS_ERR(*newfile)) {
5007                 put_unused_fd(retval);
5008                 sock_release(newsock);
5009                 retval = PTR_ERR(*newfile);
5010                 *newfile = NULL;
5011                 return retval;
5012         }
5013
5014         pr_debug("%s: sk:%p, newsk:%p, sd:%d\n", __func__, sk, newsock->sk,
5015                  retval);
5016
5017         peeloff->sd = retval;
5018
5019         if (flags & SOCK_NONBLOCK)
5020                 (*newfile)->f_flags |= O_NONBLOCK;
5021 out:
5022         return retval;
5023 }
5024
5025 static int sctp_getsockopt_peeloff(struct sock *sk, int len, char __user *optval, int __user *optlen)
5026 {
5027         sctp_peeloff_arg_t peeloff;
5028         struct file *newfile = NULL;
5029         int retval = 0;
5030
5031         if (len < sizeof(sctp_peeloff_arg_t))
5032                 return -EINVAL;
5033         len = sizeof(sctp_peeloff_arg_t);
5034         if (copy_from_user(&peeloff, optval, len))
5035                 return -EFAULT;
5036
5037         retval = sctp_getsockopt_peeloff_common(sk, &peeloff, &newfile, 0);
5038         if (retval < 0)
5039                 goto out;
5040
5041         /* Return the fd mapped to the new socket.  */
5042         if (put_user(len, optlen)) {
5043                 fput(newfile);
5044                 put_unused_fd(retval);
5045                 return -EFAULT;
5046         }
5047
5048         if (copy_to_user(optval, &peeloff, len)) {
5049                 fput(newfile);
5050                 put_unused_fd(retval);
5051                 return -EFAULT;
5052         }
5053         fd_install(retval, newfile);
5054 out:
5055         return retval;
5056 }
5057
5058 static int sctp_getsockopt_peeloff_flags(struct sock *sk, int len,
5059                                          char __user *optval, int __user *optlen)
5060 {
5061         sctp_peeloff_flags_arg_t peeloff;
5062         struct file *newfile = NULL;
5063         int retval = 0;
5064
5065         if (len < sizeof(sctp_peeloff_flags_arg_t))
5066                 return -EINVAL;
5067         len = sizeof(sctp_peeloff_flags_arg_t);
5068         if (copy_from_user(&peeloff, optval, len))
5069                 return -EFAULT;
5070
5071         retval = sctp_getsockopt_peeloff_common(sk, &peeloff.p_arg,
5072                                                 &newfile, peeloff.flags);
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 /* 7.1.13 Peer Address Parameters (SCTP_PEER_ADDR_PARAMS)
5094  *
5095  * Applications can enable or disable heartbeats for any peer address of
5096  * an association, modify an address's heartbeat interval, force a
5097  * heartbeat to be sent immediately, and adjust the address's maximum
5098  * number of retransmissions sent before an address is considered
5099  * unreachable.  The following structure is used to access and modify an
5100  * address's parameters:
5101  *
5102  *  struct sctp_paddrparams {
5103  *     sctp_assoc_t            spp_assoc_id;
5104  *     struct sockaddr_storage spp_address;
5105  *     uint32_t                spp_hbinterval;
5106  *     uint16_t                spp_pathmaxrxt;
5107  *     uint32_t                spp_pathmtu;
5108  *     uint32_t                spp_sackdelay;
5109  *     uint32_t                spp_flags;
5110  * };
5111  *
5112  *   spp_assoc_id    - (one-to-many style socket) This is filled in the
5113  *                     application, and identifies the association for
5114  *                     this query.
5115  *   spp_address     - This specifies which address is of interest.
5116  *   spp_hbinterval  - This contains the value of the heartbeat interval,
5117  *                     in milliseconds.  If a  value of zero
5118  *                     is present in this field then no changes are to
5119  *                     be made to this parameter.
5120  *   spp_pathmaxrxt  - This contains the maximum number of
5121  *                     retransmissions before this address shall be
5122  *                     considered unreachable. If a  value of zero
5123  *                     is present in this field then no changes are to
5124  *                     be made to this parameter.
5125  *   spp_pathmtu     - When Path MTU discovery is disabled the value
5126  *                     specified here will be the "fixed" path mtu.
5127  *                     Note that if the spp_address field is empty
5128  *                     then all associations on this address will
5129  *                     have this fixed path mtu set upon them.
5130  *
5131  *   spp_sackdelay   - When delayed sack is enabled, this value specifies
5132  *                     the number of milliseconds that sacks will be delayed
5133  *                     for. This value will apply to all addresses of an
5134  *                     association if the spp_address field is empty. Note
5135  *                     also, that if delayed sack is enabled and this
5136  *                     value is set to 0, no change is made to the last
5137  *                     recorded delayed sack timer value.
5138  *
5139  *   spp_flags       - These flags are used to control various features
5140  *                     on an association. The flag field may contain
5141  *                     zero or more of the following options.
5142  *
5143  *                     SPP_HB_ENABLE  - Enable heartbeats on the
5144  *                     specified address. Note that if the address
5145  *                     field is empty all addresses for the association
5146  *                     have heartbeats enabled upon them.
5147  *
5148  *                     SPP_HB_DISABLE - Disable heartbeats on the
5149  *                     speicifed address. Note that if the address
5150  *                     field is empty all addresses for the association
5151  *                     will have their heartbeats disabled. Note also
5152  *                     that SPP_HB_ENABLE and SPP_HB_DISABLE are
5153  *                     mutually exclusive, only one of these two should
5154  *                     be specified. Enabling both fields will have
5155  *                     undetermined results.
5156  *
5157  *                     SPP_HB_DEMAND - Request a user initiated heartbeat
5158  *                     to be made immediately.
5159  *
5160  *                     SPP_PMTUD_ENABLE - This field will enable PMTU
5161  *                     discovery upon the specified address. Note that
5162  *                     if the address feild is empty then all addresses
5163  *                     on the association are effected.
5164  *
5165  *                     SPP_PMTUD_DISABLE - This field will disable PMTU
5166  *                     discovery upon the specified address. Note that
5167  *                     if the address feild is empty then all addresses
5168  *                     on the association are effected. Not also that
5169  *                     SPP_PMTUD_ENABLE and SPP_PMTUD_DISABLE are mutually
5170  *                     exclusive. Enabling both will have undetermined
5171  *                     results.
5172  *
5173  *                     SPP_SACKDELAY_ENABLE - Setting this flag turns
5174  *                     on delayed sack. The time specified in spp_sackdelay
5175  *                     is used to specify the sack delay for this address. Note
5176  *                     that if spp_address is empty then all addresses will
5177  *                     enable delayed sack and take on the sack delay
5178  *                     value specified in spp_sackdelay.
5179  *                     SPP_SACKDELAY_DISABLE - Setting this flag turns
5180  *                     off delayed sack. If the spp_address field is blank then
5181  *                     delayed sack is disabled for the entire association. Note
5182  *                     also that this field is mutually exclusive to
5183  *                     SPP_SACKDELAY_ENABLE, setting both will have undefined
5184  *                     results.
5185  */
5186 static int sctp_getsockopt_peer_addr_params(struct sock *sk, int len,
5187                                             char __user *optval, int __user *optlen)
5188 {
5189         struct sctp_paddrparams  params;
5190         struct sctp_transport   *trans = NULL;
5191         struct sctp_association *asoc = NULL;
5192         struct sctp_sock        *sp = sctp_sk(sk);
5193
5194         if (len < sizeof(struct sctp_paddrparams))
5195                 return -EINVAL;
5196         len = sizeof(struct sctp_paddrparams);
5197         if (copy_from_user(&params, optval, len))
5198                 return -EFAULT;
5199
5200         /* If an address other than INADDR_ANY is specified, and
5201          * no transport is found, then the request is invalid.
5202          */
5203         if (!sctp_is_any(sk, (union sctp_addr *)&params.spp_address)) {
5204                 trans = sctp_addr_id2transport(sk, &params.spp_address,
5205                                                params.spp_assoc_id);
5206                 if (!trans) {
5207                         pr_debug("%s: failed no transport\n", __func__);
5208                         return -EINVAL;
5209                 }
5210         }
5211
5212         /* Get association, if assoc_id != 0 and the socket is a one
5213          * to many style socket, and an association was not found, then
5214          * the id was invalid.
5215          */
5216         asoc = sctp_id2assoc(sk, params.spp_assoc_id);
5217         if (!asoc && params.spp_assoc_id && sctp_style(sk, UDP)) {
5218                 pr_debug("%s: failed no association\n", __func__);
5219                 return -EINVAL;
5220         }
5221
5222         if (trans) {
5223                 /* Fetch transport values. */
5224                 params.spp_hbinterval = jiffies_to_msecs(trans->hbinterval);
5225                 params.spp_pathmtu    = trans->pathmtu;
5226                 params.spp_pathmaxrxt = trans->pathmaxrxt;
5227                 params.spp_sackdelay  = jiffies_to_msecs(trans->sackdelay);
5228
5229                 /*draft-11 doesn't say what to return in spp_flags*/
5230                 params.spp_flags      = trans->param_flags;
5231         } else if (asoc) {
5232                 /* Fetch association values. */
5233                 params.spp_hbinterval = jiffies_to_msecs(asoc->hbinterval);
5234                 params.spp_pathmtu    = asoc->pathmtu;
5235                 params.spp_pathmaxrxt = asoc->pathmaxrxt;
5236                 params.spp_sackdelay  = jiffies_to_msecs(asoc->sackdelay);
5237
5238                 /*draft-11 doesn't say what to return in spp_flags*/
5239                 params.spp_flags      = asoc->param_flags;
5240         } else {
5241                 /* Fetch socket values. */
5242                 params.spp_hbinterval = sp->hbinterval;
5243                 params.spp_pathmtu    = sp->pathmtu;
5244                 params.spp_sackdelay  = sp->sackdelay;
5245                 params.spp_pathmaxrxt = sp->pathmaxrxt;
5246
5247                 /*draft-11 doesn't say what to return in spp_flags*/
5248                 params.spp_flags      = sp->param_flags;
5249         }
5250
5251         if (copy_to_user(optval, &params, len))
5252                 return -EFAULT;
5253
5254         if (put_user(len, optlen))
5255                 return -EFAULT;
5256
5257         return 0;
5258 }
5259
5260 /*
5261  * 7.1.23.  Get or set delayed ack timer (SCTP_DELAYED_SACK)
5262  *
5263  * This option will effect the way delayed acks are performed.  This
5264  * option allows you to get or set the delayed ack time, in
5265  * milliseconds.  It also allows changing the delayed ack frequency.
5266  * Changing the frequency to 1 disables the delayed sack algorithm.  If
5267  * the assoc_id is 0, then this sets or gets the endpoints default
5268  * values.  If the assoc_id field is non-zero, then the set or get
5269  * effects the specified association for the one to many model (the
5270  * assoc_id field is ignored by the one to one model).  Note that if
5271  * sack_delay or sack_freq are 0 when setting this option, then the
5272  * current values will remain unchanged.
5273  *
5274  * struct sctp_sack_info {
5275  *     sctp_assoc_t            sack_assoc_id;
5276  *     uint32_t                sack_delay;
5277  *     uint32_t                sack_freq;
5278  * };
5279  *
5280  * sack_assoc_id -  This parameter, indicates which association the user
5281  *    is performing an action upon.  Note that if this field's value is
5282  *    zero then the endpoints default value is changed (effecting future
5283  *    associations only).
5284  *
5285  * sack_delay -  This parameter contains the number of milliseconds that
5286  *    the user is requesting the delayed ACK timer be set to.  Note that
5287  *    this value is defined in the standard to be between 200 and 500
5288  *    milliseconds.
5289  *
5290  * sack_freq -  This parameter contains the number of packets that must
5291  *    be received before a sack is sent without waiting for the delay
5292  *    timer to expire.  The default value for this is 2, setting this
5293  *    value to 1 will disable the delayed sack algorithm.
5294  */
5295 static int sctp_getsockopt_delayed_ack(struct sock *sk, int len,
5296                                             char __user *optval,
5297                                             int __user *optlen)
5298 {
5299         struct sctp_sack_info    params;
5300         struct sctp_association *asoc = NULL;
5301         struct sctp_sock        *sp = sctp_sk(sk);
5302
5303         if (len >= sizeof(struct sctp_sack_info)) {
5304                 len = sizeof(struct sctp_sack_info);
5305
5306                 if (copy_from_user(&params, optval, len))
5307                         return -EFAULT;
5308         } else if (len == sizeof(struct sctp_assoc_value)) {
5309                 pr_warn_ratelimited(DEPRECATED
5310                                     "%s (pid %d) "
5311                                     "Use of struct sctp_assoc_value in delayed_ack socket option.\n"
5312                                     "Use struct sctp_sack_info instead\n",
5313                                     current->comm, task_pid_nr(current));
5314                 if (copy_from_user(&params, optval, len))
5315                         return -EFAULT;
5316         } else
5317                 return -EINVAL;
5318
5319         /* Get association, if sack_assoc_id != 0 and the socket is a one
5320          * to many style socket, and an association was not found, then
5321          * the id was invalid.
5322          */
5323         asoc = sctp_id2assoc(sk, params.sack_assoc_id);
5324         if (!asoc && params.sack_assoc_id && sctp_style(sk, UDP))
5325                 return -EINVAL;
5326
5327         if (asoc) {
5328                 /* Fetch association values. */
5329                 if (asoc->param_flags & SPP_SACKDELAY_ENABLE) {
5330                         params.sack_delay = jiffies_to_msecs(
5331                                 asoc->sackdelay);
5332                         params.sack_freq = asoc->sackfreq;
5333
5334                 } else {
5335                         params.sack_delay = 0;
5336                         params.sack_freq = 1;
5337                 }
5338         } else {
5339                 /* Fetch socket values. */
5340                 if (sp->param_flags & SPP_SACKDELAY_ENABLE) {
5341                         params.sack_delay  = sp->sackdelay;
5342                         params.sack_freq = sp->sackfreq;
5343                 } else {
5344                         params.sack_delay  = 0;
5345                         params.sack_freq = 1;
5346                 }
5347         }
5348
5349         if (copy_to_user(optval, &params, len))
5350                 return -EFAULT;
5351
5352         if (put_user(len, optlen))
5353                 return -EFAULT;
5354
5355         return 0;
5356 }
5357
5358 /* 7.1.3 Initialization Parameters (SCTP_INITMSG)
5359  *
5360  * Applications can specify protocol parameters for the default association
5361  * initialization.  The option name argument to setsockopt() and getsockopt()
5362  * is SCTP_INITMSG.
5363  *
5364  * Setting initialization parameters is effective only on an unconnected
5365  * socket (for UDP-style sockets only future associations are effected
5366  * by the change).  With TCP-style sockets, this option is inherited by
5367  * sockets derived from a listener socket.
5368  */
5369 static int sctp_getsockopt_initmsg(struct sock *sk, int len, char __user *optval, int __user *optlen)
5370 {
5371         if (len < sizeof(struct sctp_initmsg))
5372                 return -EINVAL;
5373         len = sizeof(struct sctp_initmsg);
5374         if (put_user(len, optlen))
5375                 return -EFAULT;
5376         if (copy_to_user(optval, &sctp_sk(sk)->initmsg, len))
5377                 return -EFAULT;
5378         return 0;
5379 }
5380
5381
5382 static int sctp_getsockopt_peer_addrs(struct sock *sk, int len,
5383                                       char __user *optval, int __user *optlen)
5384 {
5385         struct sctp_association *asoc;
5386         int cnt = 0;
5387         struct sctp_getaddrs getaddrs;
5388         struct sctp_transport *from;
5389         void __user *to;
5390         union sctp_addr temp;
5391         struct sctp_sock *sp = sctp_sk(sk);
5392         int addrlen;
5393         size_t space_left;
5394         int bytes_copied;
5395
5396         if (len < sizeof(struct sctp_getaddrs))
5397                 return -EINVAL;
5398
5399         if (copy_from_user(&getaddrs, optval, sizeof(struct sctp_getaddrs)))
5400                 return -EFAULT;
5401
5402         /* For UDP-style sockets, id specifies the association to query.  */
5403         asoc = sctp_id2assoc(sk, getaddrs.assoc_id);
5404         if (!asoc)
5405                 return -EINVAL;
5406
5407         to = optval + offsetof(struct sctp_getaddrs, addrs);
5408         space_left = len - offsetof(struct sctp_getaddrs, addrs);
5409
5410         list_for_each_entry(from, &asoc->peer.transport_addr_list,
5411                                 transports) {
5412                 memcpy(&temp, &from->ipaddr, sizeof(temp));
5413                 addrlen = sctp_get_pf_specific(sk->sk_family)
5414                               ->addr_to_user(sp, &temp);
5415                 if (space_left < addrlen)
5416                         return -ENOMEM;
5417                 if (copy_to_user(to, &temp, addrlen))
5418                         return -EFAULT;
5419                 to += addrlen;
5420                 cnt++;
5421                 space_left -= addrlen;
5422         }
5423
5424         if (put_user(cnt, &((struct sctp_getaddrs __user *)optval)->addr_num))
5425                 return -EFAULT;
5426         bytes_copied = ((char __user *)to) - optval;
5427         if (put_user(bytes_copied, optlen))
5428                 return -EFAULT;
5429
5430         return 0;
5431 }
5432
5433 static int sctp_copy_laddrs(struct sock *sk, __u16 port, void *to,
5434                             size_t space_left, int *bytes_copied)
5435 {
5436         struct sctp_sockaddr_entry *addr;
5437         union sctp_addr temp;
5438         int cnt = 0;
5439         int addrlen;
5440         struct net *net = sock_net(sk);
5441
5442         rcu_read_lock();
5443         list_for_each_entry_rcu(addr, &net->sctp.local_addr_list, list) {
5444                 if (!addr->valid)
5445                         continue;
5446
5447                 if ((PF_INET == sk->sk_family) &&
5448                     (AF_INET6 == addr->a.sa.sa_family))
5449                         continue;
5450                 if ((PF_INET6 == sk->sk_family) &&
5451                     inet_v6_ipv6only(sk) &&
5452                     (AF_INET == addr->a.sa.sa_family))
5453                         continue;
5454                 memcpy(&temp, &addr->a, sizeof(temp));
5455                 if (!temp.v4.sin_port)
5456                         temp.v4.sin_port = htons(port);
5457
5458                 addrlen = sctp_get_pf_specific(sk->sk_family)
5459                               ->addr_to_user(sctp_sk(sk), &temp);
5460
5461                 if (space_left < addrlen) {
5462                         cnt =  -ENOMEM;
5463                         break;
5464                 }
5465                 memcpy(to, &temp, addrlen);
5466
5467                 to += addrlen;
5468                 cnt++;
5469                 space_left -= addrlen;
5470                 *bytes_copied += addrlen;
5471         }
5472         rcu_read_unlock();
5473
5474         return cnt;
5475 }
5476
5477
5478 static int sctp_getsockopt_local_addrs(struct sock *sk, int len,
5479                                        char __user *optval, int __user *optlen)
5480 {
5481         struct sctp_bind_addr *bp;
5482         struct sctp_association *asoc;
5483         int cnt = 0;
5484         struct sctp_getaddrs getaddrs;
5485         struct sctp_sockaddr_entry *addr;
5486         void __user *to;
5487         union sctp_addr temp;
5488         struct sctp_sock *sp = sctp_sk(sk);
5489         int addrlen;
5490         int err = 0;
5491         size_t space_left;
5492         int bytes_copied = 0;
5493         void *addrs;
5494         void *buf;
5495
5496         if (len < sizeof(struct sctp_getaddrs))
5497                 return -EINVAL;
5498
5499         if (copy_from_user(&getaddrs, optval, sizeof(struct sctp_getaddrs)))
5500                 return -EFAULT;
5501
5502         /*
5503          *  For UDP-style sockets, id specifies the association to query.
5504          *  If the id field is set to the value '0' then the locally bound
5505          *  addresses are returned without regard to any particular
5506          *  association.
5507          */
5508         if (0 == getaddrs.assoc_id) {
5509                 bp = &sctp_sk(sk)->ep->base.bind_addr;
5510         } else {
5511                 asoc = sctp_id2assoc(sk, getaddrs.assoc_id);
5512                 if (!asoc)
5513                         return -EINVAL;
5514                 bp = &asoc->base.bind_addr;
5515         }
5516
5517         to = optval + offsetof(struct sctp_getaddrs, addrs);
5518         space_left = len - offsetof(struct sctp_getaddrs, addrs);
5519
5520         addrs = kmalloc(space_left, GFP_USER | __GFP_NOWARN);
5521         if (!addrs)
5522                 return -ENOMEM;
5523
5524         /* If the endpoint is bound to 0.0.0.0 or ::0, get the valid
5525          * addresses from the global local address list.
5526          */
5527         if (sctp_list_single_entry(&bp->address_list)) {
5528                 addr = list_entry(bp->address_list.next,
5529                                   struct sctp_sockaddr_entry, list);
5530                 if (sctp_is_any(sk, &addr->a)) {
5531                         cnt = sctp_copy_laddrs(sk, bp->port, addrs,
5532                                                 space_left, &bytes_copied);
5533                         if (cnt < 0) {
5534                                 err = cnt;
5535                                 goto out;
5536                         }
5537                         goto copy_getaddrs;
5538                 }
5539         }
5540
5541         buf = addrs;
5542         /* Protection on the bound address list is not needed since
5543          * in the socket option context we hold a socket lock and
5544          * thus the bound address list can't change.
5545          */
5546         list_for_each_entry(addr, &bp->address_list, list) {
5547                 memcpy(&temp, &addr->a, sizeof(temp));
5548                 addrlen = sctp_get_pf_specific(sk->sk_family)
5549                               ->addr_to_user(sp, &temp);
5550                 if (space_left < addrlen) {
5551                         err =  -ENOMEM; /*fixme: right error?*/
5552                         goto out;
5553                 }
5554                 memcpy(buf, &temp, addrlen);
5555                 buf += addrlen;
5556                 bytes_copied += addrlen;
5557                 cnt++;
5558                 space_left -= addrlen;
5559         }
5560
5561 copy_getaddrs:
5562         if (copy_to_user(to, addrs, bytes_copied)) {
5563                 err = -EFAULT;
5564                 goto out;
5565         }
5566         if (put_user(cnt, &((struct sctp_getaddrs __user *)optval)->addr_num)) {
5567                 err = -EFAULT;
5568                 goto out;
5569         }
5570         if (put_user(bytes_copied, optlen))
5571                 err = -EFAULT;
5572 out:
5573         kfree(addrs);
5574         return err;
5575 }
5576
5577 /* 7.1.10 Set Primary Address (SCTP_PRIMARY_ADDR)
5578  *
5579  * Requests that the local SCTP stack use the enclosed peer address as
5580  * the association primary.  The enclosed address must be one of the
5581  * association peer's addresses.
5582  */
5583 static int sctp_getsockopt_primary_addr(struct sock *sk, int len,
5584                                         char __user *optval, int __user *optlen)
5585 {
5586         struct sctp_prim prim;
5587         struct sctp_association *asoc;
5588         struct sctp_sock *sp = sctp_sk(sk);
5589
5590         if (len < sizeof(struct sctp_prim))
5591                 return -EINVAL;
5592
5593         len = sizeof(struct sctp_prim);
5594
5595         if (copy_from_user(&prim, optval, len))
5596                 return -EFAULT;
5597
5598         asoc = sctp_id2assoc(sk, prim.ssp_assoc_id);
5599         if (!asoc)
5600                 return -EINVAL;
5601
5602         if (!asoc->peer.primary_path)
5603                 return -ENOTCONN;
5604
5605         memcpy(&prim.ssp_addr, &asoc->peer.primary_path->ipaddr,
5606                 asoc->peer.primary_path->af_specific->sockaddr_len);
5607
5608         sctp_get_pf_specific(sk->sk_family)->addr_to_user(sp,
5609                         (union sctp_addr *)&prim.ssp_addr);
5610
5611         if (put_user(len, optlen))
5612                 return -EFAULT;
5613         if (copy_to_user(optval, &prim, len))
5614                 return -EFAULT;
5615
5616         return 0;
5617 }
5618
5619 /*
5620  * 7.1.11  Set Adaptation Layer Indicator (SCTP_ADAPTATION_LAYER)
5621  *
5622  * Requests that the local endpoint set the specified Adaptation Layer
5623  * Indication parameter for all future INIT and INIT-ACK exchanges.
5624  */
5625 static int sctp_getsockopt_adaptation_layer(struct sock *sk, int len,
5626                                   char __user *optval, int __user *optlen)
5627 {
5628         struct sctp_setadaptation adaptation;
5629
5630         if (len < sizeof(struct sctp_setadaptation))
5631                 return -EINVAL;
5632
5633         len = sizeof(struct sctp_setadaptation);
5634
5635         adaptation.ssb_adaptation_ind = sctp_sk(sk)->adaptation_ind;
5636
5637         if (put_user(len, optlen))
5638                 return -EFAULT;
5639         if (copy_to_user(optval, &adaptation, len))
5640                 return -EFAULT;
5641
5642         return 0;
5643 }
5644
5645 /*
5646  *
5647  * 7.1.14 Set default send parameters (SCTP_DEFAULT_SEND_PARAM)
5648  *
5649  *   Applications that wish to use the sendto() system call may wish to
5650  *   specify a default set of parameters that would normally be supplied
5651  *   through the inclusion of ancillary data.  This socket option allows
5652  *   such an application to set the default sctp_sndrcvinfo structure.
5653
5654
5655  *   The application that wishes to use this socket option simply passes
5656  *   in to this call the sctp_sndrcvinfo structure defined in Section
5657  *   5.2.2) The input parameters accepted by this call include
5658  *   sinfo_stream, sinfo_flags, sinfo_ppid, sinfo_context,
5659  *   sinfo_timetolive.  The user must provide the sinfo_assoc_id field in
5660  *   to this call if the caller is using the UDP model.
5661  *
5662  *   For getsockopt, it get the default sctp_sndrcvinfo structure.
5663  */
5664 static int sctp_getsockopt_default_send_param(struct sock *sk,
5665                                         int len, char __user *optval,
5666                                         int __user *optlen)
5667 {
5668         struct sctp_sock *sp = sctp_sk(sk);
5669         struct sctp_association *asoc;
5670         struct sctp_sndrcvinfo info;
5671
5672         if (len < sizeof(info))
5673                 return -EINVAL;
5674
5675         len = sizeof(info);
5676
5677         if (copy_from_user(&info, optval, len))
5678                 return -EFAULT;
5679
5680         asoc = sctp_id2assoc(sk, info.sinfo_assoc_id);
5681         if (!asoc && info.sinfo_assoc_id && sctp_style(sk, UDP))
5682                 return -EINVAL;
5683         if (asoc) {
5684                 info.sinfo_stream = asoc->default_stream;
5685                 info.sinfo_flags = asoc->default_flags;
5686                 info.sinfo_ppid = asoc->default_ppid;
5687                 info.sinfo_context = asoc->default_context;
5688                 info.sinfo_timetolive = asoc->default_timetolive;
5689         } else {
5690                 info.sinfo_stream = sp->default_stream;
5691                 info.sinfo_flags = sp->default_flags;
5692                 info.sinfo_ppid = sp->default_ppid;
5693                 info.sinfo_context = sp->default_context;
5694                 info.sinfo_timetolive = sp->default_timetolive;
5695         }
5696
5697         if (put_user(len, optlen))
5698                 return -EFAULT;
5699         if (copy_to_user(optval, &info, len))
5700                 return -EFAULT;
5701
5702         return 0;
5703 }
5704
5705 /* RFC6458, Section 8.1.31. Set/get Default Send Parameters
5706  * (SCTP_DEFAULT_SNDINFO)
5707  */
5708 static int sctp_getsockopt_default_sndinfo(struct sock *sk, int len,
5709                                            char __user *optval,
5710                                            int __user *optlen)
5711 {
5712         struct sctp_sock *sp = sctp_sk(sk);
5713         struct sctp_association *asoc;
5714         struct sctp_sndinfo info;
5715
5716         if (len < sizeof(info))
5717                 return -EINVAL;
5718
5719         len = sizeof(info);
5720
5721         if (copy_from_user(&info, optval, len))
5722                 return -EFAULT;
5723
5724         asoc = sctp_id2assoc(sk, info.snd_assoc_id);
5725         if (!asoc && info.snd_assoc_id && sctp_style(sk, UDP))
5726                 return -EINVAL;
5727         if (asoc) {
5728                 info.snd_sid = asoc->default_stream;
5729                 info.snd_flags = asoc->default_flags;
5730                 info.snd_ppid = asoc->default_ppid;
5731                 info.snd_context = asoc->default_context;
5732         } else {
5733                 info.snd_sid = sp->default_stream;
5734                 info.snd_flags = sp->default_flags;
5735                 info.snd_ppid = sp->default_ppid;
5736                 info.snd_context = sp->default_context;
5737         }
5738
5739         if (put_user(len, optlen))
5740                 return -EFAULT;
5741         if (copy_to_user(optval, &info, len))
5742                 return -EFAULT;
5743
5744         return 0;
5745 }
5746
5747 /*
5748  *
5749  * 7.1.5 SCTP_NODELAY
5750  *
5751  * Turn on/off any Nagle-like algorithm.  This means that packets are
5752  * generally sent as soon as possible and no unnecessary delays are
5753  * introduced, at the cost of more packets in the network.  Expects an
5754  * integer boolean flag.
5755  */
5756
5757 static int sctp_getsockopt_nodelay(struct sock *sk, int len,
5758                                    char __user *optval, int __user *optlen)
5759 {
5760         int val;
5761
5762         if (len < sizeof(int))
5763                 return -EINVAL;
5764
5765         len = sizeof(int);
5766         val = (sctp_sk(sk)->nodelay == 1);
5767         if (put_user(len, optlen))
5768                 return -EFAULT;
5769         if (copy_to_user(optval, &val, len))
5770                 return -EFAULT;
5771         return 0;
5772 }
5773
5774 /*
5775  *
5776  * 7.1.1 SCTP_RTOINFO
5777  *
5778  * The protocol parameters used to initialize and bound retransmission
5779  * timeout (RTO) are tunable. sctp_rtoinfo structure is used to access
5780  * and modify these parameters.
5781  * All parameters are time values, in milliseconds.  A value of 0, when
5782  * modifying the parameters, indicates that the current value should not
5783  * be changed.
5784  *
5785  */
5786 static int sctp_getsockopt_rtoinfo(struct sock *sk, int len,
5787                                 char __user *optval,
5788                                 int __user *optlen) {
5789         struct sctp_rtoinfo rtoinfo;
5790         struct sctp_association *asoc;
5791
5792         if (len < sizeof (struct sctp_rtoinfo))
5793                 return -EINVAL;
5794
5795         len = sizeof(struct sctp_rtoinfo);
5796
5797         if (copy_from_user(&rtoinfo, optval, len))
5798                 return -EFAULT;
5799
5800         asoc = sctp_id2assoc(sk, rtoinfo.srto_assoc_id);
5801
5802         if (!asoc && rtoinfo.srto_assoc_id && sctp_style(sk, UDP))
5803                 return -EINVAL;
5804
5805         /* Values corresponding to the specific association. */
5806         if (asoc) {
5807                 rtoinfo.srto_initial = jiffies_to_msecs(asoc->rto_initial);
5808                 rtoinfo.srto_max = jiffies_to_msecs(asoc->rto_max);
5809                 rtoinfo.srto_min = jiffies_to_msecs(asoc->rto_min);
5810         } else {
5811                 /* Values corresponding to the endpoint. */
5812                 struct sctp_sock *sp = sctp_sk(sk);
5813
5814                 rtoinfo.srto_initial = sp->rtoinfo.srto_initial;
5815                 rtoinfo.srto_max = sp->rtoinfo.srto_max;
5816                 rtoinfo.srto_min = sp->rtoinfo.srto_min;
5817         }
5818
5819         if (put_user(len, optlen))
5820                 return -EFAULT;
5821
5822         if (copy_to_user(optval, &rtoinfo, len))
5823                 return -EFAULT;
5824
5825         return 0;
5826 }
5827
5828 /*
5829  *
5830  * 7.1.2 SCTP_ASSOCINFO
5831  *
5832  * This option is used to tune the maximum retransmission attempts
5833  * of the association.
5834  * Returns an error if the new association retransmission value is
5835  * greater than the sum of the retransmission value  of the peer.
5836  * See [SCTP] for more information.
5837  *
5838  */
5839 static int sctp_getsockopt_associnfo(struct sock *sk, int len,
5840                                      char __user *optval,
5841                                      int __user *optlen)
5842 {
5843
5844         struct sctp_assocparams assocparams;
5845         struct sctp_association *asoc;
5846         struct list_head *pos;
5847         int cnt = 0;
5848
5849         if (len < sizeof (struct sctp_assocparams))
5850                 return -EINVAL;
5851
5852         len = sizeof(struct sctp_assocparams);
5853
5854         if (copy_from_user(&assocparams, optval, len))
5855                 return -EFAULT;
5856
5857         asoc = sctp_id2assoc(sk, assocparams.sasoc_assoc_id);
5858
5859         if (!asoc && assocparams.sasoc_assoc_id && sctp_style(sk, UDP))
5860                 return -EINVAL;
5861
5862         /* Values correspoinding to the specific association */
5863         if (asoc) {
5864                 assocparams.sasoc_asocmaxrxt = asoc->max_retrans;
5865                 assocparams.sasoc_peer_rwnd = asoc->peer.rwnd;
5866                 assocparams.sasoc_local_rwnd = asoc->a_rwnd;
5867                 assocparams.sasoc_cookie_life = ktime_to_ms(asoc->cookie_life);
5868
5869                 list_for_each(pos, &asoc->peer.transport_addr_list) {
5870                         cnt++;
5871                 }
5872
5873                 assocparams.sasoc_number_peer_destinations = cnt;
5874         } else {
5875                 /* Values corresponding to the endpoint */
5876                 struct sctp_sock *sp = sctp_sk(sk);
5877
5878                 assocparams.sasoc_asocmaxrxt = sp->assocparams.sasoc_asocmaxrxt;
5879                 assocparams.sasoc_peer_rwnd = sp->assocparams.sasoc_peer_rwnd;
5880                 assocparams.sasoc_local_rwnd = sp->assocparams.sasoc_local_rwnd;
5881                 assocparams.sasoc_cookie_life =
5882                                         sp->assocparams.sasoc_cookie_life;
5883                 assocparams.sasoc_number_peer_destinations =
5884                                         sp->assocparams.
5885                                         sasoc_number_peer_destinations;
5886         }
5887
5888         if (put_user(len, optlen))
5889                 return -EFAULT;
5890
5891         if (copy_to_user(optval, &assocparams, len))
5892                 return -EFAULT;
5893
5894         return 0;
5895 }
5896
5897 /*
5898  * 7.1.16 Set/clear IPv4 mapped addresses (SCTP_I_WANT_MAPPED_V4_ADDR)
5899  *
5900  * This socket option is a boolean flag which turns on or off mapped V4
5901  * addresses.  If this option is turned on and the socket is type
5902  * PF_INET6, then IPv4 addresses will be mapped to V6 representation.
5903  * If this option is turned off, then no mapping will be done of V4
5904  * addresses and a user will receive both PF_INET6 and PF_INET type
5905  * addresses on the socket.
5906  */
5907 static int sctp_getsockopt_mappedv4(struct sock *sk, int len,
5908                                     char __user *optval, int __user *optlen)
5909 {
5910         int val;
5911         struct sctp_sock *sp = sctp_sk(sk);
5912
5913         if (len < sizeof(int))
5914                 return -EINVAL;
5915
5916         len = sizeof(int);
5917         val = sp->v4mapped;
5918         if (put_user(len, optlen))
5919                 return -EFAULT;
5920         if (copy_to_user(optval, &val, len))
5921                 return -EFAULT;
5922
5923         return 0;
5924 }
5925
5926 /*
5927  * 7.1.29.  Set or Get the default context (SCTP_CONTEXT)
5928  * (chapter and verse is quoted at sctp_setsockopt_context())
5929  */
5930 static int sctp_getsockopt_context(struct sock *sk, int len,
5931                                    char __user *optval, int __user *optlen)
5932 {
5933         struct sctp_assoc_value params;
5934         struct sctp_sock *sp;
5935         struct sctp_association *asoc;
5936
5937         if (len < sizeof(struct sctp_assoc_value))
5938                 return -EINVAL;
5939
5940         len = sizeof(struct sctp_assoc_value);
5941
5942         if (copy_from_user(&params, optval, len))
5943                 return -EFAULT;
5944
5945         sp = sctp_sk(sk);
5946
5947         if (params.assoc_id != 0) {
5948                 asoc = sctp_id2assoc(sk, params.assoc_id);
5949                 if (!asoc)
5950                         return -EINVAL;
5951                 params.assoc_value = asoc->default_rcv_context;
5952         } else {
5953                 params.assoc_value = sp->default_rcv_context;
5954         }
5955
5956         if (put_user(len, optlen))
5957                 return -EFAULT;
5958         if (copy_to_user(optval, &params, len))
5959                 return -EFAULT;
5960
5961         return 0;
5962 }
5963
5964 /*
5965  * 8.1.16.  Get or Set the Maximum Fragmentation Size (SCTP_MAXSEG)
5966  * This option will get or set the maximum size to put in any outgoing
5967  * SCTP DATA chunk.  If a message is larger than this size it will be
5968  * fragmented by SCTP into the specified size.  Note that the underlying
5969  * SCTP implementation may fragment into smaller sized chunks when the
5970  * PMTU of the underlying association is smaller than the value set by
5971  * the user.  The default value for this option is '0' which indicates
5972  * the user is NOT limiting fragmentation and only the PMTU will effect
5973  * SCTP's choice of DATA chunk size.  Note also that values set larger
5974  * than the maximum size of an IP datagram will effectively let SCTP
5975  * control fragmentation (i.e. the same as setting this option to 0).
5976  *
5977  * The following structure is used to access and modify this parameter:
5978  *
5979  * struct sctp_assoc_value {
5980  *   sctp_assoc_t assoc_id;
5981  *   uint32_t assoc_value;
5982  * };
5983  *
5984  * assoc_id:  This parameter is ignored for one-to-one style sockets.
5985  *    For one-to-many style sockets this parameter indicates which
5986  *    association the user is performing an action upon.  Note that if
5987  *    this field's value is zero then the endpoints default value is
5988  *    changed (effecting future associations only).
5989  * assoc_value:  This parameter specifies the maximum size in bytes.
5990  */
5991 static int sctp_getsockopt_maxseg(struct sock *sk, int len,
5992                                   char __user *optval, int __user *optlen)
5993 {
5994         struct sctp_assoc_value params;
5995         struct sctp_association *asoc;
5996
5997         if (len == sizeof(int)) {
5998                 pr_warn_ratelimited(DEPRECATED
5999                                     "%s (pid %d) "
6000                                     "Use of int in maxseg socket option.\n"
6001                                     "Use struct sctp_assoc_value instead\n",
6002                                     current->comm, task_pid_nr(current));
6003                 params.assoc_id = 0;
6004         } else if (len >= sizeof(struct sctp_assoc_value)) {
6005                 len = sizeof(struct sctp_assoc_value);
6006                 if (copy_from_user(&params, optval, sizeof(params)))
6007                         return -EFAULT;
6008         } else
6009                 return -EINVAL;
6010
6011         asoc = sctp_id2assoc(sk, params.assoc_id);
6012         if (!asoc && params.assoc_id && sctp_style(sk, UDP))
6013                 return -EINVAL;
6014
6015         if (asoc)
6016                 params.assoc_value = asoc->frag_point;
6017         else
6018                 params.assoc_value = sctp_sk(sk)->user_frag;
6019
6020         if (put_user(len, optlen))
6021                 return -EFAULT;
6022         if (len == sizeof(int)) {
6023                 if (copy_to_user(optval, &params.assoc_value, len))
6024                         return -EFAULT;
6025         } else {
6026                 if (copy_to_user(optval, &params, len))
6027                         return -EFAULT;
6028         }
6029
6030         return 0;
6031 }
6032
6033 /*
6034  * 7.1.24.  Get or set fragmented interleave (SCTP_FRAGMENT_INTERLEAVE)
6035  * (chapter and verse is quoted at sctp_setsockopt_fragment_interleave())
6036  */
6037 static int sctp_getsockopt_fragment_interleave(struct sock *sk, int len,
6038                                                char __user *optval, int __user *optlen)
6039 {
6040         int val;
6041
6042         if (len < sizeof(int))
6043                 return -EINVAL;
6044
6045         len = sizeof(int);
6046
6047         val = sctp_sk(sk)->frag_interleave;
6048         if (put_user(len, optlen))
6049                 return -EFAULT;
6050         if (copy_to_user(optval, &val, len))
6051                 return -EFAULT;
6052
6053         return 0;
6054 }
6055
6056 /*
6057  * 7.1.25.  Set or Get the sctp partial delivery point
6058  * (chapter and verse is quoted at sctp_setsockopt_partial_delivery_point())
6059  */
6060 static int sctp_getsockopt_partial_delivery_point(struct sock *sk, int len,
6061                                                   char __user *optval,
6062                                                   int __user *optlen)
6063 {
6064         u32 val;
6065
6066         if (len < sizeof(u32))
6067                 return -EINVAL;
6068
6069         len = sizeof(u32);
6070
6071         val = sctp_sk(sk)->pd_point;
6072         if (put_user(len, optlen))
6073                 return -EFAULT;
6074         if (copy_to_user(optval, &val, len))
6075                 return -EFAULT;
6076
6077         return 0;
6078 }
6079
6080 /*
6081  * 7.1.28.  Set or Get the maximum burst (SCTP_MAX_BURST)
6082  * (chapter and verse is quoted at sctp_setsockopt_maxburst())
6083  */
6084 static int sctp_getsockopt_maxburst(struct sock *sk, int len,
6085                                     char __user *optval,
6086                                     int __user *optlen)
6087 {
6088         struct sctp_assoc_value params;
6089         struct sctp_sock *sp;
6090         struct sctp_association *asoc;
6091
6092         if (len == sizeof(int)) {
6093                 pr_warn_ratelimited(DEPRECATED
6094                                     "%s (pid %d) "
6095                                     "Use of int in max_burst socket option.\n"
6096                                     "Use struct sctp_assoc_value instead\n",
6097                                     current->comm, task_pid_nr(current));
6098                 params.assoc_id = 0;
6099         } else if (len >= sizeof(struct sctp_assoc_value)) {
6100                 len = sizeof(struct sctp_assoc_value);
6101                 if (copy_from_user(&params, optval, len))
6102                         return -EFAULT;
6103         } else
6104                 return -EINVAL;
6105
6106         sp = sctp_sk(sk);
6107
6108         if (params.assoc_id != 0) {
6109                 asoc = sctp_id2assoc(sk, params.assoc_id);
6110                 if (!asoc)
6111                         return -EINVAL;
6112                 params.assoc_value = asoc->max_burst;
6113         } else
6114                 params.assoc_value = sp->max_burst;
6115
6116         if (len == sizeof(int)) {
6117                 if (copy_to_user(optval, &params.assoc_value, len))
6118                         return -EFAULT;
6119         } else {
6120                 if (copy_to_user(optval, &params, len))
6121                         return -EFAULT;
6122         }
6123
6124         return 0;
6125
6126 }
6127
6128 static int sctp_getsockopt_hmac_ident(struct sock *sk, int len,
6129                                     char __user *optval, int __user *optlen)
6130 {
6131         struct sctp_endpoint *ep = sctp_sk(sk)->ep;
6132         struct sctp_hmacalgo  __user *p = (void __user *)optval;
6133         struct sctp_hmac_algo_param *hmacs;
6134         __u16 data_len = 0;
6135         u32 num_idents;
6136         int i;
6137
6138         if (!ep->auth_enable)
6139                 return -EACCES;
6140
6141         hmacs = ep->auth_hmacs_list;
6142         data_len = ntohs(hmacs->param_hdr.length) -
6143                    sizeof(struct sctp_paramhdr);
6144
6145         if (len < sizeof(struct sctp_hmacalgo) + data_len)
6146                 return -EINVAL;
6147
6148         len = sizeof(struct sctp_hmacalgo) + data_len;
6149         num_idents = data_len / sizeof(u16);
6150
6151         if (put_user(len, optlen))
6152                 return -EFAULT;
6153         if (put_user(num_idents, &p->shmac_num_idents))
6154                 return -EFAULT;
6155         for (i = 0; i < num_idents; i++) {
6156                 __u16 hmacid = ntohs(hmacs->hmac_ids[i]);
6157
6158                 if (copy_to_user(&p->shmac_idents[i], &hmacid, sizeof(__u16)))
6159                         return -EFAULT;
6160         }
6161         return 0;
6162 }
6163
6164 static int sctp_getsockopt_active_key(struct sock *sk, int len,
6165                                     char __user *optval, int __user *optlen)
6166 {
6167         struct sctp_endpoint *ep = sctp_sk(sk)->ep;
6168         struct sctp_authkeyid val;
6169         struct sctp_association *asoc;
6170
6171         if (!ep->auth_enable)
6172                 return -EACCES;
6173
6174         if (len < sizeof(struct sctp_authkeyid))
6175                 return -EINVAL;
6176         if (copy_from_user(&val, optval, sizeof(struct sctp_authkeyid)))
6177                 return -EFAULT;
6178
6179         asoc = sctp_id2assoc(sk, val.scact_assoc_id);
6180         if (!asoc && val.scact_assoc_id && sctp_style(sk, UDP))
6181                 return -EINVAL;
6182
6183         if (asoc)
6184                 val.scact_keynumber = asoc->active_key_id;
6185         else
6186                 val.scact_keynumber = ep->active_key_id;
6187
6188         len = sizeof(struct sctp_authkeyid);
6189         if (put_user(len, optlen))
6190                 return -EFAULT;
6191         if (copy_to_user(optval, &val, len))
6192                 return -EFAULT;
6193
6194         return 0;
6195 }
6196
6197 static int sctp_getsockopt_peer_auth_chunks(struct sock *sk, int len,
6198                                     char __user *optval, int __user *optlen)
6199 {
6200         struct sctp_endpoint *ep = sctp_sk(sk)->ep;
6201         struct sctp_authchunks __user *p = (void __user *)optval;
6202         struct sctp_authchunks val;
6203         struct sctp_association *asoc;
6204         struct sctp_chunks_param *ch;
6205         u32    num_chunks = 0;
6206         char __user *to;
6207
6208         if (!ep->auth_enable)
6209                 return -EACCES;
6210
6211         if (len < sizeof(struct sctp_authchunks))
6212                 return -EINVAL;
6213
6214         if (copy_from_user(&val, optval, sizeof(struct sctp_authchunks)))
6215                 return -EFAULT;
6216
6217         to = p->gauth_chunks;
6218         asoc = sctp_id2assoc(sk, val.gauth_assoc_id);
6219         if (!asoc)
6220                 return -EINVAL;
6221
6222         ch = asoc->peer.peer_chunks;
6223         if (!ch)
6224                 goto num;
6225
6226         /* See if the user provided enough room for all the data */
6227         num_chunks = ntohs(ch->param_hdr.length) - sizeof(struct sctp_paramhdr);
6228         if (len < num_chunks)
6229                 return -EINVAL;
6230
6231         if (copy_to_user(to, ch->chunks, num_chunks))
6232                 return -EFAULT;
6233 num:
6234         len = sizeof(struct sctp_authchunks) + num_chunks;
6235         if (put_user(len, optlen))
6236                 return -EFAULT;
6237         if (put_user(num_chunks, &p->gauth_number_of_chunks))
6238                 return -EFAULT;
6239         return 0;
6240 }
6241
6242 static int sctp_getsockopt_local_auth_chunks(struct sock *sk, int len,
6243                                     char __user *optval, int __user *optlen)
6244 {
6245         struct sctp_endpoint *ep = sctp_sk(sk)->ep;
6246         struct sctp_authchunks __user *p = (void __user *)optval;
6247         struct sctp_authchunks val;
6248         struct sctp_association *asoc;
6249         struct sctp_chunks_param *ch;
6250         u32    num_chunks = 0;
6251         char __user *to;
6252
6253         if (!ep->auth_enable)
6254                 return -EACCES;
6255
6256         if (len < sizeof(struct sctp_authchunks))
6257                 return -EINVAL;
6258
6259         if (copy_from_user(&val, optval, sizeof(struct sctp_authchunks)))
6260                 return -EFAULT;
6261
6262         to = p->gauth_chunks;
6263         asoc = sctp_id2assoc(sk, val.gauth_assoc_id);
6264         if (!asoc && val.gauth_assoc_id && sctp_style(sk, UDP))
6265                 return -EINVAL;
6266
6267         if (asoc)
6268                 ch = (struct sctp_chunks_param *)asoc->c.auth_chunks;
6269         else
6270                 ch = ep->auth_chunk_list;
6271
6272         if (!ch)
6273                 goto num;
6274
6275         num_chunks = ntohs(ch->param_hdr.length) - sizeof(struct sctp_paramhdr);
6276         if (len < sizeof(struct sctp_authchunks) + num_chunks)
6277                 return -EINVAL;
6278
6279         if (copy_to_user(to, ch->chunks, num_chunks))
6280                 return -EFAULT;
6281 num:
6282         len = sizeof(struct sctp_authchunks) + num_chunks;
6283         if (put_user(len, optlen))
6284                 return -EFAULT;
6285         if (put_user(num_chunks, &p->gauth_number_of_chunks))
6286                 return -EFAULT;
6287
6288         return 0;
6289 }
6290
6291 /*
6292  * 8.2.5.  Get the Current Number of Associations (SCTP_GET_ASSOC_NUMBER)
6293  * This option gets the current number of associations that are attached
6294  * to a one-to-many style socket.  The option value is an uint32_t.
6295  */
6296 static int sctp_getsockopt_assoc_number(struct sock *sk, int len,
6297                                     char __user *optval, int __user *optlen)
6298 {
6299         struct sctp_sock *sp = sctp_sk(sk);
6300         struct sctp_association *asoc;
6301         u32 val = 0;
6302
6303         if (sctp_style(sk, TCP))
6304                 return -EOPNOTSUPP;
6305
6306         if (len < sizeof(u32))
6307                 return -EINVAL;
6308
6309         len = sizeof(u32);
6310
6311         list_for_each_entry(asoc, &(sp->ep->asocs), asocs) {
6312                 val++;
6313         }
6314
6315         if (put_user(len, optlen))
6316                 return -EFAULT;
6317         if (copy_to_user(optval, &val, len))
6318                 return -EFAULT;
6319
6320         return 0;
6321 }
6322
6323 /*
6324  * 8.1.23 SCTP_AUTO_ASCONF
6325  * See the corresponding setsockopt entry as description
6326  */
6327 static int sctp_getsockopt_auto_asconf(struct sock *sk, int len,
6328                                    char __user *optval, int __user *optlen)
6329 {
6330         int val = 0;
6331
6332         if (len < sizeof(int))
6333                 return -EINVAL;
6334
6335         len = sizeof(int);
6336         if (sctp_sk(sk)->do_auto_asconf && sctp_is_ep_boundall(sk))
6337                 val = 1;
6338         if (put_user(len, optlen))
6339                 return -EFAULT;
6340         if (copy_to_user(optval, &val, len))
6341                 return -EFAULT;
6342         return 0;
6343 }
6344
6345 /*
6346  * 8.2.6. Get the Current Identifiers of Associations
6347  *        (SCTP_GET_ASSOC_ID_LIST)
6348  *
6349  * This option gets the current list of SCTP association identifiers of
6350  * the SCTP associations handled by a one-to-many style socket.
6351  */
6352 static int sctp_getsockopt_assoc_ids(struct sock *sk, int len,
6353                                     char __user *optval, int __user *optlen)
6354 {
6355         struct sctp_sock *sp = sctp_sk(sk);
6356         struct sctp_association *asoc;
6357         struct sctp_assoc_ids *ids;
6358         u32 num = 0;
6359
6360         if (sctp_style(sk, TCP))
6361                 return -EOPNOTSUPP;
6362
6363         if (len < sizeof(struct sctp_assoc_ids))
6364                 return -EINVAL;
6365
6366         list_for_each_entry(asoc, &(sp->ep->asocs), asocs) {
6367                 num++;
6368         }
6369
6370         if (len < sizeof(struct sctp_assoc_ids) + sizeof(sctp_assoc_t) * num)
6371                 return -EINVAL;
6372
6373         len = sizeof(struct sctp_assoc_ids) + sizeof(sctp_assoc_t) * num;
6374
6375         ids = kmalloc(len, GFP_USER | __GFP_NOWARN);
6376         if (unlikely(!ids))
6377                 return -ENOMEM;
6378
6379         ids->gaids_number_of_ids = num;
6380         num = 0;
6381         list_for_each_entry(asoc, &(sp->ep->asocs), asocs) {
6382                 ids->gaids_assoc_id[num++] = asoc->assoc_id;
6383         }
6384
6385         if (put_user(len, optlen) || copy_to_user(optval, ids, len)) {
6386                 kfree(ids);
6387                 return -EFAULT;
6388         }
6389
6390         kfree(ids);
6391         return 0;
6392 }
6393
6394 /*
6395  * SCTP_PEER_ADDR_THLDS
6396  *
6397  * This option allows us to fetch the partially failed threshold for one or all
6398  * transports in an association.  See Section 6.1 of:
6399  * http://www.ietf.org/id/draft-nishida-tsvwg-sctp-failover-05.txt
6400  */
6401 static int sctp_getsockopt_paddr_thresholds(struct sock *sk,
6402                                             char __user *optval,
6403                                             int len,
6404                                             int __user *optlen)
6405 {
6406         struct sctp_paddrthlds val;
6407         struct sctp_transport *trans;
6408         struct sctp_association *asoc;
6409
6410         if (len < sizeof(struct sctp_paddrthlds))
6411                 return -EINVAL;
6412         len = sizeof(struct sctp_paddrthlds);
6413         if (copy_from_user(&val, (struct sctp_paddrthlds __user *)optval, len))
6414                 return -EFAULT;
6415
6416         if (sctp_is_any(sk, (const union sctp_addr *)&val.spt_address)) {
6417                 asoc = sctp_id2assoc(sk, val.spt_assoc_id);
6418                 if (!asoc)
6419                         return -ENOENT;
6420
6421                 val.spt_pathpfthld = asoc->pf_retrans;
6422                 val.spt_pathmaxrxt = asoc->pathmaxrxt;
6423         } else {
6424                 trans = sctp_addr_id2transport(sk, &val.spt_address,
6425                                                val.spt_assoc_id);
6426                 if (!trans)
6427                         return -ENOENT;
6428
6429                 val.spt_pathmaxrxt = trans->pathmaxrxt;
6430                 val.spt_pathpfthld = trans->pf_retrans;
6431         }
6432
6433         if (put_user(len, optlen) || copy_to_user(optval, &val, len))
6434                 return -EFAULT;
6435
6436         return 0;
6437 }
6438
6439 /*
6440  * SCTP_GET_ASSOC_STATS
6441  *
6442  * This option retrieves local per endpoint statistics. It is modeled
6443  * after OpenSolaris' implementation
6444  */
6445 static int sctp_getsockopt_assoc_stats(struct sock *sk, int len,
6446                                        char __user *optval,
6447                                        int __user *optlen)
6448 {
6449         struct sctp_assoc_stats sas;
6450         struct sctp_association *asoc = NULL;
6451
6452         /* User must provide at least the assoc id */
6453         if (len < sizeof(sctp_assoc_t))
6454                 return -EINVAL;
6455
6456         /* Allow the struct to grow and fill in as much as possible */
6457         len = min_t(size_t, len, sizeof(sas));
6458
6459         if (copy_from_user(&sas, optval, len))
6460                 return -EFAULT;
6461
6462         asoc = sctp_id2assoc(sk, sas.sas_assoc_id);
6463         if (!asoc)
6464                 return -EINVAL;
6465
6466         sas.sas_rtxchunks = asoc->stats.rtxchunks;
6467         sas.sas_gapcnt = asoc->stats.gapcnt;
6468         sas.sas_outofseqtsns = asoc->stats.outofseqtsns;
6469         sas.sas_osacks = asoc->stats.osacks;
6470         sas.sas_isacks = asoc->stats.isacks;
6471         sas.sas_octrlchunks = asoc->stats.octrlchunks;
6472         sas.sas_ictrlchunks = asoc->stats.ictrlchunks;
6473         sas.sas_oodchunks = asoc->stats.oodchunks;
6474         sas.sas_iodchunks = asoc->stats.iodchunks;
6475         sas.sas_ouodchunks = asoc->stats.ouodchunks;
6476         sas.sas_iuodchunks = asoc->stats.iuodchunks;
6477         sas.sas_idupchunks = asoc->stats.idupchunks;
6478         sas.sas_opackets = asoc->stats.opackets;
6479         sas.sas_ipackets = asoc->stats.ipackets;
6480
6481         /* New high max rto observed, will return 0 if not a single
6482          * RTO update took place. obs_rto_ipaddr will be bogus
6483          * in such a case
6484          */
6485         sas.sas_maxrto = asoc->stats.max_obs_rto;
6486         memcpy(&sas.sas_obs_rto_ipaddr, &asoc->stats.obs_rto_ipaddr,
6487                 sizeof(struct sockaddr_storage));
6488
6489         /* Mark beginning of a new observation period */
6490         asoc->stats.max_obs_rto = asoc->rto_min;
6491
6492         if (put_user(len, optlen))
6493                 return -EFAULT;
6494
6495         pr_debug("%s: len:%d, assoc_id:%d\n", __func__, len, sas.sas_assoc_id);
6496
6497         if (copy_to_user(optval, &sas, len))
6498                 return -EFAULT;
6499
6500         return 0;
6501 }
6502
6503 static int sctp_getsockopt_recvrcvinfo(struct sock *sk, int len,
6504                                        char __user *optval,
6505                                        int __user *optlen)
6506 {
6507         int val = 0;
6508
6509         if (len < sizeof(int))
6510                 return -EINVAL;
6511
6512         len = sizeof(int);
6513         if (sctp_sk(sk)->recvrcvinfo)
6514                 val = 1;
6515         if (put_user(len, optlen))
6516                 return -EFAULT;
6517         if (copy_to_user(optval, &val, len))
6518                 return -EFAULT;
6519
6520         return 0;
6521 }
6522
6523 static int sctp_getsockopt_recvnxtinfo(struct sock *sk, int len,
6524                                        char __user *optval,
6525                                        int __user *optlen)
6526 {
6527         int val = 0;
6528
6529         if (len < sizeof(int))
6530                 return -EINVAL;
6531
6532         len = sizeof(int);
6533         if (sctp_sk(sk)->recvnxtinfo)
6534                 val = 1;
6535         if (put_user(len, optlen))
6536                 return -EFAULT;
6537         if (copy_to_user(optval, &val, len))
6538                 return -EFAULT;
6539
6540         return 0;
6541 }
6542
6543 static int sctp_getsockopt_pr_supported(struct sock *sk, int len,
6544                                         char __user *optval,
6545                                         int __user *optlen)
6546 {
6547         struct sctp_assoc_value params;
6548         struct sctp_association *asoc;
6549         int retval = -EFAULT;
6550
6551         if (len < sizeof(params)) {
6552                 retval = -EINVAL;
6553                 goto out;
6554         }
6555
6556         len = sizeof(params);
6557         if (copy_from_user(&params, optval, len))
6558                 goto out;
6559
6560         asoc = sctp_id2assoc(sk, params.assoc_id);
6561         if (asoc) {
6562                 params.assoc_value = asoc->prsctp_enable;
6563         } else if (!params.assoc_id) {
6564                 struct sctp_sock *sp = sctp_sk(sk);
6565
6566                 params.assoc_value = sp->ep->prsctp_enable;
6567         } else {
6568                 retval = -EINVAL;
6569                 goto out;
6570         }
6571
6572         if (put_user(len, optlen))
6573                 goto out;
6574
6575         if (copy_to_user(optval, &params, len))
6576                 goto out;
6577
6578         retval = 0;
6579
6580 out:
6581         return retval;
6582 }
6583
6584 static int sctp_getsockopt_default_prinfo(struct sock *sk, int len,
6585                                           char __user *optval,
6586                                           int __user *optlen)
6587 {
6588         struct sctp_default_prinfo info;
6589         struct sctp_association *asoc;
6590         int retval = -EFAULT;
6591
6592         if (len < sizeof(info)) {
6593                 retval = -EINVAL;
6594                 goto out;
6595         }
6596
6597         len = sizeof(info);
6598         if (copy_from_user(&info, optval, len))
6599                 goto out;
6600
6601         asoc = sctp_id2assoc(sk, info.pr_assoc_id);
6602         if (asoc) {
6603                 info.pr_policy = SCTP_PR_POLICY(asoc->default_flags);
6604                 info.pr_value = asoc->default_timetolive;
6605         } else if (!info.pr_assoc_id) {
6606                 struct sctp_sock *sp = sctp_sk(sk);
6607
6608                 info.pr_policy = SCTP_PR_POLICY(sp->default_flags);
6609                 info.pr_value = sp->default_timetolive;
6610         } else {
6611                 retval = -EINVAL;
6612                 goto out;
6613         }
6614
6615         if (put_user(len, optlen))
6616                 goto out;
6617
6618         if (copy_to_user(optval, &info, len))
6619                 goto out;
6620
6621         retval = 0;
6622
6623 out:
6624         return retval;
6625 }
6626
6627 static int sctp_getsockopt_pr_assocstatus(struct sock *sk, int len,
6628                                           char __user *optval,
6629                                           int __user *optlen)
6630 {
6631         struct sctp_prstatus params;
6632         struct sctp_association *asoc;
6633         int policy;
6634         int retval = -EINVAL;
6635
6636         if (len < sizeof(params))
6637                 goto out;
6638
6639         len = sizeof(params);
6640         if (copy_from_user(&params, optval, len)) {
6641                 retval = -EFAULT;
6642                 goto out;
6643         }
6644
6645         policy = params.sprstat_policy;
6646         if (policy & ~SCTP_PR_SCTP_MASK)
6647                 goto out;
6648
6649         asoc = sctp_id2assoc(sk, params.sprstat_assoc_id);
6650         if (!asoc)
6651                 goto out;
6652
6653         if (policy == SCTP_PR_SCTP_NONE) {
6654                 params.sprstat_abandoned_unsent = 0;
6655                 params.sprstat_abandoned_sent = 0;
6656                 for (policy = 0; policy <= SCTP_PR_INDEX(MAX); policy++) {
6657                         params.sprstat_abandoned_unsent +=
6658                                 asoc->abandoned_unsent[policy];
6659                         params.sprstat_abandoned_sent +=
6660                                 asoc->abandoned_sent[policy];
6661                 }
6662         } else {
6663                 params.sprstat_abandoned_unsent =
6664                         asoc->abandoned_unsent[__SCTP_PR_INDEX(policy)];
6665                 params.sprstat_abandoned_sent =
6666                         asoc->abandoned_sent[__SCTP_PR_INDEX(policy)];
6667         }
6668
6669         if (put_user(len, optlen)) {
6670                 retval = -EFAULT;
6671                 goto out;
6672         }
6673
6674         if (copy_to_user(optval, &params, len)) {
6675                 retval = -EFAULT;
6676                 goto out;
6677         }
6678
6679         retval = 0;
6680
6681 out:
6682         return retval;
6683 }
6684
6685 static int sctp_getsockopt_pr_streamstatus(struct sock *sk, int len,
6686                                            char __user *optval,
6687                                            int __user *optlen)
6688 {
6689         struct sctp_stream_out_ext *streamoute;
6690         struct sctp_association *asoc;
6691         struct sctp_prstatus params;
6692         int retval = -EINVAL;
6693         int policy;
6694
6695         if (len < sizeof(params))
6696                 goto out;
6697
6698         len = sizeof(params);
6699         if (copy_from_user(&params, optval, len)) {
6700                 retval = -EFAULT;
6701                 goto out;
6702         }
6703
6704         policy = params.sprstat_policy;
6705         if (policy & ~SCTP_PR_SCTP_MASK)
6706                 goto out;
6707
6708         asoc = sctp_id2assoc(sk, params.sprstat_assoc_id);
6709         if (!asoc || params.sprstat_sid >= asoc->stream.outcnt)
6710                 goto out;
6711
6712         streamoute = asoc->stream.out[params.sprstat_sid].ext;
6713         if (!streamoute) {
6714                 /* Not allocated yet, means all stats are 0 */
6715                 params.sprstat_abandoned_unsent = 0;
6716                 params.sprstat_abandoned_sent = 0;
6717                 retval = 0;
6718                 goto out;
6719         }
6720
6721         if (policy == SCTP_PR_SCTP_NONE) {
6722                 params.sprstat_abandoned_unsent = 0;
6723                 params.sprstat_abandoned_sent = 0;
6724                 for (policy = 0; policy <= SCTP_PR_INDEX(MAX); policy++) {
6725                         params.sprstat_abandoned_unsent +=
6726                                 streamoute->abandoned_unsent[policy];
6727                         params.sprstat_abandoned_sent +=
6728                                 streamoute->abandoned_sent[policy];
6729                 }
6730         } else {
6731                 params.sprstat_abandoned_unsent =
6732                         streamoute->abandoned_unsent[__SCTP_PR_INDEX(policy)];
6733                 params.sprstat_abandoned_sent =
6734                         streamoute->abandoned_sent[__SCTP_PR_INDEX(policy)];
6735         }
6736
6737         if (put_user(len, optlen) || copy_to_user(optval, &params, len)) {
6738                 retval = -EFAULT;
6739                 goto out;
6740         }
6741
6742         retval = 0;
6743
6744 out:
6745         return retval;
6746 }
6747
6748 static int sctp_getsockopt_reconfig_supported(struct sock *sk, int len,
6749                                               char __user *optval,
6750                                               int __user *optlen)
6751 {
6752         struct sctp_assoc_value params;
6753         struct sctp_association *asoc;
6754         int retval = -EFAULT;
6755
6756         if (len < sizeof(params)) {
6757                 retval = -EINVAL;
6758                 goto out;
6759         }
6760
6761         len = sizeof(params);
6762         if (copy_from_user(&params, optval, len))
6763                 goto out;
6764
6765         asoc = sctp_id2assoc(sk, params.assoc_id);
6766         if (asoc) {
6767                 params.assoc_value = asoc->reconf_enable;
6768         } else if (!params.assoc_id) {
6769                 struct sctp_sock *sp = sctp_sk(sk);
6770
6771                 params.assoc_value = sp->ep->reconf_enable;
6772         } else {
6773                 retval = -EINVAL;
6774                 goto out;
6775         }
6776
6777         if (put_user(len, optlen))
6778                 goto out;
6779
6780         if (copy_to_user(optval, &params, len))
6781                 goto out;
6782
6783         retval = 0;
6784
6785 out:
6786         return retval;
6787 }
6788
6789 static int sctp_getsockopt_enable_strreset(struct sock *sk, int len,
6790                                            char __user *optval,
6791                                            int __user *optlen)
6792 {
6793         struct sctp_assoc_value params;
6794         struct sctp_association *asoc;
6795         int retval = -EFAULT;
6796
6797         if (len < sizeof(params)) {
6798                 retval = -EINVAL;
6799                 goto out;
6800         }
6801
6802         len = sizeof(params);
6803         if (copy_from_user(&params, optval, len))
6804                 goto out;
6805
6806         asoc = sctp_id2assoc(sk, params.assoc_id);
6807         if (asoc) {
6808                 params.assoc_value = asoc->strreset_enable;
6809         } else if (!params.assoc_id) {
6810                 struct sctp_sock *sp = sctp_sk(sk);
6811
6812                 params.assoc_value = sp->ep->strreset_enable;
6813         } else {
6814                 retval = -EINVAL;
6815                 goto out;
6816         }
6817
6818         if (put_user(len, optlen))
6819                 goto out;
6820
6821         if (copy_to_user(optval, &params, len))
6822                 goto out;
6823
6824         retval = 0;
6825
6826 out:
6827         return retval;
6828 }
6829
6830 static int sctp_getsockopt_scheduler(struct sock *sk, int len,
6831                                      char __user *optval,
6832                                      int __user *optlen)
6833 {
6834         struct sctp_assoc_value params;
6835         struct sctp_association *asoc;
6836         int retval = -EFAULT;
6837
6838         if (len < sizeof(params)) {
6839                 retval = -EINVAL;
6840                 goto out;
6841         }
6842
6843         len = sizeof(params);
6844         if (copy_from_user(&params, optval, len))
6845                 goto out;
6846
6847         asoc = sctp_id2assoc(sk, params.assoc_id);
6848         if (!asoc) {
6849                 retval = -EINVAL;
6850                 goto out;
6851         }
6852
6853         params.assoc_value = sctp_sched_get_sched(asoc);
6854
6855         if (put_user(len, optlen))
6856                 goto out;
6857
6858         if (copy_to_user(optval, &params, len))
6859                 goto out;
6860
6861         retval = 0;
6862
6863 out:
6864         return retval;
6865 }
6866
6867 static int sctp_getsockopt(struct sock *sk, int level, int optname,
6868                            char __user *optval, int __user *optlen)
6869 {
6870         int retval = 0;
6871         int len;
6872
6873         pr_debug("%s: sk:%p, optname:%d\n", __func__, sk, optname);
6874
6875         /* I can hardly begin to describe how wrong this is.  This is
6876          * so broken as to be worse than useless.  The API draft
6877          * REALLY is NOT helpful here...  I am not convinced that the
6878          * semantics of getsockopt() with a level OTHER THAN SOL_SCTP
6879          * are at all well-founded.
6880          */
6881         if (level != SOL_SCTP) {
6882                 struct sctp_af *af = sctp_sk(sk)->pf->af;
6883
6884                 retval = af->getsockopt(sk, level, optname, optval, optlen);
6885                 return retval;
6886         }
6887
6888         if (get_user(len, optlen))
6889                 return -EFAULT;
6890
6891         if (len < 0)
6892                 return -EINVAL;
6893
6894         lock_sock(sk);
6895
6896         switch (optname) {
6897         case SCTP_STATUS:
6898                 retval = sctp_getsockopt_sctp_status(sk, len, optval, optlen);
6899                 break;
6900         case SCTP_DISABLE_FRAGMENTS:
6901                 retval = sctp_getsockopt_disable_fragments(sk, len, optval,
6902                                                            optlen);
6903                 break;
6904         case SCTP_EVENTS:
6905                 retval = sctp_getsockopt_events(sk, len, optval, optlen);
6906                 break;
6907         case SCTP_AUTOCLOSE:
6908                 retval = sctp_getsockopt_autoclose(sk, len, optval, optlen);
6909                 break;
6910         case SCTP_SOCKOPT_PEELOFF:
6911                 retval = sctp_getsockopt_peeloff(sk, len, optval, optlen);
6912                 break;
6913         case SCTP_SOCKOPT_PEELOFF_FLAGS:
6914                 retval = sctp_getsockopt_peeloff_flags(sk, len, optval, optlen);
6915                 break;
6916         case SCTP_PEER_ADDR_PARAMS:
6917                 retval = sctp_getsockopt_peer_addr_params(sk, len, optval,
6918                                                           optlen);
6919                 break;
6920         case SCTP_DELAYED_SACK:
6921                 retval = sctp_getsockopt_delayed_ack(sk, len, optval,
6922                                                           optlen);
6923                 break;
6924         case SCTP_INITMSG:
6925                 retval = sctp_getsockopt_initmsg(sk, len, optval, optlen);
6926                 break;
6927         case SCTP_GET_PEER_ADDRS:
6928                 retval = sctp_getsockopt_peer_addrs(sk, len, optval,
6929                                                     optlen);
6930                 break;
6931         case SCTP_GET_LOCAL_ADDRS:
6932                 retval = sctp_getsockopt_local_addrs(sk, len, optval,
6933                                                      optlen);
6934                 break;
6935         case SCTP_SOCKOPT_CONNECTX3:
6936                 retval = sctp_getsockopt_connectx3(sk, len, optval, optlen);
6937                 break;
6938         case SCTP_DEFAULT_SEND_PARAM:
6939                 retval = sctp_getsockopt_default_send_param(sk, len,
6940                                                             optval, optlen);
6941                 break;
6942         case SCTP_DEFAULT_SNDINFO:
6943                 retval = sctp_getsockopt_default_sndinfo(sk, len,
6944                                                          optval, optlen);
6945                 break;
6946         case SCTP_PRIMARY_ADDR:
6947                 retval = sctp_getsockopt_primary_addr(sk, len, optval, optlen);
6948                 break;
6949         case SCTP_NODELAY:
6950                 retval = sctp_getsockopt_nodelay(sk, len, optval, optlen);
6951                 break;
6952         case SCTP_RTOINFO:
6953                 retval = sctp_getsockopt_rtoinfo(sk, len, optval, optlen);
6954                 break;
6955         case SCTP_ASSOCINFO:
6956                 retval = sctp_getsockopt_associnfo(sk, len, optval, optlen);
6957                 break;
6958         case SCTP_I_WANT_MAPPED_V4_ADDR:
6959                 retval = sctp_getsockopt_mappedv4(sk, len, optval, optlen);
6960                 break;
6961         case SCTP_MAXSEG:
6962                 retval = sctp_getsockopt_maxseg(sk, len, optval, optlen);
6963                 break;
6964         case SCTP_GET_PEER_ADDR_INFO:
6965                 retval = sctp_getsockopt_peer_addr_info(sk, len, optval,
6966                                                         optlen);
6967                 break;
6968         case SCTP_ADAPTATION_LAYER:
6969                 retval = sctp_getsockopt_adaptation_layer(sk, len, optval,
6970                                                         optlen);
6971                 break;
6972         case SCTP_CONTEXT:
6973                 retval = sctp_getsockopt_context(sk, len, optval, optlen);
6974                 break;
6975         case SCTP_FRAGMENT_INTERLEAVE:
6976                 retval = sctp_getsockopt_fragment_interleave(sk, len, optval,
6977                                                              optlen);
6978                 break;
6979         case SCTP_PARTIAL_DELIVERY_POINT:
6980                 retval = sctp_getsockopt_partial_delivery_point(sk, len, optval,
6981                                                                 optlen);
6982                 break;
6983         case SCTP_MAX_BURST:
6984                 retval = sctp_getsockopt_maxburst(sk, len, optval, optlen);
6985                 break;
6986         case SCTP_AUTH_KEY:
6987         case SCTP_AUTH_CHUNK:
6988         case SCTP_AUTH_DELETE_KEY:
6989                 retval = -EOPNOTSUPP;
6990                 break;
6991         case SCTP_HMAC_IDENT:
6992                 retval = sctp_getsockopt_hmac_ident(sk, len, optval, optlen);
6993                 break;
6994         case SCTP_AUTH_ACTIVE_KEY:
6995                 retval = sctp_getsockopt_active_key(sk, len, optval, optlen);
6996                 break;
6997         case SCTP_PEER_AUTH_CHUNKS:
6998                 retval = sctp_getsockopt_peer_auth_chunks(sk, len, optval,
6999                                                         optlen);
7000                 break;
7001         case SCTP_LOCAL_AUTH_CHUNKS:
7002                 retval = sctp_getsockopt_local_auth_chunks(sk, len, optval,
7003                                                         optlen);
7004                 break;
7005         case SCTP_GET_ASSOC_NUMBER:
7006                 retval = sctp_getsockopt_assoc_number(sk, len, optval, optlen);
7007                 break;
7008         case SCTP_GET_ASSOC_ID_LIST:
7009                 retval = sctp_getsockopt_assoc_ids(sk, len, optval, optlen);
7010                 break;
7011         case SCTP_AUTO_ASCONF:
7012                 retval = sctp_getsockopt_auto_asconf(sk, len, optval, optlen);
7013                 break;
7014         case SCTP_PEER_ADDR_THLDS:
7015                 retval = sctp_getsockopt_paddr_thresholds(sk, optval, len, optlen);
7016                 break;
7017         case SCTP_GET_ASSOC_STATS:
7018                 retval = sctp_getsockopt_assoc_stats(sk, len, optval, optlen);
7019                 break;
7020         case SCTP_RECVRCVINFO:
7021                 retval = sctp_getsockopt_recvrcvinfo(sk, len, optval, optlen);
7022                 break;
7023         case SCTP_RECVNXTINFO:
7024                 retval = sctp_getsockopt_recvnxtinfo(sk, len, optval, optlen);
7025                 break;
7026         case SCTP_PR_SUPPORTED:
7027                 retval = sctp_getsockopt_pr_supported(sk, len, optval, optlen);
7028                 break;
7029         case SCTP_DEFAULT_PRINFO:
7030                 retval = sctp_getsockopt_default_prinfo(sk, len, optval,
7031                                                         optlen);
7032                 break;
7033         case SCTP_PR_ASSOC_STATUS:
7034                 retval = sctp_getsockopt_pr_assocstatus(sk, len, optval,
7035                                                         optlen);
7036                 break;
7037         case SCTP_PR_STREAM_STATUS:
7038                 retval = sctp_getsockopt_pr_streamstatus(sk, len, optval,
7039                                                          optlen);
7040                 break;
7041         case SCTP_RECONFIG_SUPPORTED:
7042                 retval = sctp_getsockopt_reconfig_supported(sk, len, optval,
7043                                                             optlen);
7044                 break;
7045         case SCTP_ENABLE_STREAM_RESET:
7046                 retval = sctp_getsockopt_enable_strreset(sk, len, optval,
7047                                                          optlen);
7048                 break;
7049         case SCTP_STREAM_SCHEDULER:
7050                 retval = sctp_getsockopt_scheduler(sk, len, optval,
7051                                                    optlen);
7052                 break;
7053         default:
7054                 retval = -ENOPROTOOPT;
7055                 break;
7056         }
7057
7058         release_sock(sk);
7059         return retval;
7060 }
7061
7062 static int sctp_hash(struct sock *sk)
7063 {
7064         /* STUB */
7065         return 0;
7066 }
7067
7068 static void sctp_unhash(struct sock *sk)
7069 {
7070         /* STUB */
7071 }
7072
7073 /* Check if port is acceptable.  Possibly find first available port.
7074  *
7075  * The port hash table (contained in the 'global' SCTP protocol storage
7076  * returned by struct sctp_protocol *sctp_get_protocol()). The hash
7077  * table is an array of 4096 lists (sctp_bind_hashbucket). Each
7078  * list (the list number is the port number hashed out, so as you
7079  * would expect from a hash function, all the ports in a given list have
7080  * such a number that hashes out to the same list number; you were
7081  * expecting that, right?); so each list has a set of ports, with a
7082  * link to the socket (struct sock) that uses it, the port number and
7083  * a fastreuse flag (FIXME: NPI ipg).
7084  */
7085 static struct sctp_bind_bucket *sctp_bucket_create(
7086         struct sctp_bind_hashbucket *head, struct net *, unsigned short snum);
7087
7088 static long sctp_get_port_local(struct sock *sk, union sctp_addr *addr)
7089 {
7090         struct sctp_bind_hashbucket *head; /* hash list */
7091         struct sctp_bind_bucket *pp;
7092         unsigned short snum;
7093         int ret;
7094
7095         snum = ntohs(addr->v4.sin_port);
7096
7097         pr_debug("%s: begins, snum:%d\n", __func__, snum);
7098
7099         local_bh_disable();
7100
7101         if (snum == 0) {
7102                 /* Search for an available port. */
7103                 int low, high, remaining, index;
7104                 unsigned int rover;
7105                 struct net *net = sock_net(sk);
7106
7107                 inet_get_local_port_range(net, &low, &high);
7108                 remaining = (high - low) + 1;
7109                 rover = prandom_u32() % remaining + low;
7110
7111                 do {
7112                         rover++;
7113                         if ((rover < low) || (rover > high))
7114                                 rover = low;
7115                         if (inet_is_local_reserved_port(net, rover))
7116                                 continue;
7117                         index = sctp_phashfn(sock_net(sk), rover);
7118                         head = &sctp_port_hashtable[index];
7119                         spin_lock(&head->lock);
7120                         sctp_for_each_hentry(pp, &head->chain)
7121                                 if ((pp->port == rover) &&
7122                                     net_eq(sock_net(sk), pp->net))
7123                                         goto next;
7124                         break;
7125                 next:
7126                         spin_unlock(&head->lock);
7127                 } while (--remaining > 0);
7128
7129                 /* Exhausted local port range during search? */
7130                 ret = 1;
7131                 if (remaining <= 0)
7132                         goto fail;
7133
7134                 /* OK, here is the one we will use.  HEAD (the port
7135                  * hash table list entry) is non-NULL and we hold it's
7136                  * mutex.
7137                  */
7138                 snum = rover;
7139         } else {
7140                 /* We are given an specific port number; we verify
7141                  * that it is not being used. If it is used, we will
7142                  * exahust the search in the hash list corresponding
7143                  * to the port number (snum) - we detect that with the
7144                  * port iterator, pp being NULL.
7145                  */
7146                 head = &sctp_port_hashtable[sctp_phashfn(sock_net(sk), snum)];
7147                 spin_lock(&head->lock);
7148                 sctp_for_each_hentry(pp, &head->chain) {
7149                         if ((pp->port == snum) && net_eq(pp->net, sock_net(sk)))
7150                                 goto pp_found;
7151                 }
7152         }
7153         pp = NULL;
7154         goto pp_not_found;
7155 pp_found:
7156         if (!hlist_empty(&pp->owner)) {
7157                 /* We had a port hash table hit - there is an
7158                  * available port (pp != NULL) and it is being
7159                  * used by other socket (pp->owner not empty); that other
7160                  * socket is going to be sk2.
7161                  */
7162                 int reuse = sk->sk_reuse;
7163                 struct sock *sk2;
7164
7165                 pr_debug("%s: found a possible match\n", __func__);
7166
7167                 if (pp->fastreuse && sk->sk_reuse &&
7168                         sk->sk_state != SCTP_SS_LISTENING)
7169                         goto success;
7170
7171                 /* Run through the list of sockets bound to the port
7172                  * (pp->port) [via the pointers bind_next and
7173                  * bind_pprev in the struct sock *sk2 (pp->sk)]. On each one,
7174                  * we get the endpoint they describe and run through
7175                  * the endpoint's list of IP (v4 or v6) addresses,
7176                  * comparing each of the addresses with the address of
7177                  * the socket sk. If we find a match, then that means
7178                  * that this port/socket (sk) combination are already
7179                  * in an endpoint.
7180                  */
7181                 sk_for_each_bound(sk2, &pp->owner) {
7182                         struct sctp_endpoint *ep2;
7183                         ep2 = sctp_sk(sk2)->ep;
7184
7185                         if (sk == sk2 ||
7186                             (reuse && sk2->sk_reuse &&
7187                              sk2->sk_state != SCTP_SS_LISTENING))
7188                                 continue;
7189
7190                         if (sctp_bind_addr_conflict(&ep2->base.bind_addr, addr,
7191                                                  sctp_sk(sk2), sctp_sk(sk))) {
7192                                 ret = (long)sk2;
7193                                 goto fail_unlock;
7194                         }
7195                 }
7196
7197                 pr_debug("%s: found a match\n", __func__);
7198         }
7199 pp_not_found:
7200         /* If there was a hash table miss, create a new port.  */
7201         ret = 1;
7202         if (!pp && !(pp = sctp_bucket_create(head, sock_net(sk), snum)))
7203                 goto fail_unlock;
7204
7205         /* In either case (hit or miss), make sure fastreuse is 1 only
7206          * if sk->sk_reuse is too (that is, if the caller requested
7207          * SO_REUSEADDR on this socket -sk-).
7208          */
7209         if (hlist_empty(&pp->owner)) {
7210                 if (sk->sk_reuse && sk->sk_state != SCTP_SS_LISTENING)
7211                         pp->fastreuse = 1;
7212                 else
7213                         pp->fastreuse = 0;
7214         } else if (pp->fastreuse &&
7215                 (!sk->sk_reuse || sk->sk_state == SCTP_SS_LISTENING))
7216                 pp->fastreuse = 0;
7217
7218         /* We are set, so fill up all the data in the hash table
7219          * entry, tie the socket list information with the rest of the
7220          * sockets FIXME: Blurry, NPI (ipg).
7221          */
7222 success:
7223         if (!sctp_sk(sk)->bind_hash) {
7224                 inet_sk(sk)->inet_num = snum;
7225                 sk_add_bind_node(sk, &pp->owner);
7226                 sctp_sk(sk)->bind_hash = pp;
7227         }
7228         ret = 0;
7229
7230 fail_unlock:
7231         spin_unlock(&head->lock);
7232
7233 fail:
7234         local_bh_enable();
7235         return ret;
7236 }
7237
7238 /* Assign a 'snum' port to the socket.  If snum == 0, an ephemeral
7239  * port is requested.
7240  */
7241 static int sctp_get_port(struct sock *sk, unsigned short snum)
7242 {
7243         union sctp_addr addr;
7244         struct sctp_af *af = sctp_sk(sk)->pf->af;
7245
7246         /* Set up a dummy address struct from the sk. */
7247         af->from_sk(&addr, sk);
7248         addr.v4.sin_port = htons(snum);
7249
7250         /* Note: sk->sk_num gets filled in if ephemeral port request. */
7251         return !!sctp_get_port_local(sk, &addr);
7252 }
7253
7254 /*
7255  *  Move a socket to LISTENING state.
7256  */
7257 static int sctp_listen_start(struct sock *sk, int backlog)
7258 {
7259         struct sctp_sock *sp = sctp_sk(sk);
7260         struct sctp_endpoint *ep = sp->ep;
7261         struct crypto_shash *tfm = NULL;
7262         char alg[32];
7263
7264         /* Allocate HMAC for generating cookie. */
7265         if (!sp->hmac && sp->sctp_hmac_alg) {
7266                 sprintf(alg, "hmac(%s)", sp->sctp_hmac_alg);
7267                 tfm = crypto_alloc_shash(alg, 0, 0);
7268                 if (IS_ERR(tfm)) {
7269                         net_info_ratelimited("failed to load transform for %s: %ld\n",
7270                                              sp->sctp_hmac_alg, PTR_ERR(tfm));
7271                         return -ENOSYS;
7272                 }
7273                 sctp_sk(sk)->hmac = tfm;
7274         }
7275
7276         /*
7277          * If a bind() or sctp_bindx() is not called prior to a listen()
7278          * call that allows new associations to be accepted, the system
7279          * picks an ephemeral port and will choose an address set equivalent
7280          * to binding with a wildcard address.
7281          *
7282          * This is not currently spelled out in the SCTP sockets
7283          * extensions draft, but follows the practice as seen in TCP
7284          * sockets.
7285          *
7286          */
7287         sk->sk_state = SCTP_SS_LISTENING;
7288         if (!ep->base.bind_addr.port) {
7289                 if (sctp_autobind(sk))
7290                         return -EAGAIN;
7291         } else {
7292                 if (sctp_get_port(sk, inet_sk(sk)->inet_num)) {
7293                         sk->sk_state = SCTP_SS_CLOSED;
7294                         return -EADDRINUSE;
7295                 }
7296         }
7297
7298         sk->sk_max_ack_backlog = backlog;
7299         sctp_hash_endpoint(ep);
7300         return 0;
7301 }
7302
7303 /*
7304  * 4.1.3 / 5.1.3 listen()
7305  *
7306  *   By default, new associations are not accepted for UDP style sockets.
7307  *   An application uses listen() to mark a socket as being able to
7308  *   accept new associations.
7309  *
7310  *   On TCP style sockets, applications use listen() to ready the SCTP
7311  *   endpoint for accepting inbound associations.
7312  *
7313  *   On both types of endpoints a backlog of '0' disables listening.
7314  *
7315  *  Move a socket to LISTENING state.
7316  */
7317 int sctp_inet_listen(struct socket *sock, int backlog)
7318 {
7319         struct sock *sk = sock->sk;
7320         struct sctp_endpoint *ep = sctp_sk(sk)->ep;
7321         int err = -EINVAL;
7322
7323         if (unlikely(backlog < 0))
7324                 return err;
7325
7326         lock_sock(sk);
7327
7328         /* Peeled-off sockets are not allowed to listen().  */
7329         if (sctp_style(sk, UDP_HIGH_BANDWIDTH))
7330                 goto out;
7331
7332         if (sock->state != SS_UNCONNECTED)
7333                 goto out;
7334
7335         if (!sctp_sstate(sk, LISTENING) && !sctp_sstate(sk, CLOSED))
7336                 goto out;
7337
7338         /* If backlog is zero, disable listening. */
7339         if (!backlog) {
7340                 if (sctp_sstate(sk, CLOSED))
7341                         goto out;
7342
7343                 err = 0;
7344                 sctp_unhash_endpoint(ep);
7345                 sk->sk_state = SCTP_SS_CLOSED;
7346                 if (sk->sk_reuse)
7347                         sctp_sk(sk)->bind_hash->fastreuse = 1;
7348                 goto out;
7349         }
7350
7351         /* If we are already listening, just update the backlog */
7352         if (sctp_sstate(sk, LISTENING))
7353                 sk->sk_max_ack_backlog = backlog;
7354         else {
7355                 err = sctp_listen_start(sk, backlog);
7356                 if (err)
7357                         goto out;
7358         }
7359
7360         err = 0;
7361 out:
7362         release_sock(sk);
7363         return err;
7364 }
7365
7366 /*
7367  * This function is done by modeling the current datagram_poll() and the
7368  * tcp_poll().  Note that, based on these implementations, we don't
7369  * lock the socket in this function, even though it seems that,
7370  * ideally, locking or some other mechanisms can be used to ensure
7371  * the integrity of the counters (sndbuf and wmem_alloc) used
7372  * in this place.  We assume that we don't need locks either until proven
7373  * otherwise.
7374  *
7375  * Another thing to note is that we include the Async I/O support
7376  * here, again, by modeling the current TCP/UDP code.  We don't have
7377  * a good way to test with it yet.
7378  */
7379 unsigned int sctp_poll(struct file *file, struct socket *sock, poll_table *wait)
7380 {
7381         struct sock *sk = sock->sk;
7382         struct sctp_sock *sp = sctp_sk(sk);
7383         unsigned int mask;
7384
7385         poll_wait(file, sk_sleep(sk), wait);
7386
7387         sock_rps_record_flow(sk);
7388
7389         /* A TCP-style listening socket becomes readable when the accept queue
7390          * is not empty.
7391          */
7392         if (sctp_style(sk, TCP) && sctp_sstate(sk, LISTENING))
7393                 return (!list_empty(&sp->ep->asocs)) ?
7394                         (POLLIN | POLLRDNORM) : 0;
7395
7396         mask = 0;
7397
7398         /* Is there any exceptional events?  */
7399         if (sk->sk_err || !skb_queue_empty(&sk->sk_error_queue))
7400                 mask |= POLLERR |
7401                         (sock_flag(sk, SOCK_SELECT_ERR_QUEUE) ? POLLPRI : 0);
7402         if (sk->sk_shutdown & RCV_SHUTDOWN)
7403                 mask |= POLLRDHUP | POLLIN | POLLRDNORM;
7404         if (sk->sk_shutdown == SHUTDOWN_MASK)
7405                 mask |= POLLHUP;
7406
7407         /* Is it readable?  Reconsider this code with TCP-style support.  */
7408         if (!skb_queue_empty(&sk->sk_receive_queue))
7409                 mask |= POLLIN | POLLRDNORM;
7410
7411         /* The association is either gone or not ready.  */
7412         if (!sctp_style(sk, UDP) && sctp_sstate(sk, CLOSED))
7413                 return mask;
7414
7415         /* Is it writable?  */
7416         if (sctp_writeable(sk)) {
7417                 mask |= POLLOUT | POLLWRNORM;
7418         } else {
7419                 sk_set_bit(SOCKWQ_ASYNC_NOSPACE, sk);
7420                 /*
7421                  * Since the socket is not locked, the buffer
7422                  * might be made available after the writeable check and
7423                  * before the bit is set.  This could cause a lost I/O
7424                  * signal.  tcp_poll() has a race breaker for this race
7425                  * condition.  Based on their implementation, we put
7426                  * in the following code to cover it as well.
7427                  */
7428                 if (sctp_writeable(sk))
7429                         mask |= POLLOUT | POLLWRNORM;
7430         }
7431         return mask;
7432 }
7433
7434 /********************************************************************
7435  * 2nd Level Abstractions
7436  ********************************************************************/
7437
7438 static struct sctp_bind_bucket *sctp_bucket_create(
7439         struct sctp_bind_hashbucket *head, struct net *net, unsigned short snum)
7440 {
7441         struct sctp_bind_bucket *pp;
7442
7443         pp = kmem_cache_alloc(sctp_bucket_cachep, GFP_ATOMIC);
7444         if (pp) {
7445                 SCTP_DBG_OBJCNT_INC(bind_bucket);
7446                 pp->port = snum;
7447                 pp->fastreuse = 0;
7448                 INIT_HLIST_HEAD(&pp->owner);
7449                 pp->net = net;
7450                 hlist_add_head(&pp->node, &head->chain);
7451         }
7452         return pp;
7453 }
7454
7455 /* Caller must hold hashbucket lock for this tb with local BH disabled */
7456 static void sctp_bucket_destroy(struct sctp_bind_bucket *pp)
7457 {
7458         if (pp && hlist_empty(&pp->owner)) {
7459                 __hlist_del(&pp->node);
7460                 kmem_cache_free(sctp_bucket_cachep, pp);
7461                 SCTP_DBG_OBJCNT_DEC(bind_bucket);
7462         }
7463 }
7464
7465 /* Release this socket's reference to a local port.  */
7466 static inline void __sctp_put_port(struct sock *sk)
7467 {
7468         struct sctp_bind_hashbucket *head =
7469                 &sctp_port_hashtable[sctp_phashfn(sock_net(sk),
7470                                                   inet_sk(sk)->inet_num)];
7471         struct sctp_bind_bucket *pp;
7472
7473         spin_lock(&head->lock);
7474         pp = sctp_sk(sk)->bind_hash;
7475         __sk_del_bind_node(sk);
7476         sctp_sk(sk)->bind_hash = NULL;
7477         inet_sk(sk)->inet_num = 0;
7478         sctp_bucket_destroy(pp);
7479         spin_unlock(&head->lock);
7480 }
7481
7482 void sctp_put_port(struct sock *sk)
7483 {
7484         local_bh_disable();
7485         __sctp_put_port(sk);
7486         local_bh_enable();
7487 }
7488
7489 /*
7490  * The system picks an ephemeral port and choose an address set equivalent
7491  * to binding with a wildcard address.
7492  * One of those addresses will be the primary address for the association.
7493  * This automatically enables the multihoming capability of SCTP.
7494  */
7495 static int sctp_autobind(struct sock *sk)
7496 {
7497         union sctp_addr autoaddr;
7498         struct sctp_af *af;
7499         __be16 port;
7500
7501         /* Initialize a local sockaddr structure to INADDR_ANY. */
7502         af = sctp_sk(sk)->pf->af;
7503
7504         port = htons(inet_sk(sk)->inet_num);
7505         af->inaddr_any(&autoaddr, port);
7506
7507         return sctp_do_bind(sk, &autoaddr, af->sockaddr_len);
7508 }
7509
7510 /* Parse out IPPROTO_SCTP CMSG headers.  Perform only minimal validation.
7511  *
7512  * From RFC 2292
7513  * 4.2 The cmsghdr Structure *
7514  *
7515  * When ancillary data is sent or received, any number of ancillary data
7516  * objects can be specified by the msg_control and msg_controllen members of
7517  * the msghdr structure, because each object is preceded by
7518  * a cmsghdr structure defining the object's length (the cmsg_len member).
7519  * Historically Berkeley-derived implementations have passed only one object
7520  * at a time, but this API allows multiple objects to be
7521  * passed in a single call to sendmsg() or recvmsg(). The following example
7522  * shows two ancillary data objects in a control buffer.
7523  *
7524  *   |<--------------------------- msg_controllen -------------------------->|
7525  *   |                                                                       |
7526  *
7527  *   |<----- ancillary data object ----->|<----- ancillary data object ----->|
7528  *
7529  *   |<---------- CMSG_SPACE() --------->|<---------- CMSG_SPACE() --------->|
7530  *   |                                   |                                   |
7531  *
7532  *   |<---------- cmsg_len ---------->|  |<--------- cmsg_len ----------->|  |
7533  *
7534  *   |<--------- CMSG_LEN() --------->|  |<-------- CMSG_LEN() ---------->|  |
7535  *   |                                |  |                                |  |
7536  *
7537  *   +-----+-----+-----+--+-----------+--+-----+-----+-----+--+-----------+--+
7538  *   |cmsg_|cmsg_|cmsg_|XX|           |XX|cmsg_|cmsg_|cmsg_|XX|           |XX|
7539  *
7540  *   |len  |level|type |XX|cmsg_data[]|XX|len  |level|type |XX|cmsg_data[]|XX|
7541  *
7542  *   +-----+-----+-----+--+-----------+--+-----+-----+-----+--+-----------+--+
7543  *    ^
7544  *    |
7545  *
7546  * msg_control
7547  * points here
7548  */
7549 static int sctp_msghdr_parse(const struct msghdr *msg, struct sctp_cmsgs *cmsgs)
7550 {
7551         struct msghdr *my_msg = (struct msghdr *)msg;
7552         struct cmsghdr *cmsg;
7553
7554         for_each_cmsghdr(cmsg, my_msg) {
7555                 if (!CMSG_OK(my_msg, cmsg))
7556                         return -EINVAL;
7557
7558                 /* Should we parse this header or ignore?  */
7559                 if (cmsg->cmsg_level != IPPROTO_SCTP)
7560                         continue;
7561
7562                 /* Strictly check lengths following example in SCM code.  */
7563                 switch (cmsg->cmsg_type) {
7564                 case SCTP_INIT:
7565                         /* SCTP Socket API Extension
7566                          * 5.3.1 SCTP Initiation Structure (SCTP_INIT)
7567                          *
7568                          * This cmsghdr structure provides information for
7569                          * initializing new SCTP associations with sendmsg().
7570                          * The SCTP_INITMSG socket option uses this same data
7571                          * structure.  This structure is not used for
7572                          * recvmsg().
7573                          *
7574                          * cmsg_level    cmsg_type      cmsg_data[]
7575                          * ------------  ------------   ----------------------
7576                          * IPPROTO_SCTP  SCTP_INIT      struct sctp_initmsg
7577                          */
7578                         if (cmsg->cmsg_len != CMSG_LEN(sizeof(struct sctp_initmsg)))
7579                                 return -EINVAL;
7580
7581                         cmsgs->init = CMSG_DATA(cmsg);
7582                         break;
7583
7584                 case SCTP_SNDRCV:
7585                         /* SCTP Socket API Extension
7586                          * 5.3.2 SCTP Header Information Structure(SCTP_SNDRCV)
7587                          *
7588                          * This cmsghdr structure specifies SCTP options for
7589                          * sendmsg() and describes SCTP header information
7590                          * about a received message through recvmsg().
7591                          *
7592                          * cmsg_level    cmsg_type      cmsg_data[]
7593                          * ------------  ------------   ----------------------
7594                          * IPPROTO_SCTP  SCTP_SNDRCV    struct sctp_sndrcvinfo
7595                          */
7596                         if (cmsg->cmsg_len != CMSG_LEN(sizeof(struct sctp_sndrcvinfo)))
7597                                 return -EINVAL;
7598
7599                         cmsgs->srinfo = CMSG_DATA(cmsg);
7600
7601                         if (cmsgs->srinfo->sinfo_flags &
7602                             ~(SCTP_UNORDERED | SCTP_ADDR_OVER |
7603                               SCTP_SACK_IMMEDIATELY | SCTP_PR_SCTP_MASK |
7604                               SCTP_ABORT | SCTP_EOF))
7605                                 return -EINVAL;
7606                         break;
7607
7608                 case SCTP_SNDINFO:
7609                         /* SCTP Socket API Extension
7610                          * 5.3.4 SCTP Send Information Structure (SCTP_SNDINFO)
7611                          *
7612                          * This cmsghdr structure specifies SCTP options for
7613                          * sendmsg(). This structure and SCTP_RCVINFO replaces
7614                          * SCTP_SNDRCV which has been deprecated.
7615                          *
7616                          * cmsg_level    cmsg_type      cmsg_data[]
7617                          * ------------  ------------   ---------------------
7618                          * IPPROTO_SCTP  SCTP_SNDINFO    struct sctp_sndinfo
7619                          */
7620                         if (cmsg->cmsg_len != CMSG_LEN(sizeof(struct sctp_sndinfo)))
7621                                 return -EINVAL;
7622
7623                         cmsgs->sinfo = CMSG_DATA(cmsg);
7624
7625                         if (cmsgs->sinfo->snd_flags &
7626                             ~(SCTP_UNORDERED | SCTP_ADDR_OVER |
7627                               SCTP_SACK_IMMEDIATELY | SCTP_PR_SCTP_MASK |
7628                               SCTP_ABORT | SCTP_EOF))
7629                                 return -EINVAL;
7630                         break;
7631                 default:
7632                         return -EINVAL;
7633                 }
7634         }
7635
7636         return 0;
7637 }
7638
7639 /*
7640  * Wait for a packet..
7641  * Note: This function is the same function as in core/datagram.c
7642  * with a few modifications to make lksctp work.
7643  */
7644 static int sctp_wait_for_packet(struct sock *sk, int *err, long *timeo_p)
7645 {
7646         int error;
7647         DEFINE_WAIT(wait);
7648
7649         prepare_to_wait_exclusive(sk_sleep(sk), &wait, TASK_INTERRUPTIBLE);
7650
7651         /* Socket errors? */
7652         error = sock_error(sk);
7653         if (error)
7654                 goto out;
7655
7656         if (!skb_queue_empty(&sk->sk_receive_queue))
7657                 goto ready;
7658
7659         /* Socket shut down?  */
7660         if (sk->sk_shutdown & RCV_SHUTDOWN)
7661                 goto out;
7662
7663         /* Sequenced packets can come disconnected.  If so we report the
7664          * problem.
7665          */
7666         error = -ENOTCONN;
7667
7668         /* Is there a good reason to think that we may receive some data?  */
7669         if (list_empty(&sctp_sk(sk)->ep->asocs) && !sctp_sstate(sk, LISTENING))
7670                 goto out;
7671
7672         /* Handle signals.  */
7673         if (signal_pending(current))
7674                 goto interrupted;
7675
7676         /* Let another process have a go.  Since we are going to sleep
7677          * anyway.  Note: This may cause odd behaviors if the message
7678          * does not fit in the user's buffer, but this seems to be the
7679          * only way to honor MSG_DONTWAIT realistically.
7680          */
7681         release_sock(sk);
7682         *timeo_p = schedule_timeout(*timeo_p);
7683         lock_sock(sk);
7684
7685 ready:
7686         finish_wait(sk_sleep(sk), &wait);
7687         return 0;
7688
7689 interrupted:
7690         error = sock_intr_errno(*timeo_p);
7691
7692 out:
7693         finish_wait(sk_sleep(sk), &wait);
7694         *err = error;
7695         return error;
7696 }
7697
7698 /* Receive a datagram.
7699  * Note: This is pretty much the same routine as in core/datagram.c
7700  * with a few changes to make lksctp work.
7701  */
7702 struct sk_buff *sctp_skb_recv_datagram(struct sock *sk, int flags,
7703                                        int noblock, int *err)
7704 {
7705         int error;
7706         struct sk_buff *skb;
7707         long timeo;
7708
7709         timeo = sock_rcvtimeo(sk, noblock);
7710
7711         pr_debug("%s: timeo:%ld, max:%ld\n", __func__, timeo,
7712                  MAX_SCHEDULE_TIMEOUT);
7713
7714         do {
7715                 /* Again only user level code calls this function,
7716                  * so nothing interrupt level
7717                  * will suddenly eat the receive_queue.
7718                  *
7719                  *  Look at current nfs client by the way...
7720                  *  However, this function was correct in any case. 8)
7721                  */
7722                 if (flags & MSG_PEEK) {
7723                         skb = skb_peek(&sk->sk_receive_queue);
7724                         if (skb)
7725                                 refcount_inc(&skb->users);
7726                 } else {
7727                         skb = __skb_dequeue(&sk->sk_receive_queue);
7728                 }
7729
7730                 if (skb)
7731                         return skb;
7732
7733                 /* Caller is allowed not to check sk->sk_err before calling. */
7734                 error = sock_error(sk);
7735                 if (error)
7736                         goto no_packet;
7737
7738                 if (sk->sk_shutdown & RCV_SHUTDOWN)
7739                         break;
7740
7741                 if (sk_can_busy_loop(sk)) {
7742                         sk_busy_loop(sk, noblock);
7743
7744                         if (!skb_queue_empty(&sk->sk_receive_queue))
7745                                 continue;
7746                 }
7747
7748                 /* User doesn't want to wait.  */
7749                 error = -EAGAIN;
7750                 if (!timeo)
7751                         goto no_packet;
7752         } while (sctp_wait_for_packet(sk, err, &timeo) == 0);
7753
7754         return NULL;
7755
7756 no_packet:
7757         *err = error;
7758         return NULL;
7759 }
7760
7761 /* If sndbuf has changed, wake up per association sndbuf waiters.  */
7762 static void __sctp_write_space(struct sctp_association *asoc)
7763 {
7764         struct sock *sk = asoc->base.sk;
7765
7766         if (sctp_wspace(asoc) <= 0)
7767                 return;
7768
7769         if (waitqueue_active(&asoc->wait))
7770                 wake_up_interruptible(&asoc->wait);
7771
7772         if (sctp_writeable(sk)) {
7773                 struct socket_wq *wq;
7774
7775                 rcu_read_lock();
7776                 wq = rcu_dereference(sk->sk_wq);
7777                 if (wq) {
7778                         if (waitqueue_active(&wq->wait))
7779                                 wake_up_interruptible(&wq->wait);
7780
7781                         /* Note that we try to include the Async I/O support
7782                          * here by modeling from the current TCP/UDP code.
7783                          * We have not tested with it yet.
7784                          */
7785                         if (!(sk->sk_shutdown & SEND_SHUTDOWN))
7786                                 sock_wake_async(wq, SOCK_WAKE_SPACE, POLL_OUT);
7787                 }
7788                 rcu_read_unlock();
7789         }
7790 }
7791
7792 static void sctp_wake_up_waiters(struct sock *sk,
7793                                  struct sctp_association *asoc)
7794 {
7795         struct sctp_association *tmp = asoc;
7796
7797         /* We do accounting for the sndbuf space per association,
7798          * so we only need to wake our own association.
7799          */
7800         if (asoc->ep->sndbuf_policy)
7801                 return __sctp_write_space(asoc);
7802
7803         /* If association goes down and is just flushing its
7804          * outq, then just normally notify others.
7805          */
7806         if (asoc->base.dead)
7807                 return sctp_write_space(sk);
7808
7809         /* Accounting for the sndbuf space is per socket, so we
7810          * need to wake up others, try to be fair and in case of
7811          * other associations, let them have a go first instead
7812          * of just doing a sctp_write_space() call.
7813          *
7814          * Note that we reach sctp_wake_up_waiters() only when
7815          * associations free up queued chunks, thus we are under
7816          * lock and the list of associations on a socket is
7817          * guaranteed not to change.
7818          */
7819         for (tmp = list_next_entry(tmp, asocs); 1;
7820              tmp = list_next_entry(tmp, asocs)) {
7821                 /* Manually skip the head element. */
7822                 if (&tmp->asocs == &((sctp_sk(sk))->ep->asocs))
7823                         continue;
7824                 /* Wake up association. */
7825                 __sctp_write_space(tmp);
7826                 /* We've reached the end. */
7827                 if (tmp == asoc)
7828                         break;
7829         }
7830 }
7831
7832 /* Do accounting for the sndbuf space.
7833  * Decrement the used sndbuf space of the corresponding association by the
7834  * data size which was just transmitted(freed).
7835  */
7836 static void sctp_wfree(struct sk_buff *skb)
7837 {
7838         struct sctp_chunk *chunk = skb_shinfo(skb)->destructor_arg;
7839         struct sctp_association *asoc = chunk->asoc;
7840         struct sock *sk = asoc->base.sk;
7841
7842         asoc->sndbuf_used -= SCTP_DATA_SNDSIZE(chunk) +
7843                                 sizeof(struct sk_buff) +
7844                                 sizeof(struct sctp_chunk);
7845
7846         WARN_ON(refcount_sub_and_test(sizeof(struct sctp_chunk), &sk->sk_wmem_alloc));
7847
7848         /*
7849          * This undoes what is done via sctp_set_owner_w and sk_mem_charge
7850          */
7851         sk->sk_wmem_queued   -= skb->truesize;
7852         sk_mem_uncharge(sk, skb->truesize);
7853
7854         sock_wfree(skb);
7855         sctp_wake_up_waiters(sk, asoc);
7856
7857         sctp_association_put(asoc);
7858 }
7859
7860 /* Do accounting for the receive space on the socket.
7861  * Accounting for the association is done in ulpevent.c
7862  * We set this as a destructor for the cloned data skbs so that
7863  * accounting is done at the correct time.
7864  */
7865 void sctp_sock_rfree(struct sk_buff *skb)
7866 {
7867         struct sock *sk = skb->sk;
7868         struct sctp_ulpevent *event = sctp_skb2event(skb);
7869
7870         atomic_sub(event->rmem_len, &sk->sk_rmem_alloc);
7871
7872         /*
7873          * Mimic the behavior of sock_rfree
7874          */
7875         sk_mem_uncharge(sk, event->rmem_len);
7876 }
7877
7878
7879 /* Helper function to wait for space in the sndbuf.  */
7880 static int sctp_wait_for_sndbuf(struct sctp_association *asoc, long *timeo_p,
7881                                 size_t msg_len)
7882 {
7883         struct sock *sk = asoc->base.sk;
7884         int err = 0;
7885         long current_timeo = *timeo_p;
7886         DEFINE_WAIT(wait);
7887
7888         pr_debug("%s: asoc:%p, timeo:%ld, msg_len:%zu\n", __func__, asoc,
7889                  *timeo_p, msg_len);
7890
7891         /* Increment the association's refcnt.  */
7892         sctp_association_hold(asoc);
7893
7894         /* Wait on the association specific sndbuf space. */
7895         for (;;) {
7896                 prepare_to_wait_exclusive(&asoc->wait, &wait,
7897                                           TASK_INTERRUPTIBLE);
7898                 if (!*timeo_p)
7899                         goto do_nonblock;
7900                 if (sk->sk_err || asoc->state >= SCTP_STATE_SHUTDOWN_PENDING ||
7901                     asoc->base.dead)
7902                         goto do_error;
7903                 if (signal_pending(current))
7904                         goto do_interrupted;
7905                 if (msg_len <= sctp_wspace(asoc))
7906                         break;
7907
7908                 /* Let another process have a go.  Since we are going
7909                  * to sleep anyway.
7910                  */
7911                 release_sock(sk);
7912                 current_timeo = schedule_timeout(current_timeo);
7913                 lock_sock(sk);
7914
7915                 *timeo_p = current_timeo;
7916         }
7917
7918 out:
7919         finish_wait(&asoc->wait, &wait);
7920
7921         /* Release the association's refcnt.  */
7922         sctp_association_put(asoc);
7923
7924         return err;
7925
7926 do_error:
7927         err = -EPIPE;
7928         goto out;
7929
7930 do_interrupted:
7931         err = sock_intr_errno(*timeo_p);
7932         goto out;
7933
7934 do_nonblock:
7935         err = -EAGAIN;
7936         goto out;
7937 }
7938
7939 void sctp_data_ready(struct sock *sk)
7940 {
7941         struct socket_wq *wq;
7942
7943         rcu_read_lock();
7944         wq = rcu_dereference(sk->sk_wq);
7945         if (skwq_has_sleeper(wq))
7946                 wake_up_interruptible_sync_poll(&wq->wait, POLLIN |
7947                                                 POLLRDNORM | POLLRDBAND);
7948         sk_wake_async(sk, SOCK_WAKE_WAITD, POLL_IN);
7949         rcu_read_unlock();
7950 }
7951
7952 /* If socket sndbuf has changed, wake up all per association waiters.  */
7953 void sctp_write_space(struct sock *sk)
7954 {
7955         struct sctp_association *asoc;
7956
7957         /* Wake up the tasks in each wait queue.  */
7958         list_for_each_entry(asoc, &((sctp_sk(sk))->ep->asocs), asocs) {
7959                 __sctp_write_space(asoc);
7960         }
7961 }
7962
7963 /* Is there any sndbuf space available on the socket?
7964  *
7965  * Note that sk_wmem_alloc is the sum of the send buffers on all of the
7966  * associations on the same socket.  For a UDP-style socket with
7967  * multiple associations, it is possible for it to be "unwriteable"
7968  * prematurely.  I assume that this is acceptable because
7969  * a premature "unwriteable" is better than an accidental "writeable" which
7970  * would cause an unwanted block under certain circumstances.  For the 1-1
7971  * UDP-style sockets or TCP-style sockets, this code should work.
7972  *  - Daisy
7973  */
7974 static int sctp_writeable(struct sock *sk)
7975 {
7976         int amt = 0;
7977
7978         amt = sk->sk_sndbuf - sk_wmem_alloc_get(sk);
7979         if (amt < 0)
7980                 amt = 0;
7981         return amt;
7982 }
7983
7984 /* Wait for an association to go into ESTABLISHED state. If timeout is 0,
7985  * returns immediately with EINPROGRESS.
7986  */
7987 static int sctp_wait_for_connect(struct sctp_association *asoc, long *timeo_p)
7988 {
7989         struct sock *sk = asoc->base.sk;
7990         int err = 0;
7991         long current_timeo = *timeo_p;
7992         DEFINE_WAIT(wait);
7993
7994         pr_debug("%s: asoc:%p, timeo:%ld\n", __func__, asoc, *timeo_p);
7995
7996         /* Increment the association's refcnt.  */
7997         sctp_association_hold(asoc);
7998
7999         for (;;) {
8000                 prepare_to_wait_exclusive(&asoc->wait, &wait,
8001                                           TASK_INTERRUPTIBLE);
8002                 if (!*timeo_p)
8003                         goto do_nonblock;
8004                 if (sk->sk_shutdown & RCV_SHUTDOWN)
8005                         break;
8006                 if (sk->sk_err || asoc->state >= SCTP_STATE_SHUTDOWN_PENDING ||
8007                     asoc->base.dead)
8008                         goto do_error;
8009                 if (signal_pending(current))
8010                         goto do_interrupted;
8011
8012                 if (sctp_state(asoc, ESTABLISHED))
8013                         break;
8014
8015                 /* Let another process have a go.  Since we are going
8016                  * to sleep anyway.
8017                  */
8018                 release_sock(sk);
8019                 current_timeo = schedule_timeout(current_timeo);
8020                 lock_sock(sk);
8021
8022                 *timeo_p = current_timeo;
8023         }
8024
8025 out:
8026         finish_wait(&asoc->wait, &wait);
8027
8028         /* Release the association's refcnt.  */
8029         sctp_association_put(asoc);
8030
8031         return err;
8032
8033 do_error:
8034         if (asoc->init_err_counter + 1 > asoc->max_init_attempts)
8035                 err = -ETIMEDOUT;
8036         else
8037                 err = -ECONNREFUSED;
8038         goto out;
8039
8040 do_interrupted:
8041         err = sock_intr_errno(*timeo_p);
8042         goto out;
8043
8044 do_nonblock:
8045         err = -EINPROGRESS;
8046         goto out;
8047 }
8048
8049 static int sctp_wait_for_accept(struct sock *sk, long timeo)
8050 {
8051         struct sctp_endpoint *ep;
8052         int err = 0;
8053         DEFINE_WAIT(wait);
8054
8055         ep = sctp_sk(sk)->ep;
8056
8057
8058         for (;;) {
8059                 prepare_to_wait_exclusive(sk_sleep(sk), &wait,
8060                                           TASK_INTERRUPTIBLE);
8061
8062                 if (list_empty(&ep->asocs)) {
8063                         release_sock(sk);
8064                         timeo = schedule_timeout(timeo);
8065                         lock_sock(sk);
8066                 }
8067
8068                 err = -EINVAL;
8069                 if (!sctp_sstate(sk, LISTENING))
8070                         break;
8071
8072                 err = 0;
8073                 if (!list_empty(&ep->asocs))
8074                         break;
8075
8076                 err = sock_intr_errno(timeo);
8077                 if (signal_pending(current))
8078                         break;
8079
8080                 err = -EAGAIN;
8081                 if (!timeo)
8082                         break;
8083         }
8084
8085         finish_wait(sk_sleep(sk), &wait);
8086
8087         return err;
8088 }
8089
8090 static void sctp_wait_for_close(struct sock *sk, long timeout)
8091 {
8092         DEFINE_WAIT(wait);
8093
8094         do {
8095                 prepare_to_wait(sk_sleep(sk), &wait, TASK_INTERRUPTIBLE);
8096                 if (list_empty(&sctp_sk(sk)->ep->asocs))
8097                         break;
8098                 release_sock(sk);
8099                 timeout = schedule_timeout(timeout);
8100                 lock_sock(sk);
8101         } while (!signal_pending(current) && timeout);
8102
8103         finish_wait(sk_sleep(sk), &wait);
8104 }
8105
8106 static void sctp_skb_set_owner_r_frag(struct sk_buff *skb, struct sock *sk)
8107 {
8108         struct sk_buff *frag;
8109
8110         if (!skb->data_len)
8111                 goto done;
8112
8113         /* Don't forget the fragments. */
8114         skb_walk_frags(skb, frag)
8115                 sctp_skb_set_owner_r_frag(frag, sk);
8116
8117 done:
8118         sctp_skb_set_owner_r(skb, sk);
8119 }
8120
8121 void sctp_copy_sock(struct sock *newsk, struct sock *sk,
8122                     struct sctp_association *asoc)
8123 {
8124         struct inet_sock *inet = inet_sk(sk);
8125         struct inet_sock *newinet;
8126
8127         newsk->sk_type = sk->sk_type;
8128         newsk->sk_bound_dev_if = sk->sk_bound_dev_if;
8129         newsk->sk_flags = sk->sk_flags;
8130         newsk->sk_tsflags = sk->sk_tsflags;
8131         newsk->sk_no_check_tx = sk->sk_no_check_tx;
8132         newsk->sk_no_check_rx = sk->sk_no_check_rx;
8133         newsk->sk_reuse = sk->sk_reuse;
8134
8135         newsk->sk_shutdown = sk->sk_shutdown;
8136         newsk->sk_destruct = sctp_destruct_sock;
8137         newsk->sk_family = sk->sk_family;
8138         newsk->sk_protocol = IPPROTO_SCTP;
8139         newsk->sk_backlog_rcv = sk->sk_prot->backlog_rcv;
8140         newsk->sk_sndbuf = sk->sk_sndbuf;
8141         newsk->sk_rcvbuf = sk->sk_rcvbuf;
8142         newsk->sk_lingertime = sk->sk_lingertime;
8143         newsk->sk_rcvtimeo = sk->sk_rcvtimeo;
8144         newsk->sk_sndtimeo = sk->sk_sndtimeo;
8145         newsk->sk_rxhash = sk->sk_rxhash;
8146
8147         newinet = inet_sk(newsk);
8148
8149         /* Initialize sk's sport, dport, rcv_saddr and daddr for
8150          * getsockname() and getpeername()
8151          */
8152         newinet->inet_sport = inet->inet_sport;
8153         newinet->inet_saddr = inet->inet_saddr;
8154         newinet->inet_rcv_saddr = inet->inet_rcv_saddr;
8155         newinet->inet_dport = htons(asoc->peer.port);
8156         newinet->pmtudisc = inet->pmtudisc;
8157         newinet->inet_id = asoc->next_tsn ^ jiffies;
8158
8159         newinet->uc_ttl = inet->uc_ttl;
8160         newinet->mc_loop = 1;
8161         newinet->mc_ttl = 1;
8162         newinet->mc_index = 0;
8163         newinet->mc_list = NULL;
8164
8165         if (newsk->sk_flags & SK_FLAGS_TIMESTAMP)
8166                 net_enable_timestamp();
8167
8168         security_sk_clone(sk, newsk);
8169 }
8170
8171 static inline void sctp_copy_descendant(struct sock *sk_to,
8172                                         const struct sock *sk_from)
8173 {
8174         int ancestor_size = sizeof(struct inet_sock) +
8175                             sizeof(struct sctp_sock) -
8176                             offsetof(struct sctp_sock, auto_asconf_list);
8177
8178         if (sk_from->sk_family == PF_INET6)
8179                 ancestor_size += sizeof(struct ipv6_pinfo);
8180
8181         __inet_sk_copy_descendant(sk_to, sk_from, ancestor_size);
8182 }
8183
8184 /* Populate the fields of the newsk from the oldsk and migrate the assoc
8185  * and its messages to the newsk.
8186  */
8187 static void sctp_sock_migrate(struct sock *oldsk, struct sock *newsk,
8188                               struct sctp_association *assoc,
8189                               enum sctp_socket_type type)
8190 {
8191         struct sctp_sock *oldsp = sctp_sk(oldsk);
8192         struct sctp_sock *newsp = sctp_sk(newsk);
8193         struct sctp_bind_bucket *pp; /* hash list port iterator */
8194         struct sctp_endpoint *newep = newsp->ep;
8195         struct sk_buff *skb, *tmp;
8196         struct sctp_ulpevent *event;
8197         struct sctp_bind_hashbucket *head;
8198
8199         /* Migrate socket buffer sizes and all the socket level options to the
8200          * new socket.
8201          */
8202         newsk->sk_sndbuf = oldsk->sk_sndbuf;
8203         newsk->sk_rcvbuf = oldsk->sk_rcvbuf;
8204         /* Brute force copy old sctp opt. */
8205         sctp_copy_descendant(newsk, oldsk);
8206
8207         /* Restore the ep value that was overwritten with the above structure
8208          * copy.
8209          */
8210         newsp->ep = newep;
8211         newsp->hmac = NULL;
8212
8213         /* Hook this new socket in to the bind_hash list. */
8214         head = &sctp_port_hashtable[sctp_phashfn(sock_net(oldsk),
8215                                                  inet_sk(oldsk)->inet_num)];
8216         spin_lock_bh(&head->lock);
8217         pp = sctp_sk(oldsk)->bind_hash;
8218         sk_add_bind_node(newsk, &pp->owner);
8219         sctp_sk(newsk)->bind_hash = pp;
8220         inet_sk(newsk)->inet_num = inet_sk(oldsk)->inet_num;
8221         spin_unlock_bh(&head->lock);
8222
8223         /* Copy the bind_addr list from the original endpoint to the new
8224          * endpoint so that we can handle restarts properly
8225          */
8226         sctp_bind_addr_dup(&newsp->ep->base.bind_addr,
8227                                 &oldsp->ep->base.bind_addr, GFP_KERNEL);
8228
8229         /* Move any messages in the old socket's receive queue that are for the
8230          * peeled off association to the new socket's receive queue.
8231          */
8232         sctp_skb_for_each(skb, &oldsk->sk_receive_queue, tmp) {
8233                 event = sctp_skb2event(skb);
8234                 if (event->asoc == assoc) {
8235                         __skb_unlink(skb, &oldsk->sk_receive_queue);
8236                         __skb_queue_tail(&newsk->sk_receive_queue, skb);
8237                         sctp_skb_set_owner_r_frag(skb, newsk);
8238                 }
8239         }
8240
8241         /* Clean up any messages pending delivery due to partial
8242          * delivery.   Three cases:
8243          * 1) No partial deliver;  no work.
8244          * 2) Peeling off partial delivery; keep pd_lobby in new pd_lobby.
8245          * 3) Peeling off non-partial delivery; move pd_lobby to receive_queue.
8246          */
8247         skb_queue_head_init(&newsp->pd_lobby);
8248         atomic_set(&sctp_sk(newsk)->pd_mode, assoc->ulpq.pd_mode);
8249
8250         if (atomic_read(&sctp_sk(oldsk)->pd_mode)) {
8251                 struct sk_buff_head *queue;
8252
8253                 /* Decide which queue to move pd_lobby skbs to. */
8254                 if (assoc->ulpq.pd_mode) {
8255                         queue = &newsp->pd_lobby;
8256                 } else
8257                         queue = &newsk->sk_receive_queue;
8258
8259                 /* Walk through the pd_lobby, looking for skbs that
8260                  * need moved to the new socket.
8261                  */
8262                 sctp_skb_for_each(skb, &oldsp->pd_lobby, tmp) {
8263                         event = sctp_skb2event(skb);
8264                         if (event->asoc == assoc) {
8265                                 __skb_unlink(skb, &oldsp->pd_lobby);
8266                                 __skb_queue_tail(queue, skb);
8267                                 sctp_skb_set_owner_r_frag(skb, newsk);
8268                         }
8269                 }
8270
8271                 /* Clear up any skbs waiting for the partial
8272                  * delivery to finish.
8273                  */
8274                 if (assoc->ulpq.pd_mode)
8275                         sctp_clear_pd(oldsk, NULL);
8276
8277         }
8278
8279         sctp_skb_for_each(skb, &assoc->ulpq.reasm, tmp)
8280                 sctp_skb_set_owner_r_frag(skb, newsk);
8281
8282         sctp_skb_for_each(skb, &assoc->ulpq.lobby, tmp)
8283                 sctp_skb_set_owner_r_frag(skb, newsk);
8284
8285         /* Set the type of socket to indicate that it is peeled off from the
8286          * original UDP-style socket or created with the accept() call on a
8287          * TCP-style socket..
8288          */
8289         newsp->type = type;
8290
8291         /* Mark the new socket "in-use" by the user so that any packets
8292          * that may arrive on the association after we've moved it are
8293          * queued to the backlog.  This prevents a potential race between
8294          * backlog processing on the old socket and new-packet processing
8295          * on the new socket.
8296          *
8297          * The caller has just allocated newsk so we can guarantee that other
8298          * paths won't try to lock it and then oldsk.
8299          */
8300         lock_sock_nested(newsk, SINGLE_DEPTH_NESTING);
8301         sctp_assoc_migrate(assoc, newsk);
8302
8303         /* If the association on the newsk is already closed before accept()
8304          * is called, set RCV_SHUTDOWN flag.
8305          */
8306         if (sctp_state(assoc, CLOSED) && sctp_style(newsk, TCP)) {
8307                 newsk->sk_state = SCTP_SS_CLOSED;
8308                 newsk->sk_shutdown |= RCV_SHUTDOWN;
8309         } else {
8310                 newsk->sk_state = SCTP_SS_ESTABLISHED;
8311         }
8312
8313         release_sock(newsk);
8314 }
8315
8316
8317 /* This proto struct describes the ULP interface for SCTP.  */
8318 struct proto sctp_prot = {
8319         .name        =  "SCTP",
8320         .owner       =  THIS_MODULE,
8321         .close       =  sctp_close,
8322         .connect     =  sctp_connect,
8323         .disconnect  =  sctp_disconnect,
8324         .accept      =  sctp_accept,
8325         .ioctl       =  sctp_ioctl,
8326         .init        =  sctp_init_sock,
8327         .destroy     =  sctp_destroy_sock,
8328         .shutdown    =  sctp_shutdown,
8329         .setsockopt  =  sctp_setsockopt,
8330         .getsockopt  =  sctp_getsockopt,
8331         .sendmsg     =  sctp_sendmsg,
8332         .recvmsg     =  sctp_recvmsg,
8333         .bind        =  sctp_bind,
8334         .backlog_rcv =  sctp_backlog_rcv,
8335         .hash        =  sctp_hash,
8336         .unhash      =  sctp_unhash,
8337         .get_port    =  sctp_get_port,
8338         .obj_size    =  sizeof(struct sctp_sock),
8339         .sysctl_mem  =  sysctl_sctp_mem,
8340         .sysctl_rmem =  sysctl_sctp_rmem,
8341         .sysctl_wmem =  sysctl_sctp_wmem,
8342         .memory_pressure = &sctp_memory_pressure,
8343         .enter_memory_pressure = sctp_enter_memory_pressure,
8344         .memory_allocated = &sctp_memory_allocated,
8345         .sockets_allocated = &sctp_sockets_allocated,
8346 };
8347
8348 #if IS_ENABLED(CONFIG_IPV6)
8349
8350 #include <net/transp_v6.h>
8351 static void sctp_v6_destroy_sock(struct sock *sk)
8352 {
8353         sctp_destroy_sock(sk);
8354         inet6_destroy_sock(sk);
8355 }
8356
8357 struct proto sctpv6_prot = {
8358         .name           = "SCTPv6",
8359         .owner          = THIS_MODULE,
8360         .close          = sctp_close,
8361         .connect        = sctp_connect,
8362         .disconnect     = sctp_disconnect,
8363         .accept         = sctp_accept,
8364         .ioctl          = sctp_ioctl,
8365         .init           = sctp_init_sock,
8366         .destroy        = sctp_v6_destroy_sock,
8367         .shutdown       = sctp_shutdown,
8368         .setsockopt     = sctp_setsockopt,
8369         .getsockopt     = sctp_getsockopt,
8370         .sendmsg        = sctp_sendmsg,
8371         .recvmsg        = sctp_recvmsg,
8372         .bind           = sctp_bind,
8373         .backlog_rcv    = sctp_backlog_rcv,
8374         .hash           = sctp_hash,
8375         .unhash         = sctp_unhash,
8376         .get_port       = sctp_get_port,
8377         .obj_size       = sizeof(struct sctp6_sock),
8378         .sysctl_mem     = sysctl_sctp_mem,
8379         .sysctl_rmem    = sysctl_sctp_rmem,
8380         .sysctl_wmem    = sysctl_sctp_wmem,
8381         .memory_pressure = &sctp_memory_pressure,
8382         .enter_memory_pressure = sctp_enter_memory_pressure,
8383         .memory_allocated = &sctp_memory_allocated,
8384         .sockets_allocated = &sctp_sockets_allocated,
8385 };
8386 #endif /* IS_ENABLED(CONFIG_IPV6) */