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