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