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