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