~ [ source navigation ] ~ [ diff markup ] ~ [ identifier search ] ~

TOMOYO Linux Cross Reference
Linux/net/sctp/socket.c

Version: ~ [ linux-5.8-rc4 ] ~ [ linux-5.7.7 ] ~ [ linux-5.6.19 ] ~ [ linux-5.5.19 ] ~ [ linux-5.4.50 ] ~ [ linux-5.3.18 ] ~ [ linux-5.2.21 ] ~ [ linux-5.1.21 ] ~ [ linux-5.0.21 ] ~ [ linux-4.20.17 ] ~ [ linux-4.19.131 ] ~ [ linux-4.18.20 ] ~ [ linux-4.17.19 ] ~ [ linux-4.16.18 ] ~ [ linux-4.15.18 ] ~ [ linux-4.14.187 ] ~ [ linux-4.13.16 ] ~ [ linux-4.12.14 ] ~ [ linux-4.11.12 ] ~ [ linux-4.10.17 ] ~ [ linux-4.9.229 ] ~ [ linux-4.8.17 ] ~ [ linux-4.7.10 ] ~ [ linux-4.6.7 ] ~ [ linux-4.5.7 ] ~ [ linux-4.4.229 ] ~ [ linux-4.3.6 ] ~ [ linux-4.2.8 ] ~ [ linux-4.1.52 ] ~ [ linux-4.0.9 ] ~ [ linux-3.19.8 ] ~ [ linux-3.18.140 ] ~ [ linux-3.17.8 ] ~ [ linux-3.16.85 ] ~ [ linux-3.15.10 ] ~ [ linux-3.14.79 ] ~ [ linux-3.13.11 ] ~ [ linux-3.12.74 ] ~ [ linux-3.11.10 ] ~ [ linux-3.10.108 ] ~ [ linux-2.6.32.71 ] ~ [ linux-2.6.0 ] ~ [ linux-2.4.37.11 ] ~ [ unix-v6-master ] ~ [ ccs-tools-1.8.5 ] ~ [ policy-sample ] ~
Architecture: ~ [ i386 ] ~ [ alpha ] ~ [ m68k ] ~ [ mips ] ~ [ ppc ] ~ [ sparc ] ~ [ sparc64 ] ~

  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, write to
 32  * the Free Software Foundation, 59 Temple Place - Suite 330,
 33  * Boston, MA 02111-1307, USA.
 34  *
 35  * Please send any bug reports or fixes you make to the
 36  * email address(es):
 37  *    lksctp developers <lksctp-developers@lists.sourceforge.net>
 38  *
 39  * Or submit a bug report through the following website:
 40  *    http://www.sf.net/projects/lksctp
 41  *
 42  * Written or modified by:
 43  *    La Monte H.P. Yarroll <piggy@acm.org>
 44  *    Narasimha Budihal     <narsi@refcode.org>
 45  *    Karl Knutson          <karl@athena.chicago.il.us>
 46  *    Jon Grimm             <jgrimm@us.ibm.com>
 47  *    Xingang Guo           <xingang.guo@intel.com>
 48  *    Daisy Chang           <daisyc@us.ibm.com>
 49  *    Sridhar Samudrala     <samudrala@us.ibm.com>
 50  *    Inaky Perez-Gonzalez  <inaky.gonzalez@intel.com>
 51  *    Ardelle Fan           <ardelle.fan@intel.com>
 52  *    Ryan Layer            <rmlayer@us.ibm.com>
 53  *    Anup Pemmaiah         <pemmaiah@cc.usu.edu>
 54  *    Kevin Gao             <kevin.gao@intel.com>
 55  *
 56  * Any bugs reported given to us we will try to fix... any fixes shared will
 57  * be incorporated into the next SCTP release.
 58  */
 59 
 60 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
 61 
 62 #include <linux/types.h>
 63 #include <linux/kernel.h>
 64 #include <linux/wait.h>
 65 #include <linux/time.h>
 66 #include <linux/ip.h>
 67 #include <linux/capability.h>
 68 #include <linux/fcntl.h>
 69 #include <linux/poll.h>
 70 #include <linux/init.h>
 71 #include <linux/crypto.h>
 72 #include <linux/slab.h>
 73 #include <linux/file.h>
 74 
 75 #include <net/ip.h>
 76 #include <net/icmp.h>
 77 #include <net/route.h>
 78 #include <net/ipv6.h>
 79 #include <net/inet_common.h>
 80 
 81 #include <linux/socket.h> /* for sa_family_t */
 82 #include <linux/export.h>
 83 #include <net/sock.h>
 84 #include <net/sctp/sctp.h>
 85 #include <net/sctp/sm.h>
 86 
 87 /* Forward declarations for internal helper functions. */
 88 static int sctp_writeable(struct sock *sk);
 89 static void sctp_wfree(struct sk_buff *skb);
 90 static int sctp_wait_for_sndbuf(struct sctp_association *, long *timeo_p,
 91                                 size_t msg_len);
 92 static int sctp_wait_for_packet(struct sock * sk, int *err, long *timeo_p);
 93 static int sctp_wait_for_connect(struct sctp_association *, long *timeo_p);
 94 static int sctp_wait_for_accept(struct sock *sk, long timeo);
 95 static void sctp_wait_for_close(struct sock *sk, long timeo);
 96 static void sctp_destruct_sock(struct sock *sk);
 97 static struct sctp_af *sctp_sockaddr_af(struct sctp_sock *opt,
 98                                         union sctp_addr *addr, int len);
 99 static int sctp_bindx_add(struct sock *, struct sockaddr *, int);
100 static int sctp_bindx_rem(struct sock *, struct sockaddr *, int);
101 static int sctp_send_asconf_add_ip(struct sock *, struct sockaddr *, int);
102 static int sctp_send_asconf_del_ip(struct sock *, struct sockaddr *, int);
103 static int sctp_send_asconf(struct sctp_association *asoc,
104                             struct sctp_chunk *chunk);
105 static int sctp_do_bind(struct sock *, union sctp_addr *, int);
106 static int sctp_autobind(struct sock *sk);
107 static void sctp_sock_migrate(struct sock *, struct sock *,
108                               struct sctp_association *, sctp_socket_type_t);
109 
110 extern struct kmem_cache *sctp_bucket_cachep;
111 extern long sysctl_sctp_mem[3];
112 extern int sysctl_sctp_rmem[3];
113 extern int sysctl_sctp_wmem[3];
114 
115 static int sctp_memory_pressure;
116 static atomic_long_t sctp_memory_allocated;
117 struct percpu_counter sctp_sockets_allocated;
118 
119 static void sctp_enter_memory_pressure(struct sock *sk)
120 {
121         sctp_memory_pressure = 1;
122 }
123 
124 
125 /* Get the sndbuf space available at the time on the association.  */
126 static inline int sctp_wspace(struct sctp_association *asoc)
127 {
128         int amt;
129 
130         if (asoc->ep->sndbuf_policy)
131                 amt = asoc->sndbuf_used;
132         else
133                 amt = sk_wmem_alloc_get(asoc->base.sk);
134 
135         if (amt >= asoc->base.sk->sk_sndbuf) {
136                 if (asoc->base.sk->sk_userlocks & SOCK_SNDBUF_LOCK)
137                         amt = 0;
138                 else {
139                         amt = sk_stream_wspace(asoc->base.sk);
140                         if (amt < 0)
141                                 amt = 0;
142                 }
143         } else {
144                 amt = asoc->base.sk->sk_sndbuf - amt;
145         }
146         return amt;
147 }
148 
149 /* Increment the used sndbuf space count of the corresponding association by
150  * the size of the outgoing data chunk.
151  * Also, set the skb destructor for sndbuf accounting later.
152  *
153  * Since it is always 1-1 between chunk and skb, and also a new skb is always
154  * allocated for chunk bundling in sctp_packet_transmit(), we can use the
155  * destructor in the data chunk skb for the purpose of the sndbuf space
156  * tracking.
157  */
158 static inline void sctp_set_owner_w(struct sctp_chunk *chunk)
159 {
160         struct sctp_association *asoc = chunk->asoc;
161         struct sock *sk = asoc->base.sk;
162 
163         /* The sndbuf space is tracked per association.  */
164         sctp_association_hold(asoc);
165 
166         skb_set_owner_w(chunk->skb, sk);
167 
168         chunk->skb->destructor = sctp_wfree;
169         /* Save the chunk pointer in skb for sctp_wfree to use later.  */
170         *((struct sctp_chunk **)(chunk->skb->cb)) = chunk;
171 
172         asoc->sndbuf_used += SCTP_DATA_SNDSIZE(chunk) +
173                                 sizeof(struct sk_buff) +
174                                 sizeof(struct sctp_chunk);
175 
176         atomic_add(sizeof(struct sctp_chunk), &sk->sk_wmem_alloc);
177         sk->sk_wmem_queued += chunk->skb->truesize;
178         sk_mem_charge(sk, chunk->skb->truesize);
179 }
180 
181 /* Verify that this is a valid address. */
182 static inline int sctp_verify_addr(struct sock *sk, union sctp_addr *addr,
183                                    int len)
184 {
185         struct sctp_af *af;
186 
187         /* Verify basic sockaddr. */
188         af = sctp_sockaddr_af(sctp_sk(sk), addr, len);
189         if (!af)
190                 return -EINVAL;
191 
192         /* Is this a valid SCTP address?  */
193         if (!af->addr_valid(addr, sctp_sk(sk), NULL))
194                 return -EINVAL;
195 
196         if (!sctp_sk(sk)->pf->send_verify(sctp_sk(sk), (addr)))
197                 return -EINVAL;
198 
199         return 0;
200 }
201 
202 /* Look up the association by its id.  If this is not a UDP-style
203  * socket, the ID field is always ignored.
204  */
205 struct sctp_association *sctp_id2assoc(struct sock *sk, sctp_assoc_t id)
206 {
207         struct sctp_association *asoc = NULL;
208 
209         /* If this is not a UDP-style socket, assoc id should be ignored. */
210         if (!sctp_style(sk, UDP)) {
211                 /* Return NULL if the socket state is not ESTABLISHED. It
212                  * could be a TCP-style listening socket or a socket which
213                  * hasn't yet called connect() to establish an association.
214                  */
215                 if (!sctp_sstate(sk, ESTABLISHED))
216                         return NULL;
217 
218                 /* Get the first and the only association from the list. */
219                 if (!list_empty(&sctp_sk(sk)->ep->asocs))
220                         asoc = list_entry(sctp_sk(sk)->ep->asocs.next,
221                                           struct sctp_association, asocs);
222                 return asoc;
223         }
224 
225         /* Otherwise this is a UDP-style socket. */
226         if (!id || (id == (sctp_assoc_t)-1))
227                 return NULL;
228 
229         spin_lock_bh(&sctp_assocs_id_lock);
230         asoc = (struct sctp_association *)idr_find(&sctp_assocs_id, (int)id);
231         spin_unlock_bh(&sctp_assocs_id_lock);
232 
233         if (!asoc || (asoc->base.sk != sk) || asoc->base.dead)
234                 return NULL;
235 
236         return asoc;
237 }
238 
239 /* Look up the transport from an address and an assoc id. If both address and
240  * id are specified, the associations matching the address and the id should be
241  * the same.
242  */
243 static struct sctp_transport *sctp_addr_id2transport(struct sock *sk,
244                                               struct sockaddr_storage *addr,
245                                               sctp_assoc_t id)
246 {
247         struct sctp_association *addr_asoc = NULL, *id_asoc = NULL;
248         struct sctp_transport *transport;
249         union sctp_addr *laddr = (union sctp_addr *)addr;
250 
251         addr_asoc = sctp_endpoint_lookup_assoc(sctp_sk(sk)->ep,
252                                                laddr,
253                                                &transport);
254 
255         if (!addr_asoc)
256                 return NULL;
257 
258         id_asoc = sctp_id2assoc(sk, id);
259         if (id_asoc && (id_asoc != addr_asoc))
260                 return NULL;
261 
262         sctp_get_pf_specific(sk->sk_family)->addr_v4map(sctp_sk(sk),
263                                                 (union sctp_addr *)addr);
264 
265         return transport;
266 }
267 
268 /* API 3.1.2 bind() - UDP Style Syntax
269  * The syntax of bind() is,
270  *
271  *   ret = bind(int sd, struct sockaddr *addr, int addrlen);
272  *
273  *   sd      - the socket descriptor returned by socket().
274  *   addr    - the address structure (struct sockaddr_in or struct
275  *             sockaddr_in6 [RFC 2553]),
276  *   addr_len - the size of the address structure.
277  */
278 static int sctp_bind(struct sock *sk, struct sockaddr *addr, int addr_len)
279 {
280         int retval = 0;
281 
282         sctp_lock_sock(sk);
283 
284         pr_debug("%s: sk:%p, addr:%p, addr_len:%d\n", __func__, sk,
285                  addr, addr_len);
286 
287         /* Disallow binding twice. */
288         if (!sctp_sk(sk)->ep->base.bind_addr.port)
289                 retval = sctp_do_bind(sk, (union sctp_addr *)addr,
290                                       addr_len);
291         else
292                 retval = -EINVAL;
293 
294         sctp_release_sock(sk);
295 
296         return retval;
297 }
298 
299 static long sctp_get_port_local(struct sock *, union sctp_addr *);
300 
301 /* Verify this is a valid sockaddr. */
302 static struct sctp_af *sctp_sockaddr_af(struct sctp_sock *opt,
303                                         union sctp_addr *addr, int len)
304 {
305         struct sctp_af *af;
306 
307         /* Check minimum size.  */
308         if (len < sizeof (struct sockaddr))
309                 return NULL;
310 
311         /* V4 mapped address are really of AF_INET family */
312         if (addr->sa.sa_family == AF_INET6 &&
313             ipv6_addr_v4mapped(&addr->v6.sin6_addr)) {
314                 if (!opt->pf->af_supported(AF_INET, opt))
315                         return NULL;
316         } else {
317                 /* Does this PF support this AF? */
318                 if (!opt->pf->af_supported(addr->sa.sa_family, opt))
319                         return NULL;
320         }
321 
322         /* If we get this far, af is valid. */
323         af = sctp_get_af_specific(addr->sa.sa_family);
324 
325         if (len < af->sockaddr_len)
326                 return NULL;
327 
328         return af;
329 }
330 
331 /* Bind a local address either to an endpoint or to an association.  */
332 static int sctp_do_bind(struct sock *sk, union sctp_addr *addr, int len)
333 {
334         struct net *net = sock_net(sk);
335         struct sctp_sock *sp = sctp_sk(sk);
336         struct sctp_endpoint *ep = sp->ep;
337         struct sctp_bind_addr *bp = &ep->base.bind_addr;
338         struct sctp_af *af;
339         unsigned short snum;
340         int ret = 0;
341 
342         /* Common sockaddr verification. */
343         af = sctp_sockaddr_af(sp, addr, len);
344         if (!af) {
345                 pr_debug("%s: sk:%p, newaddr:%p, len:%d EINVAL\n",
346                          __func__, sk, addr, len);
347                 return -EINVAL;
348         }
349 
350         snum = ntohs(addr->v4.sin_port);
351 
352         pr_debug("%s: sk:%p, new addr:%pISc, port:%d, new port:%d, len:%d\n",
353                  __func__, sk, &addr->sa, bp->port, snum, len);
354 
355         /* PF specific bind() address verification. */
356         if (!sp->pf->bind_verify(sp, addr))
357                 return -EADDRNOTAVAIL;
358 
359         /* We must either be unbound, or bind to the same port.
360          * It's OK to allow 0 ports if we are already bound.
361          * We'll just inhert an already bound port in this case
362          */
363         if (bp->port) {
364                 if (!snum)
365                         snum = bp->port;
366                 else if (snum != bp->port) {
367                         pr_debug("%s: new port %d doesn't match existing port "
368                                  "%d\n", __func__, snum, bp->port);
369                         return -EINVAL;
370                 }
371         }
372 
373         if (snum && snum < PROT_SOCK &&
374             !ns_capable(net->user_ns, CAP_NET_BIND_SERVICE))
375                 return -EACCES;
376 
377         /* See if the address matches any of the addresses we may have
378          * already bound before checking against other endpoints.
379          */
380         if (sctp_bind_addr_match(bp, addr, sp))
381                 return -EINVAL;
382 
383         /* Make sure we are allowed to bind here.
384          * The function sctp_get_port_local() does duplicate address
385          * detection.
386          */
387         addr->v4.sin_port = htons(snum);
388         if ((ret = sctp_get_port_local(sk, addr))) {
389                 return -EADDRINUSE;
390         }
391 
392         /* Refresh ephemeral port.  */
393         if (!bp->port)
394                 bp->port = inet_sk(sk)->inet_num;
395 
396         /* Add the address to the bind address list.
397          * Use GFP_ATOMIC since BHs will be disabled.
398          */
399         ret = sctp_add_bind_addr(bp, addr, SCTP_ADDR_SRC, GFP_ATOMIC);
400 
401         /* Copy back into socket for getsockname() use. */
402         if (!ret) {
403                 inet_sk(sk)->inet_sport = htons(inet_sk(sk)->inet_num);
404                 af->to_sk_saddr(addr, sk);
405         }
406 
407         return ret;
408 }
409 
410  /* ADDIP Section 4.1.1 Congestion Control of ASCONF Chunks
411  *
412  * R1) One and only one ASCONF Chunk MAY be in transit and unacknowledged
413  * at any one time.  If a sender, after sending an ASCONF chunk, decides
414  * it needs to transfer another ASCONF Chunk, it MUST wait until the
415  * ASCONF-ACK Chunk returns from the previous ASCONF Chunk before sending a
416  * subsequent ASCONF. Note this restriction binds each side, so at any
417  * time two ASCONF may be in-transit on any given association (one sent
418  * from each endpoint).
419  */
420 static int sctp_send_asconf(struct sctp_association *asoc,
421                             struct sctp_chunk *chunk)
422 {
423         struct net      *net = sock_net(asoc->base.sk);
424         int             retval = 0;
425 
426         /* If there is an outstanding ASCONF chunk, queue it for later
427          * transmission.
428          */
429         if (asoc->addip_last_asconf) {
430                 list_add_tail(&chunk->list, &asoc->addip_chunk_list);
431                 goto out;
432         }
433 
434         /* Hold the chunk until an ASCONF_ACK is received. */
435         sctp_chunk_hold(chunk);
436         retval = sctp_primitive_ASCONF(net, asoc, chunk);
437         if (retval)
438                 sctp_chunk_free(chunk);
439         else
440                 asoc->addip_last_asconf = chunk;
441 
442 out:
443         return retval;
444 }
445 
446 /* Add a list of addresses as bind addresses to local endpoint or
447  * association.
448  *
449  * Basically run through each address specified in the addrs/addrcnt
450  * array/length pair, determine if it is IPv6 or IPv4 and call
451  * sctp_do_bind() on it.
452  *
453  * If any of them fails, then the operation will be reversed and the
454  * ones that were added will be removed.
455  *
456  * Only sctp_setsockopt_bindx() is supposed to call this function.
457  */
458 static int sctp_bindx_add(struct sock *sk, struct sockaddr *addrs, int addrcnt)
459 {
460         int cnt;
461         int retval = 0;
462         void *addr_buf;
463         struct sockaddr *sa_addr;
464         struct sctp_af *af;
465 
466         pr_debug("%s: sk:%p, addrs:%p, addrcnt:%d\n", __func__, sk,
467                  addrs, addrcnt);
468 
469         addr_buf = addrs;
470         for (cnt = 0; cnt < addrcnt; cnt++) {
471                 /* The list may contain either IPv4 or IPv6 address;
472                  * determine the address length for walking thru the list.
473                  */
474                 sa_addr = addr_buf;
475                 af = sctp_get_af_specific(sa_addr->sa_family);
476                 if (!af) {
477                         retval = -EINVAL;
478                         goto err_bindx_add;
479                 }
480 
481                 retval = sctp_do_bind(sk, (union sctp_addr *)sa_addr,
482                                       af->sockaddr_len);
483 
484                 addr_buf += af->sockaddr_len;
485 
486 err_bindx_add:
487                 if (retval < 0) {
488                         /* Failed. Cleanup the ones that have been added */
489                         if (cnt > 0)
490                                 sctp_bindx_rem(sk, addrs, cnt);
491                         return retval;
492                 }
493         }
494 
495         return retval;
496 }
497 
498 /* Send an ASCONF chunk with Add IP address parameters to all the peers of the
499  * associations that are part of the endpoint indicating that a list of local
500  * addresses are added to the endpoint.
501  *
502  * If any of the addresses is already in the bind address list of the
503  * association, we do not send the chunk for that association.  But it will not
504  * affect other associations.
505  *
506  * Only sctp_setsockopt_bindx() is supposed to call this function.
507  */
508 static int sctp_send_asconf_add_ip(struct sock          *sk,
509                                    struct sockaddr      *addrs,
510                                    int                  addrcnt)
511 {
512         struct net *net = sock_net(sk);
513         struct sctp_sock                *sp;
514         struct sctp_endpoint            *ep;
515         struct sctp_association         *asoc;
516         struct sctp_bind_addr           *bp;
517         struct sctp_chunk               *chunk;
518         struct sctp_sockaddr_entry      *laddr;
519         union sctp_addr                 *addr;
520         union sctp_addr                 saveaddr;
521         void                            *addr_buf;
522         struct sctp_af                  *af;
523         struct list_head                *p;
524         int                             i;
525         int                             retval = 0;
526 
527         if (!net->sctp.addip_enable)
528                 return retval;
529 
530         sp = sctp_sk(sk);
531         ep = sp->ep;
532 
533         pr_debug("%s: sk:%p, addrs:%p, addrcnt:%d\n",
534                  __func__, sk, addrs, addrcnt);
535 
536         list_for_each_entry(asoc, &ep->asocs, asocs) {
537                 if (!asoc->peer.asconf_capable)
538                         continue;
539 
540                 if (asoc->peer.addip_disabled_mask & SCTP_PARAM_ADD_IP)
541                         continue;
542 
543                 if (!sctp_state(asoc, ESTABLISHED))
544                         continue;
545 
546                 /* Check if any address in the packed array of addresses is
547                  * in the bind address list of the association. If so,
548                  * do not send the asconf chunk to its peer, but continue with
549                  * other associations.
550                  */
551                 addr_buf = addrs;
552                 for (i = 0; i < addrcnt; i++) {
553                         addr = addr_buf;
554                         af = sctp_get_af_specific(addr->v4.sin_family);
555                         if (!af) {
556                                 retval = -EINVAL;
557                                 goto out;
558                         }
559 
560                         if (sctp_assoc_lookup_laddr(asoc, addr))
561                                 break;
562 
563                         addr_buf += af->sockaddr_len;
564                 }
565                 if (i < addrcnt)
566                         continue;
567 
568                 /* Use the first valid address in bind addr list of
569                  * association as Address Parameter of ASCONF CHUNK.
570                  */
571                 bp = &asoc->base.bind_addr;
572                 p = bp->address_list.next;
573                 laddr = list_entry(p, struct sctp_sockaddr_entry, list);
574                 chunk = sctp_make_asconf_update_ip(asoc, &laddr->a, addrs,
575                                                    addrcnt, SCTP_PARAM_ADD_IP);
576                 if (!chunk) {
577                         retval = -ENOMEM;
578                         goto out;
579                 }
580 
581                 /* Add the new addresses to the bind address list with
582                  * use_as_src set to 0.
583                  */
584                 addr_buf = addrs;
585                 for (i = 0; i < addrcnt; i++) {
586                         addr = addr_buf;
587                         af = sctp_get_af_specific(addr->v4.sin_family);
588                         memcpy(&saveaddr, addr, af->sockaddr_len);
589                         retval = sctp_add_bind_addr(bp, &saveaddr,
590                                                     SCTP_ADDR_NEW, GFP_ATOMIC);
591                         addr_buf += af->sockaddr_len;
592                 }
593                 if (asoc->src_out_of_asoc_ok) {
594                         struct sctp_transport *trans;
595 
596                         list_for_each_entry(trans,
597                             &asoc->peer.transport_addr_list, transports) {
598                                 /* Clear the source and route cache */
599                                 dst_release(trans->dst);
600                                 trans->cwnd = min(4*asoc->pathmtu, max_t(__u32,
601                                     2*asoc->pathmtu, 4380));
602                                 trans->ssthresh = asoc->peer.i.a_rwnd;
603                                 trans->rto = asoc->rto_initial;
604                                 sctp_max_rto(asoc, trans);
605                                 trans->rtt = trans->srtt = trans->rttvar = 0;
606                                 sctp_transport_route(trans, NULL,
607                                     sctp_sk(asoc->base.sk));
608                         }
609                 }
610                 retval = sctp_send_asconf(asoc, chunk);
611         }
612 
613 out:
614         return retval;
615 }
616 
617 /* Remove a list of addresses from bind addresses list.  Do not remove the
618  * last address.
619  *
620  * Basically run through each address specified in the addrs/addrcnt
621  * array/length pair, determine if it is IPv6 or IPv4 and call
622  * sctp_del_bind() on it.
623  *
624  * If any of them fails, then the operation will be reversed and the
625  * ones that were removed will be added back.
626  *
627  * At least one address has to be left; if only one address is
628  * available, the operation will return -EBUSY.
629  *
630  * Only sctp_setsockopt_bindx() is supposed to call this function.
631  */
632 static int sctp_bindx_rem(struct sock *sk, struct sockaddr *addrs, int addrcnt)
633 {
634         struct sctp_sock *sp = sctp_sk(sk);
635         struct sctp_endpoint *ep = sp->ep;
636         int cnt;
637         struct sctp_bind_addr *bp = &ep->base.bind_addr;
638         int retval = 0;
639         void *addr_buf;
640         union sctp_addr *sa_addr;
641         struct sctp_af *af;
642 
643         pr_debug("%s: sk:%p, addrs:%p, addrcnt:%d\n",
644                  __func__, sk, addrs, addrcnt);
645 
646         addr_buf = addrs;
647         for (cnt = 0; cnt < addrcnt; cnt++) {
648                 /* If the bind address list is empty or if there is only one
649                  * bind address, there is nothing more to be removed (we need
650                  * at least one address here).
651                  */
652                 if (list_empty(&bp->address_list) ||
653                     (sctp_list_single_entry(&bp->address_list))) {
654                         retval = -EBUSY;
655                         goto err_bindx_rem;
656                 }
657 
658                 sa_addr = addr_buf;
659                 af = sctp_get_af_specific(sa_addr->sa.sa_family);
660                 if (!af) {
661                         retval = -EINVAL;
662                         goto err_bindx_rem;
663                 }
664 
665                 if (!af->addr_valid(sa_addr, sp, NULL)) {
666                         retval = -EADDRNOTAVAIL;
667                         goto err_bindx_rem;
668                 }
669 
670                 if (sa_addr->v4.sin_port &&
671                     sa_addr->v4.sin_port != htons(bp->port)) {
672                         retval = -EINVAL;
673                         goto err_bindx_rem;
674                 }
675 
676                 if (!sa_addr->v4.sin_port)
677                         sa_addr->v4.sin_port = htons(bp->port);
678 
679                 /* FIXME - There is probably a need to check if sk->sk_saddr and
680                  * sk->sk_rcv_addr are currently set to one of the addresses to
681                  * be removed. This is something which needs to be looked into
682                  * when we are fixing the outstanding issues with multi-homing
683                  * socket routing and failover schemes. Refer to comments in
684                  * sctp_do_bind(). -daisy
685                  */
686                 retval = sctp_del_bind_addr(bp, sa_addr);
687 
688                 addr_buf += af->sockaddr_len;
689 err_bindx_rem:
690                 if (retval < 0) {
691                         /* Failed. Add the ones that has been removed back */
692                         if (cnt > 0)
693                                 sctp_bindx_add(sk, addrs, cnt);
694                         return retval;
695                 }
696         }
697 
698         return retval;
699 }
700 
701 /* Send an ASCONF chunk with Delete IP address parameters to all the peers of
702  * the associations that are part of the endpoint indicating that a list of
703  * local addresses are removed from the endpoint.
704  *
705  * If any of the addresses is already in the bind address list of the
706  * association, we do not send the chunk for that association.  But it will not
707  * affect other associations.
708  *
709  * Only sctp_setsockopt_bindx() is supposed to call this function.
710  */
711 static int sctp_send_asconf_del_ip(struct sock          *sk,
712                                    struct sockaddr      *addrs,
713                                    int                  addrcnt)
714 {
715         struct net *net = sock_net(sk);
716         struct sctp_sock        *sp;
717         struct sctp_endpoint    *ep;
718         struct sctp_association *asoc;
719         struct sctp_transport   *transport;
720         struct sctp_bind_addr   *bp;
721         struct sctp_chunk       *chunk;
722         union sctp_addr         *laddr;
723         void                    *addr_buf;
724         struct sctp_af          *af;
725         struct sctp_sockaddr_entry *saddr;
726         int                     i;
727         int                     retval = 0;
728         int                     stored = 0;
729 
730         chunk = NULL;
731         if (!net->sctp.addip_enable)
732                 return retval;
733 
734         sp = sctp_sk(sk);
735         ep = sp->ep;
736 
737         pr_debug("%s: sk:%p, addrs:%p, addrcnt:%d\n",
738                  __func__, sk, addrs, addrcnt);
739 
740         list_for_each_entry(asoc, &ep->asocs, asocs) {
741 
742                 if (!asoc->peer.asconf_capable)
743                         continue;
744 
745                 if (asoc->peer.addip_disabled_mask & SCTP_PARAM_DEL_IP)
746                         continue;
747 
748                 if (!sctp_state(asoc, ESTABLISHED))
749                         continue;
750 
751                 /* Check if any address in the packed array of addresses is
752                  * not present in the bind address list of the association.
753                  * If so, do not send the asconf chunk to its peer, but
754                  * continue with other associations.
755                  */
756                 addr_buf = addrs;
757                 for (i = 0; i < addrcnt; i++) {
758                         laddr = addr_buf;
759                         af = sctp_get_af_specific(laddr->v4.sin_family);
760                         if (!af) {
761                                 retval = -EINVAL;
762                                 goto out;
763                         }
764 
765                         if (!sctp_assoc_lookup_laddr(asoc, laddr))
766                                 break;
767 
768                         addr_buf += af->sockaddr_len;
769                 }
770                 if (i < addrcnt)
771                         continue;
772 
773                 /* Find one address in the association's bind address list
774                  * that is not in the packed array of addresses. This is to
775                  * make sure that we do not delete all the addresses in the
776                  * association.
777                  */
778                 bp = &asoc->base.bind_addr;
779                 laddr = sctp_find_unmatch_addr(bp, (union sctp_addr *)addrs,
780                                                addrcnt, sp);
781                 if ((laddr == NULL) && (addrcnt == 1)) {
782                         if (asoc->asconf_addr_del_pending)
783                                 continue;
784                         asoc->asconf_addr_del_pending =
785                             kzalloc(sizeof(union sctp_addr), GFP_ATOMIC);
786                         if (asoc->asconf_addr_del_pending == NULL) {
787                                 retval = -ENOMEM;
788                                 goto out;
789                         }
790                         asoc->asconf_addr_del_pending->sa.sa_family =
791                                     addrs->sa_family;
792                         asoc->asconf_addr_del_pending->v4.sin_port =
793                                     htons(bp->port);
794                         if (addrs->sa_family == AF_INET) {
795                                 struct sockaddr_in *sin;
796 
797                                 sin = (struct sockaddr_in *)addrs;
798                                 asoc->asconf_addr_del_pending->v4.sin_addr.s_addr = sin->sin_addr.s_addr;
799                         } else if (addrs->sa_family == AF_INET6) {
800                                 struct sockaddr_in6 *sin6;
801 
802                                 sin6 = (struct sockaddr_in6 *)addrs;
803                                 asoc->asconf_addr_del_pending->v6.sin6_addr = sin6->sin6_addr;
804                         }
805 
806                         pr_debug("%s: keep the last address asoc:%p %pISc at %p\n",
807                                  __func__, asoc, &asoc->asconf_addr_del_pending->sa,
808                                  asoc->asconf_addr_del_pending);
809 
810                         asoc->src_out_of_asoc_ok = 1;
811                         stored = 1;
812                         goto skip_mkasconf;
813                 }
814 
815                 if (laddr == NULL)
816                         return -EINVAL;
817 
818                 /* We do not need RCU protection throughout this loop
819                  * because this is done under a socket lock from the
820                  * setsockopt call.
821                  */
822                 chunk = sctp_make_asconf_update_ip(asoc, laddr, addrs, addrcnt,
823                                                    SCTP_PARAM_DEL_IP);
824                 if (!chunk) {
825                         retval = -ENOMEM;
826                         goto out;
827                 }
828 
829 skip_mkasconf:
830                 /* Reset use_as_src flag for the addresses in the bind address
831                  * list that are to be deleted.
832                  */
833                 addr_buf = addrs;
834                 for (i = 0; i < addrcnt; i++) {
835                         laddr = addr_buf;
836                         af = sctp_get_af_specific(laddr->v4.sin_family);
837                         list_for_each_entry(saddr, &bp->address_list, list) {
838                                 if (sctp_cmp_addr_exact(&saddr->a, laddr))
839                                         saddr->state = SCTP_ADDR_DEL;
840                         }
841                         addr_buf += af->sockaddr_len;
842                 }
843 
844                 /* Update the route and saddr entries for all the transports
845                  * as some of the addresses in the bind address list are
846                  * about to be deleted and cannot be used as source addresses.
847                  */
848                 list_for_each_entry(transport, &asoc->peer.transport_addr_list,
849                                         transports) {
850                         dst_release(transport->dst);
851                         sctp_transport_route(transport, NULL,
852                                              sctp_sk(asoc->base.sk));
853                 }
854 
855                 if (stored)
856                         /* We don't need to transmit ASCONF */
857                         continue;
858                 retval = sctp_send_asconf(asoc, chunk);
859         }
860 out:
861         return retval;
862 }
863 
864 /* set addr events to assocs in the endpoint.  ep and addr_wq must be locked */
865 int sctp_asconf_mgmt(struct sctp_sock *sp, struct sctp_sockaddr_entry *addrw)
866 {
867         struct sock *sk = sctp_opt2sk(sp);
868         union sctp_addr *addr;
869         struct sctp_af *af;
870 
871         /* It is safe to write port space in caller. */
872         addr = &addrw->a;
873         addr->v4.sin_port = htons(sp->ep->base.bind_addr.port);
874         af = sctp_get_af_specific(addr->sa.sa_family);
875         if (!af)
876                 return -EINVAL;
877         if (sctp_verify_addr(sk, addr, af->sockaddr_len))
878                 return -EINVAL;
879 
880         if (addrw->state == SCTP_ADDR_NEW)
881                 return sctp_send_asconf_add_ip(sk, (struct sockaddr *)addr, 1);
882         else
883                 return sctp_send_asconf_del_ip(sk, (struct sockaddr *)addr, 1);
884 }
885 
886 /* Helper for tunneling sctp_bindx() requests through sctp_setsockopt()
887  *
888  * API 8.1
889  * int sctp_bindx(int sd, struct sockaddr *addrs, int addrcnt,
890  *                int flags);
891  *
892  * If sd is an IPv4 socket, the addresses passed must be IPv4 addresses.
893  * If the sd is an IPv6 socket, the addresses passed can either be IPv4
894  * or IPv6 addresses.
895  *
896  * A single address may be specified as INADDR_ANY or IN6ADDR_ANY, see
897  * Section 3.1.2 for this usage.
898  *
899  * addrs is a pointer to an array of one or more socket addresses. Each
900  * address is contained in its appropriate structure (i.e. struct
901  * sockaddr_in or struct sockaddr_in6) the family of the address type
902  * must be used to distinguish the address length (note that this
903  * representation is termed a "packed array" of addresses). The caller
904  * specifies the number of addresses in the array with addrcnt.
905  *
906  * On success, sctp_bindx() returns 0. On failure, sctp_bindx() returns
907  * -1, and sets errno to the appropriate error code.
908  *
909  * For SCTP, the port given in each socket address must be the same, or
910  * sctp_bindx() will fail, setting errno to EINVAL.
911  *
912  * The flags parameter is formed from the bitwise OR of zero or more of
913  * the following currently defined flags:
914  *
915  * SCTP_BINDX_ADD_ADDR
916  *
917  * SCTP_BINDX_REM_ADDR
918  *
919  * SCTP_BINDX_ADD_ADDR directs SCTP to add the given addresses to the
920  * association, and SCTP_BINDX_REM_ADDR directs SCTP to remove the given
921  * addresses from the association. The two flags are mutually exclusive;
922  * if both are given, sctp_bindx() will fail with EINVAL. A caller may
923  * not remove all addresses from an association; sctp_bindx() will
924  * reject such an attempt with EINVAL.
925  *
926  * An application can use sctp_bindx(SCTP_BINDX_ADD_ADDR) to associate
927  * additional addresses with an endpoint after calling bind().  Or use
928  * sctp_bindx(SCTP_BINDX_REM_ADDR) to remove some addresses a listening
929  * socket is associated with so that no new association accepted will be
930  * associated with those addresses. If the endpoint supports dynamic
931  * address a SCTP_BINDX_REM_ADDR or SCTP_BINDX_ADD_ADDR may cause a
932  * endpoint to send the appropriate message to the peer to change the
933  * peers address lists.
934  *
935  * Adding and removing addresses from a connected association is
936  * optional functionality. Implementations that do not support this
937  * functionality should return EOPNOTSUPP.
938  *
939  * Basically do nothing but copying the addresses from user to kernel
940  * land and invoking either sctp_bindx_add() or sctp_bindx_rem() on the sk.
941  * This is used for tunneling the sctp_bindx() request through sctp_setsockopt()
942  * from userspace.
943  *
944  * We don't use copy_from_user() for optimization: we first do the
945  * sanity checks (buffer size -fast- and access check-healthy
946  * pointer); if all of those succeed, then we can alloc the memory
947  * (expensive operation) needed to copy the data to kernel. Then we do
948  * the copying without checking the user space area
949  * (__copy_from_user()).
950  *
951  * On exit there is no need to do sockfd_put(), sys_setsockopt() does
952  * it.
953  *
954  * sk        The sk of the socket
955  * addrs     The pointer to the addresses in user land
956  * addrssize Size of the addrs buffer
957  * op        Operation to perform (add or remove, see the flags of
958  *           sctp_bindx)
959  *
960  * Returns 0 if ok, <0 errno code on error.
961  */
962 static int sctp_setsockopt_bindx(struct sock* sk,
963                                  struct sockaddr __user *addrs,
964                                  int addrs_size, int op)
965 {
966         struct sockaddr *kaddrs;
967         int err;
968         int addrcnt = 0;
969         int walk_size = 0;
970         struct sockaddr *sa_addr;
971         void *addr_buf;
972         struct sctp_af *af;
973 
974         pr_debug("%s: sk:%p addrs:%p addrs_size:%d opt:%d\n",
975                  __func__, sk, addrs, addrs_size, op);
976 
977         if (unlikely(addrs_size <= 0))
978                 return -EINVAL;
979 
980         /* Check the user passed a healthy pointer.  */
981         if (unlikely(!access_ok(VERIFY_READ, addrs, addrs_size)))
982                 return -EFAULT;
983 
984         /* Alloc space for the address array in kernel memory.  */
985         kaddrs = kmalloc(addrs_size, GFP_KERNEL);
986         if (unlikely(!kaddrs))
987                 return -ENOMEM;
988 
989         if (__copy_from_user(kaddrs, addrs, addrs_size)) {
990                 kfree(kaddrs);
991                 return -EFAULT;
992         }
993 
994         /* Walk through the addrs buffer and count the number of addresses. */
995         addr_buf = kaddrs;
996         while (walk_size < addrs_size) {
997                 if (walk_size + sizeof(sa_family_t) > addrs_size) {
998                         kfree(kaddrs);
999                         return -EINVAL;
1000                 }
1001 
1002                 sa_addr = addr_buf;
1003                 af = sctp_get_af_specific(sa_addr->sa_family);
1004 
1005                 /* If the address family is not supported or if this address
1006                  * causes the address buffer to overflow return EINVAL.
1007                  */
1008                 if (!af || (walk_size + af->sockaddr_len) > addrs_size) {
1009                         kfree(kaddrs);
1010                         return -EINVAL;
1011                 }
1012                 addrcnt++;
1013                 addr_buf += af->sockaddr_len;
1014                 walk_size += af->sockaddr_len;
1015         }
1016 
1017         /* Do the work. */
1018         switch (op) {
1019         case SCTP_BINDX_ADD_ADDR:
1020                 err = sctp_bindx_add(sk, kaddrs, addrcnt);
1021                 if (err)
1022                         goto out;
1023                 err = sctp_send_asconf_add_ip(sk, kaddrs, addrcnt);
1024                 break;
1025 
1026         case SCTP_BINDX_REM_ADDR:
1027                 err = sctp_bindx_rem(sk, kaddrs, addrcnt);
1028                 if (err)
1029                         goto out;
1030                 err = sctp_send_asconf_del_ip(sk, kaddrs, addrcnt);
1031                 break;
1032 
1033         default:
1034                 err = -EINVAL;
1035                 break;
1036         }
1037 
1038 out:
1039         kfree(kaddrs);
1040 
1041         return err;
1042 }
1043 
1044 /* __sctp_connect(struct sock* sk, struct sockaddr *kaddrs, int addrs_size)
1045  *
1046  * Common routine for handling connect() and sctp_connectx().
1047  * Connect will come in with just a single address.
1048  */
1049 static int __sctp_connect(struct sock* sk,
1050                           struct sockaddr *kaddrs,
1051                           int addrs_size,
1052                           sctp_assoc_t *assoc_id)
1053 {
1054         struct net *net = sock_net(sk);
1055         struct sctp_sock *sp;
1056         struct sctp_endpoint *ep;
1057         struct sctp_association *asoc = NULL;
1058         struct sctp_association *asoc2;
1059         struct sctp_transport *transport;
1060         union sctp_addr to;
1061         struct sctp_af *af;
1062         sctp_scope_t scope;
1063         long timeo;
1064         int err = 0;
1065         int addrcnt = 0;
1066         int walk_size = 0;
1067         union sctp_addr *sa_addr = NULL;
1068         void *addr_buf;
1069         unsigned short port;
1070         unsigned int f_flags = 0;
1071 
1072         sp = sctp_sk(sk);
1073         ep = sp->ep;
1074 
1075         /* connect() cannot be done on a socket that is already in ESTABLISHED
1076          * state - UDP-style peeled off socket or a TCP-style socket that
1077          * is already connected.
1078          * It cannot be done even on a TCP-style listening socket.
1079          */
1080         if (sctp_sstate(sk, ESTABLISHED) ||
1081             (sctp_style(sk, TCP) && sctp_sstate(sk, LISTENING))) {
1082                 err = -EISCONN;
1083                 goto out_free;
1084         }
1085 
1086         /* Walk through the addrs buffer and count the number of addresses. */
1087         addr_buf = kaddrs;
1088         while (walk_size < addrs_size) {
1089                 if (walk_size + sizeof(sa_family_t) > addrs_size) {
1090                         err = -EINVAL;
1091                         goto out_free;
1092                 }
1093 
1094                 sa_addr = addr_buf;
1095                 af = sctp_get_af_specific(sa_addr->sa.sa_family);
1096 
1097                 /* If the address family is not supported or if this address
1098                  * causes the address buffer to overflow return EINVAL.
1099                  */
1100                 if (!af || (walk_size + af->sockaddr_len) > addrs_size) {
1101                         err = -EINVAL;
1102                         goto out_free;
1103                 }
1104 
1105                 port = ntohs(sa_addr->v4.sin_port);
1106 
1107                 /* Save current address so we can work with it */
1108                 memcpy(&to, sa_addr, af->sockaddr_len);
1109 
1110                 err = sctp_verify_addr(sk, &to, af->sockaddr_len);
1111                 if (err)
1112                         goto out_free;
1113 
1114                 /* Make sure the destination port is correctly set
1115                  * in all addresses.
1116                  */
1117                 if (asoc && asoc->peer.port && asoc->peer.port != port) {
1118                         err = -EINVAL;
1119                         goto out_free;
1120                 }
1121 
1122                 /* Check if there already is a matching association on the
1123                  * endpoint (other than the one created here).
1124                  */
1125                 asoc2 = sctp_endpoint_lookup_assoc(ep, &to, &transport);
1126                 if (asoc2 && asoc2 != asoc) {
1127                         if (asoc2->state >= SCTP_STATE_ESTABLISHED)
1128                                 err = -EISCONN;
1129                         else
1130                                 err = -EALREADY;
1131                         goto out_free;
1132                 }
1133 
1134                 /* If we could not find a matching association on the endpoint,
1135                  * make sure that there is no peeled-off association matching
1136                  * the peer address even on another socket.
1137                  */
1138                 if (sctp_endpoint_is_peeled_off(ep, &to)) {
1139                         err = -EADDRNOTAVAIL;
1140                         goto out_free;
1141                 }
1142 
1143                 if (!asoc) {
1144                         /* If a bind() or sctp_bindx() is not called prior to
1145                          * an sctp_connectx() call, the system picks an
1146                          * ephemeral port and will choose an address set
1147                          * equivalent to binding with a wildcard address.
1148                          */
1149                         if (!ep->base.bind_addr.port) {
1150                                 if (sctp_autobind(sk)) {
1151                                         err = -EAGAIN;
1152                                         goto out_free;
1153                                 }
1154                         } else {
1155                                 /*
1156                                  * If an unprivileged user inherits a 1-many
1157                                  * style socket with open associations on a
1158                                  * privileged port, it MAY be permitted to
1159                                  * accept new associations, but it SHOULD NOT
1160                                  * be permitted to open new associations.
1161                                  */
1162                                 if (ep->base.bind_addr.port < PROT_SOCK &&
1163                                     !ns_capable(net->user_ns, CAP_NET_BIND_SERVICE)) {
1164                                         err = -EACCES;
1165                                         goto out_free;
1166                                 }
1167                         }
1168 
1169                         scope = sctp_scope(&to);
1170                         asoc = sctp_association_new(ep, sk, scope, GFP_KERNEL);
1171                         if (!asoc) {
1172                                 err = -ENOMEM;
1173                                 goto out_free;
1174                         }
1175 
1176                         err = sctp_assoc_set_bind_addr_from_ep(asoc, scope,
1177                                                               GFP_KERNEL);
1178                         if (err < 0) {
1179                                 goto out_free;
1180                         }
1181 
1182                 }
1183 
1184                 /* Prime the peer's transport structures.  */
1185                 transport = sctp_assoc_add_peer(asoc, &to, GFP_KERNEL,
1186                                                 SCTP_UNKNOWN);
1187                 if (!transport) {
1188                         err = -ENOMEM;
1189                         goto out_free;
1190                 }
1191 
1192                 addrcnt++;
1193                 addr_buf += af->sockaddr_len;
1194                 walk_size += af->sockaddr_len;
1195         }
1196 
1197         /* In case the user of sctp_connectx() wants an association
1198          * id back, assign one now.
1199          */
1200         if (assoc_id) {
1201                 err = sctp_assoc_set_id(asoc, GFP_KERNEL);
1202                 if (err < 0)
1203                         goto out_free;
1204         }
1205 
1206         err = sctp_primitive_ASSOCIATE(net, asoc, NULL);
1207         if (err < 0) {
1208                 goto out_free;
1209         }
1210 
1211         /* Initialize sk's dport and daddr for getpeername() */
1212         inet_sk(sk)->inet_dport = htons(asoc->peer.port);
1213         af = sctp_get_af_specific(sa_addr->sa.sa_family);
1214         af->to_sk_daddr(sa_addr, sk);
1215         sk->sk_err = 0;
1216 
1217         /* in-kernel sockets don't generally have a file allocated to them
1218          * if all they do is call sock_create_kern().
1219          */
1220         if (sk->sk_socket->file)
1221                 f_flags = sk->sk_socket->file->f_flags;
1222 
1223         timeo = sock_sndtimeo(sk, f_flags & O_NONBLOCK);
1224 
1225         err = sctp_wait_for_connect(asoc, &timeo);
1226         if ((err == 0 || err == -EINPROGRESS) && assoc_id)
1227                 *assoc_id = asoc->assoc_id;
1228 
1229         /* Don't free association on exit. */
1230         asoc = NULL;
1231 
1232 out_free:
1233         pr_debug("%s: took out_free path with asoc:%p kaddrs:%p err:%d\n",
1234                  __func__, asoc, kaddrs, err);
1235 
1236         if (asoc) {
1237                 /* sctp_primitive_ASSOCIATE may have added this association
1238                  * To the hash table, try to unhash it, just in case, its a noop
1239                  * if it wasn't hashed so we're safe
1240                  */
1241                 sctp_unhash_established(asoc);
1242                 sctp_association_free(asoc);
1243         }
1244         return err;
1245 }
1246 
1247 /* Helper for tunneling sctp_connectx() requests through sctp_setsockopt()
1248  *
1249  * API 8.9
1250  * int sctp_connectx(int sd, struct sockaddr *addrs, int addrcnt,
1251  *                      sctp_assoc_t *asoc);
1252  *
1253  * If sd is an IPv4 socket, the addresses passed must be IPv4 addresses.
1254  * If the sd is an IPv6 socket, the addresses passed can either be IPv4
1255  * or IPv6 addresses.
1256  *
1257  * A single address may be specified as INADDR_ANY or IN6ADDR_ANY, see
1258  * Section 3.1.2 for this usage.
1259  *
1260  * addrs is a pointer to an array of one or more socket addresses. Each
1261  * address is contained in its appropriate structure (i.e. struct
1262  * sockaddr_in or struct sockaddr_in6) the family of the address type
1263  * must be used to distengish the address length (note that this
1264  * representation is termed a "packed array" of addresses). The caller
1265  * specifies the number of addresses in the array with addrcnt.
1266  *
1267  * On success, sctp_connectx() returns 0. It also sets the assoc_id to
1268  * the association id of the new association.  On failure, sctp_connectx()
1269  * returns -1, and sets errno to the appropriate error code.  The assoc_id
1270  * is not touched by the kernel.
1271  *
1272  * For SCTP, the port given in each socket address must be the same, or
1273  * sctp_connectx() will fail, setting errno to EINVAL.
1274  *
1275  * An application can use sctp_connectx to initiate an association with
1276  * an endpoint that is multi-homed.  Much like sctp_bindx() this call
1277  * allows a caller to specify multiple addresses at which a peer can be
1278  * reached.  The way the SCTP stack uses the list of addresses to set up
1279  * the association is implementation dependent.  This function only
1280  * specifies that the stack will try to make use of all the addresses in
1281  * the list when needed.
1282  *
1283  * Note that the list of addresses passed in is only used for setting up
1284  * the association.  It does not necessarily equal the set of addresses
1285  * the peer uses for the resulting association.  If the caller wants to
1286  * find out the set of peer addresses, it must use sctp_getpaddrs() to
1287  * retrieve them after the association has been set up.
1288  *
1289  * Basically do nothing but copying the addresses from user to kernel
1290  * land and invoking either sctp_connectx(). This is used for tunneling
1291  * the sctp_connectx() request through sctp_setsockopt() from userspace.
1292  *
1293  * We don't use copy_from_user() for optimization: we first do the
1294  * sanity checks (buffer size -fast- and access check-healthy
1295  * pointer); if all of those succeed, then we can alloc the memory
1296  * (expensive operation) needed to copy the data to kernel. Then we do
1297  * the copying without checking the user space area
1298  * (__copy_from_user()).
1299  *
1300  * On exit there is no need to do sockfd_put(), sys_setsockopt() does
1301  * it.
1302  *
1303  * sk        The sk of the socket
1304  * addrs     The pointer to the addresses in user land
1305  * addrssize Size of the addrs buffer
1306  *
1307  * Returns >=0 if ok, <0 errno code on error.
1308  */
1309 static int __sctp_setsockopt_connectx(struct sock* sk,
1310                                       struct sockaddr __user *addrs,
1311                                       int addrs_size,
1312                                       sctp_assoc_t *assoc_id)
1313 {
1314         int err = 0;
1315         struct sockaddr *kaddrs;
1316 
1317         pr_debug("%s: sk:%p addrs:%p addrs_size:%d\n",
1318                  __func__, sk, addrs, addrs_size);
1319 
1320         if (unlikely(addrs_size <= 0))
1321                 return -EINVAL;
1322 
1323         /* Check the user passed a healthy pointer.  */
1324         if (unlikely(!access_ok(VERIFY_READ, addrs, addrs_size)))
1325                 return -EFAULT;
1326 
1327         /* Alloc space for the address array in kernel memory.  */
1328         kaddrs = kmalloc(addrs_size, GFP_KERNEL);
1329         if (unlikely(!kaddrs))
1330                 return -ENOMEM;
1331 
1332         if (__copy_from_user(kaddrs, addrs, addrs_size)) {
1333                 err = -EFAULT;
1334         } else {
1335                 err = __sctp_connect(sk, kaddrs, addrs_size, assoc_id);
1336         }
1337 
1338         kfree(kaddrs);
1339 
1340         return err;
1341 }
1342 
1343 /*
1344  * This is an older interface.  It's kept for backward compatibility
1345  * to the option that doesn't provide association id.
1346  */
1347 static int sctp_setsockopt_connectx_old(struct sock* sk,
1348                                         struct sockaddr __user *addrs,
1349                                         int addrs_size)
1350 {
1351         return __sctp_setsockopt_connectx(sk, addrs, addrs_size, NULL);
1352 }
1353 
1354 /*
1355  * New interface for the API.  The since the API is done with a socket
1356  * option, to make it simple we feed back the association id is as a return
1357  * indication to the call.  Error is always negative and association id is
1358  * always positive.
1359  */
1360 static int sctp_setsockopt_connectx(struct sock* sk,
1361                                     struct sockaddr __user *addrs,
1362                                     int addrs_size)
1363 {
1364         sctp_assoc_t assoc_id = 0;
1365         int err = 0;
1366 
1367         err = __sctp_setsockopt_connectx(sk, addrs, addrs_size, &assoc_id);
1368 
1369         if (err)
1370                 return err;
1371         else
1372                 return assoc_id;
1373 }
1374 
1375 /*
1376  * New (hopefully final) interface for the API.
1377  * We use the sctp_getaddrs_old structure so that use-space library
1378  * can avoid any unnecessary allocations.   The only defferent part
1379  * is that we store the actual length of the address buffer into the
1380  * addrs_num structure member.  That way we can re-use the existing
1381  * code.
1382  */
1383 static int sctp_getsockopt_connectx3(struct sock* sk, int len,
1384                                      char __user *optval,
1385                                      int __user *optlen)
1386 {
1387         struct sctp_getaddrs_old param;
1388         sctp_assoc_t assoc_id = 0;
1389         int err = 0;
1390 
1391         if (len < sizeof(param))
1392                 return -EINVAL;
1393 
1394         if (copy_from_user(&param, optval, sizeof(param)))
1395                 return -EFAULT;
1396 
1397         err = __sctp_setsockopt_connectx(sk,
1398                         (struct sockaddr __user *)param.addrs,
1399                         param.addr_num, &assoc_id);
1400 
1401         if (err == 0 || err == -EINPROGRESS) {
1402                 if (copy_to_user(optval, &assoc_id, sizeof(assoc_id)))
1403                         return -EFAULT;
1404                 if (put_user(sizeof(assoc_id), optlen))
1405                         return -EFAULT;
1406         }
1407 
1408         return err;
1409 }
1410 
1411 /* API 3.1.4 close() - UDP Style Syntax
1412  * Applications use close() to perform graceful shutdown (as described in
1413  * Section 10.1 of [SCTP]) on ALL the associations currently represented
1414  * by a UDP-style socket.
1415  *
1416  * The syntax is
1417  *
1418  *   ret = close(int sd);
1419  *
1420  *   sd      - the socket descriptor of the associations to be closed.
1421  *
1422  * To gracefully shutdown a specific association represented by the
1423  * UDP-style socket, an application should use the sendmsg() call,
1424  * passing no user data, but including the appropriate flag in the
1425  * ancillary data (see Section xxxx).
1426  *
1427  * If sd in the close() call is a branched-off socket representing only
1428  * one association, the shutdown is performed on that association only.
1429  *
1430  * 4.1.6 close() - TCP Style Syntax
1431  *
1432  * Applications use close() to gracefully close down an association.
1433  *
1434  * The syntax is:
1435  *
1436  *    int close(int sd);
1437  *
1438  *      sd      - the socket descriptor of the association to be closed.
1439  *
1440  * After an application calls close() on a socket descriptor, no further
1441  * socket operations will succeed on that descriptor.
1442  *
1443  * API 7.1.4 SO_LINGER
1444  *
1445  * An application using the TCP-style socket can use this option to
1446  * perform the SCTP ABORT primitive.  The linger option structure is:
1447  *
1448  *  struct  linger {
1449  *     int     l_onoff;                // option on/off
1450  *     int     l_linger;               // linger time
1451  * };
1452  *
1453  * To enable the option, set l_onoff to 1.  If the l_linger value is set
1454  * to 0, calling close() is the same as the ABORT primitive.  If the
1455  * value is set to a negative value, the setsockopt() call will return
1456  * an error.  If the value is set to a positive value linger_time, the
1457  * close() can be blocked for at most linger_time ms.  If the graceful
1458  * shutdown phase does not finish during this period, close() will
1459  * return but the graceful shutdown phase continues in the system.
1460  */
1461 static void sctp_close(struct sock *sk, long timeout)
1462 {
1463         struct net *net = sock_net(sk);
1464         struct sctp_endpoint *ep;
1465         struct sctp_association *asoc;
1466         struct list_head *pos, *temp;
1467         unsigned int data_was_unread;
1468 
1469         pr_debug("%s: sk:%p, timeout:%ld\n", __func__, sk, timeout);
1470 
1471         sctp_lock_sock(sk);
1472         sk->sk_shutdown = SHUTDOWN_MASK;
1473         sk->sk_state = SCTP_SS_CLOSING;
1474 
1475         ep = sctp_sk(sk)->ep;
1476 
1477         /* Clean up any skbs sitting on the receive queue.  */
1478         data_was_unread = sctp_queue_purge_ulpevents(&sk->sk_receive_queue);
1479         data_was_unread += sctp_queue_purge_ulpevents(&sctp_sk(sk)->pd_lobby);
1480 
1481         /* Walk all associations on an endpoint.  */
1482         list_for_each_safe(pos, temp, &ep->asocs) {
1483                 asoc = list_entry(pos, struct sctp_association, asocs);
1484 
1485                 if (sctp_style(sk, TCP)) {
1486                         /* A closed association can still be in the list if
1487                          * it belongs to a TCP-style listening socket that is
1488                          * not yet accepted. If so, free it. If not, send an
1489                          * ABORT or SHUTDOWN based on the linger options.
1490                          */
1491                         if (sctp_state(asoc, CLOSED)) {
1492                                 sctp_unhash_established(asoc);
1493                                 sctp_association_free(asoc);
1494                                 continue;
1495                         }
1496                 }
1497 
1498                 if (data_was_unread || !skb_queue_empty(&asoc->ulpq.lobby) ||
1499                     !skb_queue_empty(&asoc->ulpq.reasm) ||
1500                     (sock_flag(sk, SOCK_LINGER) && !sk->sk_lingertime)) {
1501                         struct sctp_chunk *chunk;
1502 
1503                         chunk = sctp_make_abort_user(asoc, NULL, 0);
1504                         if (chunk)
1505                                 sctp_primitive_ABORT(net, asoc, chunk);
1506                 } else
1507                         sctp_primitive_SHUTDOWN(net, asoc, NULL);
1508         }
1509 
1510         /* On a TCP-style socket, block for at most linger_time if set. */
1511         if (sctp_style(sk, TCP) && timeout)
1512                 sctp_wait_for_close(sk, timeout);
1513 
1514         /* This will run the backlog queue.  */
1515         sctp_release_sock(sk);
1516 
1517         /* Supposedly, no process has access to the socket, but
1518          * the net layers still may.
1519          */
1520         sctp_local_bh_disable();
1521         sctp_bh_lock_sock(sk);
1522 
1523         /* Hold the sock, since sk_common_release() will put sock_put()
1524          * and we have just a little more cleanup.
1525          */
1526         sock_hold(sk);
1527         sk_common_release(sk);
1528 
1529         sctp_bh_unlock_sock(sk);
1530         sctp_local_bh_enable();
1531 
1532         sock_put(sk);
1533 
1534         SCTP_DBG_OBJCNT_DEC(sock);
1535 }
1536 
1537 /* Handle EPIPE error. */
1538 static int sctp_error(struct sock *sk, int flags, int err)
1539 {
1540         if (err == -EPIPE)
1541                 err = sock_error(sk) ? : -EPIPE;
1542         if (err == -EPIPE && !(flags & MSG_NOSIGNAL))
1543                 send_sig(SIGPIPE, current, 0);
1544         return err;
1545 }
1546 
1547 /* API 3.1.3 sendmsg() - UDP Style Syntax
1548  *
1549  * An application uses sendmsg() and recvmsg() calls to transmit data to
1550  * and receive data from its peer.
1551  *
1552  *  ssize_t sendmsg(int socket, const struct msghdr *message,
1553  *                  int flags);
1554  *
1555  *  socket  - the socket descriptor of the endpoint.
1556  *  message - pointer to the msghdr structure which contains a single
1557  *            user message and possibly some ancillary data.
1558  *
1559  *            See Section 5 for complete description of the data
1560  *            structures.
1561  *
1562  *  flags   - flags sent or received with the user message, see Section
1563  *            5 for complete description of the flags.
1564  *
1565  * Note:  This function could use a rewrite especially when explicit
1566  * connect support comes in.
1567  */
1568 /* BUG:  We do not implement the equivalent of sk_stream_wait_memory(). */
1569 
1570 static int sctp_msghdr_parse(const struct msghdr *, sctp_cmsgs_t *);
1571 
1572 static int sctp_sendmsg(struct kiocb *iocb, struct sock *sk,
1573                         struct msghdr *msg, size_t msg_len)
1574 {
1575         struct net *net = sock_net(sk);
1576         struct sctp_sock *sp;
1577         struct sctp_endpoint *ep;
1578         struct sctp_association *new_asoc=NULL, *asoc=NULL;
1579         struct sctp_transport *transport, *chunk_tp;
1580         struct sctp_chunk *chunk;
1581         union sctp_addr to;
1582         struct sockaddr *msg_name = NULL;
1583         struct sctp_sndrcvinfo default_sinfo;
1584         struct sctp_sndrcvinfo *sinfo;
1585         struct sctp_initmsg *sinit;
1586         sctp_assoc_t associd = 0;
1587         sctp_cmsgs_t cmsgs = { NULL };
1588         int err;
1589         sctp_scope_t scope;
1590         long timeo;
1591         __u16 sinfo_flags = 0;
1592         struct sctp_datamsg *datamsg;
1593         int msg_flags = msg->msg_flags;
1594 
1595         err = 0;
1596         sp = sctp_sk(sk);
1597         ep = sp->ep;
1598 
1599         pr_debug("%s: sk:%p, msg:%p, msg_len:%zu ep:%p\n", __func__, sk,
1600                  msg, msg_len, ep);
1601 
1602         /* We cannot send a message over a TCP-style listening socket. */
1603         if (sctp_style(sk, TCP) && sctp_sstate(sk, LISTENING)) {
1604                 err = -EPIPE;
1605                 goto out_nounlock;
1606         }
1607 
1608         /* Parse out the SCTP CMSGs.  */
1609         err = sctp_msghdr_parse(msg, &cmsgs);
1610         if (err) {
1611                 pr_debug("%s: msghdr parse err:%x\n", __func__, err);
1612                 goto out_nounlock;
1613         }
1614 
1615         /* Fetch the destination address for this packet.  This
1616          * address only selects the association--it is not necessarily
1617          * the address we will send to.
1618          * For a peeled-off socket, msg_name is ignored.
1619          */
1620         if (!sctp_style(sk, UDP_HIGH_BANDWIDTH) && msg->msg_name) {
1621                 int msg_namelen = msg->msg_namelen;
1622 
1623                 err = sctp_verify_addr(sk, (union sctp_addr *)msg->msg_name,
1624                                        msg_namelen);
1625                 if (err)
1626                         return err;
1627 
1628                 if (msg_namelen > sizeof(to))
1629                         msg_namelen = sizeof(to);
1630                 memcpy(&to, msg->msg_name, msg_namelen);
1631                 msg_name = msg->msg_name;
1632         }
1633 
1634         sinfo = cmsgs.info;
1635         sinit = cmsgs.init;
1636 
1637         /* Did the user specify SNDRCVINFO?  */
1638         if (sinfo) {
1639                 sinfo_flags = sinfo->sinfo_flags;
1640                 associd = sinfo->sinfo_assoc_id;
1641         }
1642 
1643         pr_debug("%s: msg_len:%zu, sinfo_flags:0x%x\n", __func__,
1644                  msg_len, sinfo_flags);
1645 
1646         /* SCTP_EOF or SCTP_ABORT cannot be set on a TCP-style socket. */
1647         if (sctp_style(sk, TCP) && (sinfo_flags & (SCTP_EOF | SCTP_ABORT))) {
1648                 err = -EINVAL;
1649                 goto out_nounlock;
1650         }
1651 
1652         /* If SCTP_EOF is set, no data can be sent. Disallow sending zero
1653          * length messages when SCTP_EOF|SCTP_ABORT is not set.
1654          * If SCTP_ABORT is set, the message length could be non zero with
1655          * the msg_iov set to the user abort reason.
1656          */
1657         if (((sinfo_flags & SCTP_EOF) && (msg_len > 0)) ||
1658             (!(sinfo_flags & (SCTP_EOF|SCTP_ABORT)) && (msg_len == 0))) {
1659                 err = -EINVAL;
1660                 goto out_nounlock;
1661         }
1662 
1663         /* If SCTP_ADDR_OVER is set, there must be an address
1664          * specified in msg_name.
1665          */
1666         if ((sinfo_flags & SCTP_ADDR_OVER) && (!msg->msg_name)) {
1667                 err = -EINVAL;
1668                 goto out_nounlock;
1669         }
1670 
1671         transport = NULL;
1672 
1673         pr_debug("%s: about to look up association\n", __func__);
1674 
1675         sctp_lock_sock(sk);
1676 
1677         /* If a msg_name has been specified, assume this is to be used.  */
1678         if (msg_name) {
1679                 /* Look for a matching association on the endpoint. */
1680                 asoc = sctp_endpoint_lookup_assoc(ep, &to, &transport);
1681                 if (!asoc) {
1682                         /* If we could not find a matching association on the
1683                          * endpoint, make sure that it is not a TCP-style
1684                          * socket that already has an association or there is
1685                          * no peeled-off association on another socket.
1686                          */
1687                         if ((sctp_style(sk, TCP) &&
1688                              sctp_sstate(sk, ESTABLISHED)) ||
1689                             sctp_endpoint_is_peeled_off(ep, &to)) {
1690                                 err = -EADDRNOTAVAIL;
1691                                 goto out_unlock;
1692                         }
1693                 }
1694         } else {
1695                 asoc = sctp_id2assoc(sk, associd);
1696                 if (!asoc) {
1697                         err = -EPIPE;
1698                         goto out_unlock;
1699                 }
1700         }
1701 
1702         if (asoc) {
1703                 pr_debug("%s: just looked up association:%p\n", __func__, asoc);
1704 
1705                 /* We cannot send a message on a TCP-style SCTP_SS_ESTABLISHED
1706                  * socket that has an association in CLOSED state. This can
1707                  * happen when an accepted socket has an association that is
1708                  * already CLOSED.
1709                  */
1710                 if (sctp_state(asoc, CLOSED) && sctp_style(sk, TCP)) {
1711                         err = -EPIPE;
1712                         goto out_unlock;
1713                 }
1714 
1715                 if (sinfo_flags & SCTP_EOF) {
1716                         pr_debug("%s: shutting down association:%p\n",
1717                                  __func__, asoc);
1718 
1719                         sctp_primitive_SHUTDOWN(net, asoc, NULL);
1720                         err = 0;
1721                         goto out_unlock;
1722                 }
1723                 if (sinfo_flags & SCTP_ABORT) {
1724 
1725                         chunk = sctp_make_abort_user(asoc, msg, msg_len);
1726                         if (!chunk) {
1727                                 err = -ENOMEM;
1728                                 goto out_unlock;
1729                         }
1730 
1731                         pr_debug("%s: aborting association:%p\n",
1732                                  __func__, asoc);
1733 
1734                         sctp_primitive_ABORT(net, asoc, chunk);
1735                         err = 0;
1736                         goto out_unlock;
1737                 }
1738         }
1739 
1740         /* Do we need to create the association?  */
1741         if (!asoc) {
1742                 pr_debug("%s: there is no association yet\n", __func__);
1743 
1744                 if (sinfo_flags & (SCTP_EOF | SCTP_ABORT)) {
1745                         err = -EINVAL;
1746                         goto out_unlock;
1747                 }
1748 
1749                 /* Check for invalid stream against the stream counts,
1750                  * either the default or the user specified stream counts.
1751                  */
1752                 if (sinfo) {
1753                         if (!sinit || (sinit && !sinit->sinit_num_ostreams)) {
1754                                 /* Check against the defaults. */
1755                                 if (sinfo->sinfo_stream >=
1756                                     sp->initmsg.sinit_num_ostreams) {
1757                                         err = -EINVAL;
1758                                         goto out_unlock;
1759                                 }
1760                         } else {
1761                                 /* Check against the requested.  */
1762                                 if (sinfo->sinfo_stream >=
1763                                     sinit->sinit_num_ostreams) {
1764                                         err = -EINVAL;
1765                                         goto out_unlock;
1766                                 }
1767                         }
1768                 }
1769 
1770                 /*
1771                  * API 3.1.2 bind() - UDP Style Syntax
1772                  * If a bind() or sctp_bindx() is not called prior to a
1773                  * sendmsg() call that initiates a new association, the
1774                  * system picks an ephemeral port and will choose an address
1775                  * set equivalent to binding with a wildcard address.
1776                  */
1777                 if (!ep->base.bind_addr.port) {
1778                         if (sctp_autobind(sk)) {
1779                                 err = -EAGAIN;
1780                                 goto out_unlock;
1781                         }
1782                 } else {
1783                         /*
1784                          * If an unprivileged user inherits a one-to-many
1785                          * style socket with open associations on a privileged
1786                          * port, it MAY be permitted to accept new associations,
1787                          * but it SHOULD NOT be permitted to open new
1788                          * associations.
1789                          */
1790                         if (ep->base.bind_addr.port < PROT_SOCK &&
1791                             !ns_capable(net->user_ns, CAP_NET_BIND_SERVICE)) {
1792                                 err = -EACCES;
1793                                 goto out_unlock;
1794                         }
1795                 }
1796 
1797                 scope = sctp_scope(&to);
1798                 new_asoc = sctp_association_new(ep, sk, scope, GFP_KERNEL);
1799                 if (!new_asoc) {
1800                         err = -ENOMEM;
1801                         goto out_unlock;
1802                 }
1803                 asoc = new_asoc;
1804                 err = sctp_assoc_set_bind_addr_from_ep(asoc, scope, GFP_KERNEL);
1805                 if (err < 0) {
1806                         err = -ENOMEM;
1807                         goto out_free;
1808                 }
1809 
1810                 /* If the SCTP_INIT ancillary data is specified, set all
1811                  * the association init values accordingly.
1812                  */
1813                 if (sinit) {
1814                         if (sinit->sinit_num_ostreams) {
1815                                 asoc->c.sinit_num_ostreams =
1816                                         sinit->sinit_num_ostreams;
1817                         }
1818                         if (sinit->sinit_max_instreams) {
1819                                 asoc->c.sinit_max_instreams =
1820                                         sinit->sinit_max_instreams;
1821                         }
1822                         if (sinit->sinit_max_attempts) {
1823                                 asoc->max_init_attempts
1824                                         = sinit->sinit_max_attempts;
1825                         }
1826                         if (sinit->sinit_max_init_timeo) {
1827                                 asoc->max_init_timeo =
1828                                  msecs_to_jiffies(sinit->sinit_max_init_timeo);
1829                         }
1830                 }
1831 
1832                 /* Prime the peer's transport structures.  */
1833                 transport = sctp_assoc_add_peer(asoc, &to, GFP_KERNEL, SCTP_UNKNOWN);
1834                 if (!transport) {
1835                         err = -ENOMEM;
1836                         goto out_free;
1837                 }
1838         }
1839 
1840         /* ASSERT: we have a valid association at this point.  */
1841         pr_debug("%s: we have a valid association\n", __func__);
1842 
1843         if (!sinfo) {
1844                 /* If the user didn't specify SNDRCVINFO, make up one with
1845                  * some defaults.
1846                  */
1847                 memset(&default_sinfo, 0, sizeof(default_sinfo));
1848                 default_sinfo.sinfo_stream = asoc->default_stream;
1849                 default_sinfo.sinfo_flags = asoc->default_flags;
1850                 default_sinfo.sinfo_ppid = asoc->default_ppid;
1851                 default_sinfo.sinfo_context = asoc->default_context;
1852                 default_sinfo.sinfo_timetolive = asoc->default_timetolive;
1853                 default_sinfo.sinfo_assoc_id = sctp_assoc2id(asoc);
1854                 sinfo = &default_sinfo;
1855         }
1856 
1857         /* API 7.1.7, the sndbuf size per association bounds the
1858          * maximum size of data that can be sent in a single send call.
1859          */
1860         if (msg_len > sk->sk_sndbuf) {
1861                 err = -EMSGSIZE;
1862                 goto out_free;
1863         }
1864 
1865         if (asoc->pmtu_pending)
1866                 sctp_assoc_pending_pmtu(sk, asoc);
1867 
1868         /* If fragmentation is disabled and the message length exceeds the
1869          * association fragmentation point, return EMSGSIZE.  The I-D
1870          * does not specify what this error is, but this looks like
1871          * a great fit.
1872          */
1873         if (sctp_sk(sk)->disable_fragments && (msg_len > asoc->frag_point)) {
1874                 err = -EMSGSIZE;
1875                 goto out_free;
1876         }
1877 
1878         /* Check for invalid stream. */
1879         if (sinfo->sinfo_stream >= asoc->c.sinit_num_ostreams) {
1880                 err = -EINVAL;
1881                 goto out_free;
1882         }
1883 
1884         timeo = sock_sndtimeo(sk, msg->msg_flags & MSG_DONTWAIT);
1885         if (!sctp_wspace(asoc)) {
1886                 err = sctp_wait_for_sndbuf(asoc, &timeo, msg_len);
1887                 if (err)
1888                         goto out_free;
1889         }
1890 
1891         /* If an address is passed with the sendto/sendmsg call, it is used
1892          * to override the primary destination address in the TCP model, or
1893          * when SCTP_ADDR_OVER flag is set in the UDP model.
1894          */
1895         if ((sctp_style(sk, TCP) && msg_name) ||
1896             (sinfo_flags & SCTP_ADDR_OVER)) {
1897                 chunk_tp = sctp_assoc_lookup_paddr(asoc, &to);
1898                 if (!chunk_tp) {
1899                         err = -EINVAL;
1900                         goto out_free;
1901                 }
1902         } else
1903                 chunk_tp = NULL;
1904 
1905         /* Auto-connect, if we aren't connected already. */
1906         if (sctp_state(asoc, CLOSED)) {
1907                 err = sctp_primitive_ASSOCIATE(net, asoc, NULL);
1908                 if (err < 0)
1909                         goto out_free;
1910 
1911                 pr_debug("%s: we associated primitively\n", __func__);
1912         }
1913 
1914         /* Break the message into multiple chunks of maximum size. */
1915         datamsg = sctp_datamsg_from_user(asoc, sinfo, msg, msg_len);
1916         if (IS_ERR(datamsg)) {
1917                 err = PTR_ERR(datamsg);
1918                 goto out_free;
1919         }
1920 
1921         /* Now send the (possibly) fragmented message. */
1922         list_for_each_entry(chunk, &datamsg->chunks, frag_list) {
1923                 sctp_chunk_hold(chunk);
1924 
1925                 /* Do accounting for the write space.  */
1926                 sctp_set_owner_w(chunk);
1927 
1928                 chunk->transport = chunk_tp;
1929         }
1930 
1931         /* Send it to the lower layers.  Note:  all chunks
1932          * must either fail or succeed.   The lower layer
1933          * works that way today.  Keep it that way or this
1934          * breaks.
1935          */
1936         err = sctp_primitive_SEND(net, asoc, datamsg);
1937         /* Did the lower layer accept the chunk? */
1938         if (err) {
1939                 sctp_datamsg_free(datamsg);
1940                 goto out_free;
1941         }
1942 
1943         pr_debug("%s: we sent primitively\n", __func__);
1944 
1945         sctp_datamsg_put(datamsg);
1946         err = msg_len;
1947 
1948         /* If we are already past ASSOCIATE, the lower
1949          * layers are responsible for association cleanup.
1950          */
1951         goto out_unlock;
1952 
1953 out_free:
1954         if (new_asoc) {
1955                 sctp_unhash_established(asoc);
1956                 sctp_association_free(asoc);
1957         }
1958 out_unlock:
1959         sctp_release_sock(sk);
1960 
1961 out_nounlock:
1962         return sctp_error(sk, msg_flags, err);
1963 
1964 #if 0
1965 do_sock_err:
1966         if (msg_len)
1967                 err = msg_len;
1968         else
1969                 err = sock_error(sk);
1970         goto out;
1971 
1972 do_interrupted:
1973         if (msg_len)
1974                 err = msg_len;
1975         goto out;
1976 #endif /* 0 */
1977 }
1978 
1979 /* This is an extended version of skb_pull() that removes the data from the
1980  * start of a skb even when data is spread across the list of skb's in the
1981  * frag_list. len specifies the total amount of data that needs to be removed.
1982  * when 'len' bytes could be removed from the skb, it returns 0.
1983  * If 'len' exceeds the total skb length,  it returns the no. of bytes that
1984  * could not be removed.
1985  */
1986 static int sctp_skb_pull(struct sk_buff *skb, int len)
1987 {
1988         struct sk_buff *list;
1989         int skb_len = skb_headlen(skb);
1990         int rlen;
1991 
1992         if (len <= skb_len) {
1993                 __skb_pull(skb, len);
1994                 return 0;
1995         }
1996         len -= skb_len;
1997         __skb_pull(skb, skb_len);
1998 
1999         skb_walk_frags(skb, list) {
2000                 rlen = sctp_skb_pull(list, len);
2001                 skb->len -= (len-rlen);
2002                 skb->data_len -= (len-rlen);
2003 
2004                 if (!rlen)
2005                         return 0;
2006 
2007                 len = rlen;
2008         }
2009 
2010         return len;
2011 }
2012 
2013 /* API 3.1.3  recvmsg() - UDP Style Syntax
2014  *
2015  *  ssize_t recvmsg(int socket, struct msghdr *message,
2016  *                    int flags);
2017  *
2018  *  socket  - the socket descriptor of the endpoint.
2019  *  message - pointer to the msghdr structure which contains a single
2020  *            user message and possibly some ancillary data.
2021  *
2022  *            See Section 5 for complete description of the data
2023  *            structures.
2024  *
2025  *  flags   - flags sent or received with the user message, see Section
2026  *            5 for complete description of the flags.
2027  */
2028 static struct sk_buff *sctp_skb_recv_datagram(struct sock *, int, int, int *);
2029 
2030 static int sctp_recvmsg(struct kiocb *iocb, struct sock *sk,
2031                         struct msghdr *msg, size_t len, int noblock,
2032                         int flags, int *addr_len)
2033 {
2034         struct sctp_ulpevent *event = NULL;
2035         struct sctp_sock *sp = sctp_sk(sk);
2036         struct sk_buff *skb;
2037         int copied;
2038         int err = 0;
2039         int skb_len;
2040 
2041         pr_debug("%s: sk:%p, msghdr:%p, len:%zd, noblock:%d, flags:0x%x, "
2042                  "addr_len:%p)\n", __func__, sk, msg, len, noblock, flags,
2043                  addr_len);
2044 
2045         sctp_lock_sock(sk);
2046 
2047         if (sctp_style(sk, TCP) && !sctp_sstate(sk, ESTABLISHED)) {
2048                 err = -ENOTCONN;
2049                 goto out;
2050         }
2051 
2052         skb = sctp_skb_recv_datagram(sk, flags, noblock, &err);
2053         if (!skb)
2054                 goto out;
2055 
2056         /* Get the total length of the skb including any skb's in the
2057          * frag_list.
2058          */
2059         skb_len = skb->len;
2060 
2061         copied = skb_len;
2062         if (copied > len)
2063                 copied = len;
2064 
2065         err = skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied);
2066 
2067         event = sctp_skb2event(skb);
2068 
2069         if (err)
2070                 goto out_free;
2071 
2072         sock_recv_ts_and_drops(msg, sk, skb);
2073         if (sctp_ulpevent_is_notification(event)) {
2074                 msg->msg_flags |= MSG_NOTIFICATION;
2075                 sp->pf->event_msgname(event, msg->msg_name, addr_len);
2076         } else {
2077                 sp->pf->skb_msgname(skb, msg->msg_name, addr_len);
2078         }
2079 
2080         /* Check if we allow SCTP_SNDRCVINFO. */
2081         if (sp->subscribe.sctp_data_io_event)
2082                 sctp_ulpevent_read_sndrcvinfo(event, msg);
2083 #if 0
2084         /* FIXME: we should be calling IP/IPv6 layers.  */
2085         if (sk->sk_protinfo.af_inet.cmsg_flags)
2086                 ip_cmsg_recv(msg, skb);
2087 #endif
2088 
2089         err = copied;
2090 
2091         /* If skb's length exceeds the user's buffer, update the skb and
2092          * push it back to the receive_queue so that the next call to
2093          * recvmsg() will return the remaining data. Don't set MSG_EOR.
2094          */
2095         if (skb_len > copied) {
2096                 msg->msg_flags &= ~MSG_EOR;
2097                 if (flags & MSG_PEEK)
2098                         goto out_free;
2099                 sctp_skb_pull(skb, copied);
2100                 skb_queue_head(&sk->sk_receive_queue, skb);
2101 
2102                 /* When only partial message is copied to the user, increase
2103                  * rwnd by that amount. If all the data in the skb is read,
2104                  * rwnd is updated when the event is freed.
2105                  */
2106                 if (!sctp_ulpevent_is_notification(event))
2107                         sctp_assoc_rwnd_increase(event->asoc, copied);
2108                 goto out;
2109         } else if ((event->msg_flags & MSG_NOTIFICATION) ||
2110                    (event->msg_flags & MSG_EOR))
2111                 msg->msg_flags |= MSG_EOR;
2112         else
2113                 msg->msg_flags &= ~MSG_EOR;
2114 
2115 out_free:
2116         if (flags & MSG_PEEK) {
2117                 /* Release the skb reference acquired after peeking the skb in
2118                  * sctp_skb_recv_datagram().
2119                  */
2120                 kfree_skb(skb);
2121         } else {
2122                 /* Free the event which includes releasing the reference to
2123                  * the owner of the skb, freeing the skb and updating the
2124                  * rwnd.
2125                  */
2126                 sctp_ulpevent_free(event);
2127         }
2128 out:
2129         sctp_release_sock(sk);
2130         return err;
2131 }
2132 
2133 /* 7.1.12 Enable/Disable message fragmentation (SCTP_DISABLE_FRAGMENTS)
2134  *
2135  * This option is a on/off flag.  If enabled no SCTP message
2136  * fragmentation will be performed.  Instead if a message being sent
2137  * exceeds the current PMTU size, the message will NOT be sent and
2138  * instead a error will be indicated to the user.
2139  */
2140 static int sctp_setsockopt_disable_fragments(struct sock *sk,
2141                                              char __user *optval,
2142                                              unsigned int optlen)
2143 {
2144         int val;
2145 
2146         if (optlen < sizeof(int))
2147                 return -EINVAL;
2148 
2149         if (get_user(val, (int __user *)optval))
2150                 return -EFAULT;
2151 
2152         sctp_sk(sk)->disable_fragments = (val == 0) ? 0 : 1;
2153 
2154         return 0;
2155 }
2156 
2157 static int sctp_setsockopt_events(struct sock *sk, char __user *optval,
2158                                   unsigned int optlen)
2159 {
2160         struct sctp_association *asoc;
2161         struct sctp_ulpevent *event;
2162 
2163         if (optlen > sizeof(struct sctp_event_subscribe))
2164                 return -EINVAL;
2165         if (copy_from_user(&sctp_sk(sk)->subscribe, optval, optlen))
2166                 return -EFAULT;
2167 
2168         /*
2169          * At the time when a user app subscribes to SCTP_SENDER_DRY_EVENT,
2170          * if there is no data to be sent or retransmit, the stack will
2171          * immediately send up this notification.
2172          */
2173         if (sctp_ulpevent_type_enabled(SCTP_SENDER_DRY_EVENT,
2174                                        &sctp_sk(sk)->subscribe)) {
2175                 asoc = sctp_id2assoc(sk, 0);
2176 
2177                 if (asoc && sctp_outq_is_empty(&asoc->outqueue)) {
2178                         event = sctp_ulpevent_make_sender_dry_event(asoc,
2179                                         GFP_ATOMIC);
2180                         if (!event)
2181                                 return -ENOMEM;
2182 
2183                         sctp_ulpq_tail_event(&asoc->ulpq, event);
2184                 }
2185         }
2186 
2187         return 0;
2188 }
2189 
2190 /* 7.1.8 Automatic Close of associations (SCTP_AUTOCLOSE)
2191  *
2192  * This socket option is applicable to the UDP-style socket only.  When
2193  * set it will cause associations that are idle for more than the
2194  * specified number of seconds to automatically close.  An association
2195  * being idle is defined an association that has NOT sent or received
2196  * user data.  The special value of '' indicates that no automatic
2197  * close of any associations should be performed.  The option expects an
2198  * integer defining the number of seconds of idle time before an
2199  * association is closed.
2200  */
2201 static int sctp_setsockopt_autoclose(struct sock *sk, char __user *optval,
2202                                      unsigned int optlen)
2203 {
2204         struct sctp_sock *sp = sctp_sk(sk);
2205 
2206         /* Applicable to UDP-style socket only */
2207         if (sctp_style(sk, TCP))
2208                 return -EOPNOTSUPP;
2209         if (optlen != sizeof(int))
2210                 return -EINVAL;
2211         if (copy_from_user(&sp->autoclose, optval, optlen))
2212                 return -EFAULT;
2213 
2214         return 0;
2215 }
2216 
2217 /* 7.1.13 Peer Address Parameters (SCTP_PEER_ADDR_PARAMS)
2218  *
2219  * Applications can enable or disable heartbeats for any peer address of
2220  * an association, modify an address's heartbeat interval, force a
2221  * heartbeat to be sent immediately, and adjust the address's maximum
2222  * number of retransmissions sent before an address is considered
2223  * unreachable.  The following structure is used to access and modify an
2224  * address's parameters:
2225  *
2226  *  struct sctp_paddrparams {
2227  *     sctp_assoc_t            spp_assoc_id;
2228  *     struct sockaddr_storage spp_address;
2229  *     uint32_t                spp_hbinterval;
2230  *     uint16_t                spp_pathmaxrxt;
2231  *     uint32_t                spp_pathmtu;
2232  *     uint32_t                spp_sackdelay;
2233  *     uint32_t                spp_flags;
2234  * };
2235  *
2236  *   spp_assoc_id    - (one-to-many style socket) This is filled in the
2237  *                     application, and identifies the association for
2238  *                     this query.
2239  *   spp_address     - This specifies which address is of interest.
2240  *   spp_hbinterval  - This contains the value of the heartbeat interval,
2241  *                     in milliseconds.  If a  value of zero
2242  *                     is present in this field then no changes are to
2243  *                     be made to this parameter.
2244  *   spp_pathmaxrxt  - This contains the maximum number of
2245  *                     retransmissions before this address shall be
2246  *                     considered unreachable. If a  value of zero
2247  *                     is present in this field then no changes are to
2248  *                     be made to this parameter.
2249  *   spp_pathmtu     - When Path MTU discovery is disabled the value
2250  *                     specified here will be the "fixed" path mtu.
2251  *                     Note that if the spp_address field is empty
2252  *                     then all associations on this address will
2253  *                     have this fixed path mtu set upon them.
2254  *
2255  *   spp_sackdelay   - When delayed sack is enabled, this value specifies
2256  *                     the number of milliseconds that sacks will be delayed
2257  *                     for. This value will apply to all addresses of an
2258  *                     association if the spp_address field is empty. Note
2259  *                     also, that if delayed sack is enabled and this
2260  *                     value is set to 0, no change is made to the last
2261  *                     recorded delayed sack timer value.
2262  *
2263  *   spp_flags       - These flags are used to control various features
2264  *                     on an association. The flag field may contain
2265  *                     zero or more of the following options.
2266  *
2267  *                     SPP_HB_ENABLE  - Enable heartbeats on the
2268  *                     specified address. Note that if the address
2269  *                     field is empty all addresses for the association
2270  *                     have heartbeats enabled upon them.
2271  *
2272  *                     SPP_HB_DISABLE - Disable heartbeats on the
2273  *                     speicifed address. Note that if the address
2274  *                     field is empty all addresses for the association
2275  *                     will have their heartbeats disabled. Note also
2276  *                     that SPP_HB_ENABLE and SPP_HB_DISABLE are
2277  *                     mutually exclusive, only one of these two should
2278  *                     be specified. Enabling both fields will have
2279  *                     undetermined results.
2280  *
2281  *                     SPP_HB_DEMAND - Request a user initiated heartbeat
2282  *                     to be made immediately.
2283  *
2284  *                     SPP_HB_TIME_IS_ZERO - Specify's that the time for
2285  *                     heartbeat delayis to be set to the value of 0
2286  *                     milliseconds.
2287  *
2288  *                     SPP_PMTUD_ENABLE - This field will enable PMTU
2289  *                     discovery upon the specified address. Note that
2290  *                     if the address feild is empty then all addresses
2291  *                     on the association are effected.
2292  *
2293  *                     SPP_PMTUD_DISABLE - This field will disable PMTU
2294  *                     discovery upon the specified address. Note that
2295  *                     if the address feild is empty then all addresses
2296  *                     on the association are effected. Not also that
2297  *                     SPP_PMTUD_ENABLE and SPP_PMTUD_DISABLE are mutually
2298  *                     exclusive. Enabling both will have undetermined
2299  *                     results.
2300  *
2301  *                     SPP_SACKDELAY_ENABLE - Setting this flag turns
2302  *                     on delayed sack. The time specified in spp_sackdelay
2303  *                     is used to specify the sack delay for this address. Note
2304  *                     that if spp_address is empty then all addresses will
2305  *                     enable delayed sack and take on the sack delay
2306  *                     value specified in spp_sackdelay.
2307  *                     SPP_SACKDELAY_DISABLE - Setting this flag turns
2308  *                     off delayed sack. If the spp_address field is blank then
2309  *                     delayed sack is disabled for the entire association. Note
2310  *                     also that this field is mutually exclusive to
2311  *                     SPP_SACKDELAY_ENABLE, setting both will have undefined
2312  *                     results.
2313  */
2314 static int sctp_apply_peer_addr_params(struct sctp_paddrparams *params,
2315                                        struct sctp_transport   *trans,
2316                                        struct sctp_association *asoc,
2317                                        struct sctp_sock        *sp,
2318                                        int                      hb_change,
2319                                        int                      pmtud_change,
2320                                        int                      sackdelay_change)
2321 {
2322         int error;
2323 
2324         if (params->spp_flags & SPP_HB_DEMAND && trans) {
2325                 struct net *net = sock_net(trans->asoc->base.sk);
2326 
2327                 error = sctp_primitive_REQUESTHEARTBEAT(net, trans->asoc, trans);
2328                 if (error)
2329                         return error;
2330         }
2331 
2332         /* Note that unless the spp_flag is set to SPP_HB_ENABLE the value of
2333          * this field is ignored.  Note also that a value of zero indicates
2334          * the current setting should be left unchanged.
2335          */
2336         if (params->spp_flags & SPP_HB_ENABLE) {
2337 
2338                 /* Re-zero the interval if the SPP_HB_TIME_IS_ZERO is
2339                  * set.  This lets us use 0 value when this flag
2340                  * is set.
2341                  */
2342                 if (params->spp_flags & SPP_HB_TIME_IS_ZERO)
2343                         params->spp_hbinterval = 0;
2344 
2345                 if (params->spp_hbinterval ||
2346                     (params->spp_flags & SPP_HB_TIME_IS_ZERO)) {
2347                         if (trans) {
2348                                 trans->hbinterval =
2349                                     msecs_to_jiffies(params->spp_hbinterval);
2350                         } else if (asoc) {
2351                                 asoc->hbinterval =
2352                                     msecs_to_jiffies(params->spp_hbinterval);
2353                         } else {
2354                                 sp->hbinterval = params->spp_hbinterval;
2355                         }
2356                 }
2357         }
2358 
2359         if (hb_change) {
2360                 if (trans) {
2361                         trans->param_flags =
2362                                 (trans->param_flags & ~SPP_HB) | hb_change;
2363                 } else if (asoc) {
2364                         asoc->param_flags =
2365                                 (asoc->param_flags & ~SPP_HB) | hb_change;
2366                 } else {
2367                         sp->param_flags =
2368                                 (sp->param_flags & ~SPP_HB) | hb_change;
2369                 }
2370         }
2371 
2372         /* When Path MTU discovery is disabled the value specified here will
2373          * be the "fixed" path mtu (i.e. the value of the spp_flags field must
2374          * include the flag SPP_PMTUD_DISABLE for this field to have any
2375          * effect).
2376          */
2377         if ((params->spp_flags & SPP_PMTUD_DISABLE) && params->spp_pathmtu) {
2378                 if (trans) {
2379                         trans->pathmtu = params->spp_pathmtu;
2380                         sctp_assoc_sync_pmtu(sctp_opt2sk(sp), asoc);
2381                 } else if (asoc) {
2382                         asoc->pathmtu = params->spp_pathmtu;
2383                         sctp_frag_point(asoc, params->spp_pathmtu);
2384                 } else {
2385                         sp->pathmtu = params->spp_pathmtu;
2386                 }
2387         }
2388 
2389         if (pmtud_change) {
2390                 if (trans) {
2391                         int update = (trans->param_flags & SPP_PMTUD_DISABLE) &&
2392                                 (params->spp_flags & SPP_PMTUD_ENABLE);
2393                         trans->param_flags =
2394                                 (trans->param_flags & ~SPP_PMTUD) | pmtud_change;
2395                         if (update) {
2396                                 sctp_transport_pmtu(trans, sctp_opt2sk(sp));
2397                                 sctp_assoc_sync_pmtu(sctp_opt2sk(sp), asoc);
2398                         }
2399                 } else if (asoc) {
2400                         asoc->param_flags =
2401                                 (asoc->param_flags & ~SPP_PMTUD) | pmtud_change;
2402                 } else {
2403                         sp->param_flags =
2404                                 (sp->param_flags & ~SPP_PMTUD) | pmtud_change;
2405                 }
2406         }
2407 
2408         /* Note that unless the spp_flag is set to SPP_SACKDELAY_ENABLE the
2409          * value of this field is ignored.  Note also that a value of zero
2410          * indicates the current setting should be left unchanged.
2411          */
2412         if ((params->spp_flags & SPP_SACKDELAY_ENABLE) && params->spp_sackdelay) {
2413                 if (trans) {
2414                         trans->sackdelay =
2415                                 msecs_to_jiffies(params->spp_sackdelay);
2416                 } else if (asoc) {
2417                         asoc->sackdelay =
2418                                 msecs_to_jiffies(params->spp_sackdelay);
2419                 } else {
2420                         sp->sackdelay = params->spp_sackdelay;
2421                 }
2422         }
2423 
2424         if (sackdelay_change) {
2425                 if (trans) {
2426                         trans->param_flags =
2427                                 (trans->param_flags & ~SPP_SACKDELAY) |
2428                                 sackdelay_change;
2429                 } else if (asoc) {
2430                         asoc->param_flags =
2431                                 (asoc->param_flags & ~SPP_SACKDELAY) |
2432                                 sackdelay_change;
2433                 } else {
2434                         sp->param_flags =
2435                                 (sp->param_flags & ~SPP_SACKDELAY) |
2436                                 sackdelay_change;
2437                 }
2438         }
2439 
2440         /* Note that a value of zero indicates the current setting should be
2441            left unchanged.
2442          */
2443         if (params->spp_pathmaxrxt) {
2444                 if (trans) {
2445                         trans->pathmaxrxt = params->spp_pathmaxrxt;
2446                 } else if (asoc) {
2447                         asoc->pathmaxrxt = params->spp_pathmaxrxt;
2448                 } else {
2449                         sp->pathmaxrxt = params->spp_pathmaxrxt;
2450                 }
2451         }
2452 
2453         return 0;
2454 }
2455 
2456 static int sctp_setsockopt_peer_addr_params(struct sock *sk,
2457                                             char __user *optval,
2458                                             unsigned int optlen)
2459 {
2460         struct sctp_paddrparams  params;
2461         struct sctp_transport   *trans = NULL;
2462         struct sctp_association *asoc = NULL;
2463         struct sctp_sock        *sp = sctp_sk(sk);
2464         int error;
2465         int hb_change, pmtud_change, sackdelay_change;
2466 
2467         if (optlen != sizeof(struct sctp_paddrparams))
2468                 return - EINVAL;
2469 
2470         if (copy_from_user(&params, optval, optlen))
2471                 return -EFAULT;
2472 
2473         /* Validate flags and value parameters. */
2474         hb_change        = params.spp_flags & SPP_HB;
2475         pmtud_change     = params.spp_flags & SPP_PMTUD;
2476         sackdelay_change = params.spp_flags & SPP_SACKDELAY;
2477 
2478         if (hb_change        == SPP_HB ||
2479             pmtud_change     == SPP_PMTUD ||
2480             sackdelay_change == SPP_SACKDELAY ||
2481             params.spp_sackdelay > 500 ||
2482             (params.spp_pathmtu &&
2483              params.spp_pathmtu < SCTP_DEFAULT_MINSEGMENT))
2484                 return -EINVAL;
2485 
2486         /* If an address other than INADDR_ANY is specified, and
2487          * no transport is found, then the request is invalid.
2488          */
2489         if (!sctp_is_any(sk, ( union sctp_addr *)&params.spp_address)) {
2490                 trans = sctp_addr_id2transport(sk, &params.spp_address,
2491                                                params.spp_assoc_id);
2492                 if (!trans)
2493                         return -EINVAL;
2494         }
2495 
2496         /* Get association, if assoc_id != 0 and the socket is a one
2497          * to many style socket, and an association was not found, then
2498          * the id was invalid.
2499          */
2500         asoc = sctp_id2assoc(sk, params.spp_assoc_id);
2501         if (!asoc && params.spp_assoc_id && sctp_style(sk, UDP))
2502                 return -EINVAL;
2503 
2504         /* Heartbeat demand can only be sent on a transport or
2505          * association, but not a socket.
2506          */
2507         if (params.spp_flags & SPP_HB_DEMAND && !trans && !asoc)
2508                 return -EINVAL;
2509 
2510         /* Process parameters. */
2511         error = sctp_apply_peer_addr_params(&params, trans, asoc, sp,
2512                                             hb_change, pmtud_change,
2513                                             sackdelay_change);
2514 
2515         if (error)
2516                 return error;
2517 
2518         /* If changes are for association, also apply parameters to each
2519          * transport.
2520          */
2521         if (!trans && asoc) {
2522                 list_for_each_entry(trans, &asoc->peer.transport_addr_list,
2523                                 transports) {
2524                         sctp_apply_peer_addr_params(&params, trans, asoc, sp,
2525                                                     hb_change, pmtud_change,
2526                                                     sackdelay_change);
2527                 }
2528         }
2529 
2530         return 0;
2531 }
2532 
2533 /*
2534  * 7.1.23.  Get or set delayed ack timer (SCTP_DELAYED_SACK)
2535  *
2536  * This option will effect the way delayed acks are performed.  This
2537  * option allows you to get or set the delayed ack time, in
2538  * milliseconds.  It also allows changing the delayed ack frequency.
2539  * Changing the frequency to 1 disables the delayed sack algorithm.  If
2540  * the assoc_id is 0, then this sets or gets the endpoints default
2541  * values.  If the assoc_id field is non-zero, then the set or get
2542  * effects the specified association for the one to many model (the
2543  * assoc_id field is ignored by the one to one model).  Note that if
2544  * sack_delay or sack_freq are 0 when setting this option, then the
2545  * current values will remain unchanged.
2546  *
2547  * struct sctp_sack_info {
2548  *     sctp_assoc_t            sack_assoc_id;
2549  *     uint32_t                sack_delay;
2550  *     uint32_t                sack_freq;
2551  * };
2552  *
2553  * sack_assoc_id -  This parameter, indicates which association the user
2554  *    is performing an action upon.  Note that if this field's value is
2555  *    zero then the endpoints default value is changed (effecting future
2556  *    associations only).
2557  *
2558  * sack_delay -  This parameter contains the number of milliseconds that
2559  *    the user is requesting the delayed ACK timer be set to.  Note that
2560  *    this value is defined in the standard to be between 200 and 500
2561  *    milliseconds.
2562  *
2563  * sack_freq -  This parameter contains the number of packets that must
2564  *    be received before a sack is sent without waiting for the delay
2565  *    timer to expire.  The default value for this is 2, setting this
2566  *    value to 1 will disable the delayed sack algorithm.
2567  */
2568 
2569 static int sctp_setsockopt_delayed_ack(struct sock *sk,
2570                                        char __user *optval, unsigned int optlen)
2571 {
2572         struct sctp_sack_info    params;
2573         struct sctp_transport   *trans = NULL;
2574         struct sctp_association *asoc = NULL;
2575         struct sctp_sock        *sp = sctp_sk(sk);
2576 
2577         if (optlen == sizeof(struct sctp_sack_info)) {
2578                 if (copy_from_user(&params, optval, optlen))
2579                         return -EFAULT;
2580 
2581                 if (params.sack_delay == 0 && params.sack_freq == 0)
2582                         return 0;
2583         } else if (optlen == sizeof(struct sctp_assoc_value)) {
2584                 pr_warn("Use of struct sctp_assoc_value in delayed_ack socket option deprecated\n");
2585                 pr_warn("Use struct sctp_sack_info instead\n");
2586                 if (copy_from_user(&params, optval, optlen))
2587                         return -EFAULT;
2588 
2589                 if (params.sack_delay == 0)
2590                         params.sack_freq = 1;
2591                 else
2592                         params.sack_freq = 0;
2593         } else
2594                 return - EINVAL;
2595 
2596         /* Validate value parameter. */
2597         if (params.sack_delay > 500)
2598                 return -EINVAL;
2599 
2600         /* Get association, if sack_assoc_id != 0 and the socket is a one
2601          * to many style socket, and an association was not found, then
2602          * the id was invalid.
2603          */
2604         asoc = sctp_id2assoc(sk, params.sack_assoc_id);
2605         if (!asoc && params.sack_assoc_id && sctp_style(sk, UDP))
2606                 return -EINVAL;
2607 
2608         if (params.sack_delay) {
2609                 if (asoc) {
2610                         asoc->sackdelay =
2611                                 msecs_to_jiffies(params.sack_delay);
2612                         asoc->param_flags =
2613                                 (asoc->param_flags & ~SPP_SACKDELAY) |
2614                                 SPP_SACKDELAY_ENABLE;
2615                 } else {
2616                         sp->sackdelay = params.sack_delay;
2617                         sp->param_flags =
2618                                 (sp->param_flags & ~SPP_SACKDELAY) |
2619                                 SPP_SACKDELAY_ENABLE;
2620                 }
2621         }
2622 
2623         if (params.sack_freq == 1) {
2624                 if (asoc) {
2625                         asoc->param_flags =
2626                                 (asoc->param_flags & ~SPP_SACKDELAY) |
2627                                 SPP_SACKDELAY_DISABLE;
2628                 } else {
2629                         sp->param_flags =
2630                                 (sp->param_flags & ~SPP_SACKDELAY) |
2631                                 SPP_SACKDELAY_DISABLE;
2632                 }
2633         } else if (params.sack_freq > 1) {
2634                 if (asoc) {
2635                         asoc->sackfreq = params.sack_freq;
2636                         asoc->param_flags =
2637                                 (asoc->param_flags & ~SPP_SACKDELAY) |
2638                                 SPP_SACKDELAY_ENABLE;
2639                 } else {
2640                         sp->sackfreq = params.sack_freq;
2641                         sp->param_flags =
2642                                 (sp->param_flags & ~SPP_SACKDELAY) |
2643                                 SPP_SACKDELAY_ENABLE;
2644                 }
2645         }
2646 
2647         /* If change is for association, also apply to each transport. */
2648         if (asoc) {
2649                 list_for_each_entry(trans, &asoc->peer.transport_addr_list,
2650                                 transports) {
2651                         if (params.sack_delay) {
2652                                 trans->sackdelay =
2653                                         msecs_to_jiffies(params.sack_delay);
2654                                 trans->param_flags =
2655                                         (trans->param_flags & ~SPP_SACKDELAY) |
2656                                         SPP_SACKDELAY_ENABLE;
2657                         }
2658                         if (params.sack_freq == 1) {
2659                                 trans->param_flags =
2660                                         (trans->param_flags & ~SPP_SACKDELAY) |
2661                                         SPP_SACKDELAY_DISABLE;
2662                         } else if (params.sack_freq > 1) {
2663                                 trans->sackfreq = params.sack_freq;
2664                                 trans->param_flags =
2665                                         (trans->param_flags & ~SPP_SACKDELAY) |
2666                                         SPP_SACKDELAY_ENABLE;
2667                         }
2668                 }
2669         }
2670 
2671         return 0;
2672 }
2673 
2674 /* 7.1.3 Initialization Parameters (SCTP_INITMSG)
2675  *
2676  * Applications can specify protocol parameters for the default association
2677  * initialization.  The option name argument to setsockopt() and getsockopt()
2678  * is SCTP_INITMSG.
2679  *
2680  * Setting initialization parameters is effective only on an unconnected
2681  * socket (for UDP-style sockets only future associations are effected
2682  * by the change).  With TCP-style sockets, this option is inherited by
2683  * sockets derived from a listener socket.
2684  */
2685 static int sctp_setsockopt_initmsg(struct sock *sk, char __user *optval, unsigned int optlen)
2686 {
2687         struct sctp_initmsg sinit;
2688         struct sctp_sock *sp = sctp_sk(sk);
2689 
2690         if (optlen != sizeof(struct sctp_initmsg))
2691                 return -EINVAL;
2692         if (copy_from_user(&sinit, optval, optlen))
2693                 return -EFAULT;
2694 
2695         if (sinit.sinit_num_ostreams)
2696                 sp->initmsg.sinit_num_ostreams = sinit.sinit_num_ostreams;
2697         if (sinit.sinit_max_instreams)
2698                 sp->initmsg.sinit_max_instreams = sinit.sinit_max_instreams;
2699         if (sinit.sinit_max_attempts)
2700                 sp->initmsg.sinit_max_attempts = sinit.sinit_max_attempts;
2701         if (sinit.sinit_max_init_timeo)
2702                 sp->initmsg.sinit_max_init_timeo = sinit.sinit_max_init_timeo;
2703 
2704         return 0;
2705 }
2706 
2707 /*
2708  * 7.1.14 Set default send parameters (SCTP_DEFAULT_SEND_PARAM)
2709  *
2710  *   Applications that wish to use the sendto() system call may wish to
2711  *   specify a default set of parameters that would normally be supplied
2712  *   through the inclusion of ancillary data.  This socket option allows
2713  *   such an application to set the default sctp_sndrcvinfo structure.
2714  *   The application that wishes to use this socket option simply passes
2715  *   in to this call the sctp_sndrcvinfo structure defined in Section
2716  *   5.2.2) The input parameters accepted by this call include
2717  *   sinfo_stream, sinfo_flags, sinfo_ppid, sinfo_context,
2718  *   sinfo_timetolive.  The user must provide the sinfo_assoc_id field in
2719  *   to this call if the caller is using the UDP model.
2720  */
2721 static int sctp_setsockopt_default_send_param(struct sock *sk,
2722                                               char __user *optval,
2723                                               unsigned int optlen)
2724 {
2725         struct sctp_sndrcvinfo info;
2726         struct sctp_association *asoc;
2727         struct sctp_sock *sp = sctp_sk(sk);
2728 
2729         if (optlen != sizeof(struct sctp_sndrcvinfo))
2730                 return -EINVAL;
2731         if (copy_from_user(&info, optval, optlen))
2732                 return -EFAULT;
2733 
2734         asoc = sctp_id2assoc(sk, info.sinfo_assoc_id);
2735         if (!asoc && info.sinfo_assoc_id && sctp_style(sk, UDP))
2736                 return -EINVAL;
2737 
2738         if (asoc) {
2739                 asoc->default_stream = info.sinfo_stream;
2740                 asoc->default_flags = info.sinfo_flags;
2741                 asoc->default_ppid = info.sinfo_ppid;
2742                 asoc->default_context = info.sinfo_context;
2743                 asoc->default_timetolive = info.sinfo_timetolive;
2744         } else {
2745                 sp->default_stream = info.sinfo_stream;
2746                 sp->default_flags = info.sinfo_flags;
2747                 sp->default_ppid = info.sinfo_ppid;
2748                 sp->default_context = info.sinfo_context;
2749                 sp->default_timetolive = info.sinfo_timetolive;
2750         }
2751 
2752         return 0;
2753 }
2754 
2755 /* 7.1.10 Set Primary Address (SCTP_PRIMARY_ADDR)
2756  *
2757  * Requests that the local SCTP stack use the enclosed peer address as
2758  * the association primary.  The enclosed address must be one of the
2759  * association peer's addresses.
2760  */
2761 static int sctp_setsockopt_primary_addr(struct sock *sk, char __user *optval,
2762                                         unsigned int optlen)
2763 {
2764         struct sctp_prim prim;
2765         struct sctp_transport *trans;
2766 
2767         if (optlen != sizeof(struct sctp_prim))
2768                 return -EINVAL;
2769 
2770         if (copy_from_user(&prim, optval, sizeof(struct sctp_prim)))
2771                 return -EFAULT;
2772 
2773         trans = sctp_addr_id2transport(sk, &prim.ssp_addr, prim.ssp_assoc_id);
2774         if (!trans)
2775                 return -EINVAL;
2776 
2777         sctp_assoc_set_primary(trans->asoc, trans);
2778 
2779         return 0;
2780 }
2781 
2782 /*
2783  * 7.1.5 SCTP_NODELAY
2784  *
2785  * Turn on/off any Nagle-like algorithm.  This means that packets are
2786  * generally sent as soon as possible and no unnecessary delays are
2787  * introduced, at the cost of more packets in the network.  Expects an
2788  *  integer boolean flag.
2789  */
2790 static int sctp_setsockopt_nodelay(struct sock *sk, char __user *optval,
2791                                    unsigned int optlen)
2792 {
2793         int val;
2794 
2795         if (optlen < sizeof(int))
2796                 return -EINVAL;
2797         if (get_user(val, (int __user *)optval))
2798                 return -EFAULT;
2799 
2800         sctp_sk(sk)->nodelay = (val == 0) ? 0 : 1;
2801         return 0;
2802 }
2803 
2804 /*
2805  *
2806  * 7.1.1 SCTP_RTOINFO
2807  *
2808  * The protocol parameters used to initialize and bound retransmission
2809  * timeout (RTO) are tunable. sctp_rtoinfo structure is used to access
2810  * and modify these parameters.
2811  * All parameters are time values, in milliseconds.  A value of 0, when
2812  * modifying the parameters, indicates that the current value should not
2813  * be changed.
2814  *
2815  */
2816 static int sctp_setsockopt_rtoinfo(struct sock *sk, char __user *optval, unsigned int optlen)
2817 {
2818         struct sctp_rtoinfo rtoinfo;
2819         struct sctp_association *asoc;
2820 
2821         if (optlen != sizeof (struct sctp_rtoinfo))
2822                 return -EINVAL;
2823 
2824         if (copy_from_user(&rtoinfo, optval, optlen))
2825                 return -EFAULT;
2826 
2827         asoc = sctp_id2assoc(sk, rtoinfo.srto_assoc_id);
2828 
2829         /* Set the values to the specific association */
2830         if (!asoc && rtoinfo.srto_assoc_id && sctp_style(sk, UDP))
2831                 return -EINVAL;
2832 
2833         if (asoc) {
2834                 if (rtoinfo.srto_initial != 0)
2835                         asoc->rto_initial =
2836                                 msecs_to_jiffies(rtoinfo.srto_initial);
2837                 if (rtoinfo.srto_max != 0)
2838                         asoc->rto_max = msecs_to_jiffies(rtoinfo.srto_max);
2839                 if (rtoinfo.srto_min != 0)
2840                         asoc->rto_min = msecs_to_jiffies(rtoinfo.srto_min);
2841         } else {
2842                 /* If there is no association or the association-id = 0
2843                  * set the values to the endpoint.
2844                  */
2845                 struct sctp_sock *sp = sctp_sk(sk);
2846 
2847                 if (rtoinfo.srto_initial != 0)
2848                         sp->rtoinfo.srto_initial = rtoinfo.srto_initial;
2849                 if (rtoinfo.srto_max != 0)
2850                         sp->rtoinfo.srto_max = rtoinfo.srto_max;
2851                 if (rtoinfo.srto_min != 0)
2852                         sp->rtoinfo.srto_min = rtoinfo.srto_min;
2853         }
2854 
2855         return 0;
2856 }
2857 
2858 /*
2859  *
2860  * 7.1.2 SCTP_ASSOCINFO
2861  *
2862  * This option is used to tune the maximum retransmission attempts
2863  * of the association.
2864  * Returns an error if the new association retransmission value is
2865  * greater than the sum of the retransmission value  of the peer.
2866  * See [SCTP] for more information.
2867  *
2868  */
2869 static int sctp_setsockopt_associnfo(struct sock *sk, char __user *optval, unsigned int optlen)
2870 {
2871 
2872         struct sctp_assocparams assocparams;
2873         struct sctp_association *asoc;
2874 
2875         if (optlen != sizeof(struct sctp_assocparams))
2876                 return -EINVAL;
2877         if (copy_from_user(&assocparams, optval, optlen))
2878                 return -EFAULT;
2879 
2880         asoc = sctp_id2assoc(sk, assocparams.sasoc_assoc_id);
2881 
2882         if (!asoc && assocparams.sasoc_assoc_id && sctp_style(sk, UDP))
2883                 return -EINVAL;
2884 
2885         /* Set the values to the specific association */
2886         if (asoc) {
2887                 if (assocparams.sasoc_asocmaxrxt != 0) {
2888                         __u32 path_sum = 0;
2889                         int   paths = 0;
2890                         struct sctp_transport *peer_addr;
2891 
2892                         list_for_each_entry(peer_addr, &asoc->peer.transport_addr_list,
2893                                         transports) {
2894                                 path_sum += peer_addr->pathmaxrxt;
2895                                 paths++;
2896                         }
2897 
2898                         /* Only validate asocmaxrxt if we have more than
2899                          * one path/transport.  We do this because path
2900                          * retransmissions are only counted when we have more
2901                          * then one path.
2902                          */
2903                         if (paths > 1 &&
2904                             assocparams.sasoc_asocmaxrxt > path_sum)
2905                                 return -EINVAL;
2906 
2907                         asoc->max_retrans = assocparams.sasoc_asocmaxrxt;
2908                 }
2909 
2910                 if (assocparams.sasoc_cookie_life != 0)
2911                         asoc->cookie_life = ms_to_ktime(assocparams.sasoc_cookie_life);
2912         } else {
2913                 /* Set the values to the endpoint */
2914                 struct sctp_sock *sp = sctp_sk(sk);
2915 
2916                 if (assocparams.sasoc_asocmaxrxt != 0)
2917                         sp->assocparams.sasoc_asocmaxrxt =
2918                                                 assocparams.sasoc_asocmaxrxt;
2919                 if (assocparams.sasoc_cookie_life != 0)
2920                         sp->assocparams.sasoc_cookie_life =
2921                                                 assocparams.sasoc_cookie_life;
2922         }
2923         return 0;
2924 }
2925 
2926 /*
2927  * 7.1.16 Set/clear IPv4 mapped addresses (SCTP_I_WANT_MAPPED_V4_ADDR)
2928  *
2929  * This socket option is a boolean flag which turns on or off mapped V4
2930  * addresses.  If this option is turned on and the socket is type
2931  * PF_INET6, then IPv4 addresses will be mapped to V6 representation.
2932  * If this option is turned off, then no mapping will be done of V4
2933  * addresses and a user will receive both PF_INET6 and PF_INET type
2934  * addresses on the socket.
2935  */
2936 static int sctp_setsockopt_mappedv4(struct sock *sk, char __user *optval, unsigned int optlen)
2937 {
2938         int val;
2939         struct sctp_sock *sp = sctp_sk(sk);
2940 
2941         if (optlen < sizeof(int))
2942                 return -EINVAL;
2943         if (get_user(val, (int __user *)optval))
2944                 return -EFAULT;
2945         if (val)
2946                 sp->v4mapped = 1;
2947         else
2948                 sp->v4mapped = 0;
2949 
2950         return 0;
2951 }
2952 
2953 /*
2954  * 8.1.16.  Get or Set the Maximum Fragmentation Size (SCTP_MAXSEG)
2955  * This option will get or set the maximum size to put in any outgoing
2956  * SCTP DATA chunk.  If a message is larger than this size it will be
2957  * fragmented by SCTP into the specified size.  Note that the underlying
2958  * SCTP implementation may fragment into smaller sized chunks when the
2959  * PMTU of the underlying association is smaller than the value set by
2960  * the user.  The default value for this option is '' which indicates
2961  * the user is NOT limiting fragmentation and only the PMTU will effect
2962  * SCTP's choice of DATA chunk size.  Note also that values set larger
2963  * than the maximum size of an IP datagram will effectively let SCTP
2964  * control fragmentation (i.e. the same as setting this option to 0).
2965  *
2966  * The following structure is used to access and modify this parameter:
2967  *
2968  * struct sctp_assoc_value {
2969  *   sctp_assoc_t assoc_id;
2970  *   uint32_t assoc_value;
2971  * };
2972  *
2973  * assoc_id:  This parameter is ignored for one-to-one style sockets.
2974  *    For one-to-many style sockets this parameter indicates which
2975  *    association the user is performing an action upon.  Note that if
2976  *    this field's value is zero then the endpoints default value is
2977  *    changed (effecting future associations only).
2978  * assoc_value:  This parameter specifies the maximum size in bytes.
2979  */
2980 static int sctp_setsockopt_maxseg(struct sock *sk, char __user *optval, unsigned int optlen)
2981 {
2982         struct sctp_assoc_value params;
2983         struct sctp_association *asoc;
2984         struct sctp_sock *sp = sctp_sk(sk);
2985         int val;
2986 
2987         if (optlen == sizeof(int)) {
2988                 pr_warn("Use of int in maxseg socket option deprecated\n");
2989                 pr_warn("Use struct sctp_assoc_value instead\n");
2990                 if (copy_from_user(&val, optval, optlen))
2991                         return -EFAULT;
2992                 params.assoc_id = 0;
2993         } else if (optlen == sizeof(struct sctp_assoc_value)) {
2994                 if (copy_from_user(&params, optval, optlen))
2995                         return -EFAULT;
2996                 val = params.assoc_value;
2997         } else
2998                 return -EINVAL;
2999 
3000         if ((val != 0) && ((val < 8) || (val > SCTP_MAX_CHUNK_LEN)))
3001                 return -EINVAL;
3002 
3003         asoc = sctp_id2assoc(sk, params.assoc_id);
3004         if (!asoc && params.assoc_id && sctp_style(sk, UDP))
3005                 return -EINVAL;
3006 
3007         if (asoc) {
3008                 if (val == 0) {
3009                         val = asoc->pathmtu;
3010                         val -= sp->pf->af->net_header_len;
3011                         val -= sizeof(struct sctphdr) +
3012                                         sizeof(struct sctp_data_chunk);
3013                 }
3014                 asoc->user_frag = val;
3015                 asoc->frag_point = sctp_frag_point(asoc, asoc->pathmtu);
3016         } else {
3017                 sp->user_frag = val;
3018         }
3019 
3020         return 0;
3021 }
3022 
3023 
3024 /*
3025  *  7.1.9 Set Peer Primary Address (SCTP_SET_PEER_PRIMARY_ADDR)
3026  *
3027  *   Requests that the peer mark the enclosed address as the association
3028  *   primary. The enclosed address must be one of the association's
3029  *   locally bound addresses. The following structure is used to make a
3030  *   set primary request:
3031  */
3032 static int sctp_setsockopt_peer_primary_addr(struct sock *sk, char __user *optval,
3033                                              unsigned int optlen)
3034 {
3035         struct net *net = sock_net(sk);
3036         struct sctp_sock        *sp;
3037         struct sctp_association *asoc = NULL;
3038         struct sctp_setpeerprim prim;
3039         struct sctp_chunk       *chunk;
3040         struct sctp_af          *af;
3041         int                     err;
3042 
3043         sp = sctp_sk(sk);
3044 
3045         if (!net->sctp.addip_enable)
3046                 return -EPERM;
3047 
3048         if (optlen != sizeof(struct sctp_setpeerprim))
3049                 return -EINVAL;
3050 
3051         if (copy_from_user(&prim, optval, optlen))
3052                 return -EFAULT;
3053 
3054         asoc = sctp_id2assoc(sk, prim.sspp_assoc_id);
3055         if (!asoc)
3056                 return -EINVAL;
3057 
3058         if (!asoc->peer.asconf_capable)
3059                 return -EPERM;
3060 
3061         if (asoc->peer.addip_disabled_mask & SCTP_PARAM_SET_PRIMARY)
3062                 return -EPERM;
3063 
3064         if (!sctp_state(asoc, ESTABLISHED))
3065                 return -ENOTCONN;
3066 
3067         af = sctp_get_af_specific(prim.sspp_addr.ss_family);
3068         if (!af)
3069                 return -EINVAL;
3070 
3071         if (!af->addr_valid((union sctp_addr *)&prim.sspp_addr, sp, NULL))
3072                 return -EADDRNOTAVAIL;
3073 
3074         if (!sctp_assoc_lookup_laddr(asoc, (union sctp_addr *)&prim.sspp_addr))
3075                 return -EADDRNOTAVAIL;
3076 
3077         /* Create an ASCONF chunk with SET_PRIMARY parameter    */
3078         chunk = sctp_make_asconf_set_prim(asoc,
3079                                           (union sctp_addr *)&prim.sspp_addr);
3080         if (!chunk)
3081                 return -ENOMEM;
3082 
3083         err = sctp_send_asconf(asoc, chunk);
3084 
3085         pr_debug("%s: we set peer primary addr primitively\n", __func__);
3086 
3087         return err;
3088 }
3089 
3090 static int sctp_setsockopt_adaptation_layer(struct sock *sk, char __user *optval,
3091                                             unsigned int optlen)
3092 {
3093         struct sctp_setadaptation adaptation;
3094 
3095         if (optlen != sizeof(struct sctp_setadaptation))
3096                 return -EINVAL;
3097         if (copy_from_user(&adaptation, optval, optlen))
3098                 return -EFAULT;
3099 
3100         sctp_sk(sk)->adaptation_ind = adaptation.ssb_adaptation_ind;
3101 
3102         return 0;
3103 }
3104 
3105 /*
3106  * 7.1.29.  Set or Get the default context (SCTP_CONTEXT)
3107  *
3108  * The context field in the sctp_sndrcvinfo structure is normally only
3109  * used when a failed message is retrieved holding the value that was
3110  * sent down on the actual send call.  This option allows the setting of
3111  * a default context on an association basis that will be received on
3112  * reading messages from the peer.  This is especially helpful in the
3113  * one-2-many model for an application to keep some reference to an
3114  * internal state machine that is processing messages on the
3115  * association.  Note that the setting of this value only effects
3116  * received messages from the peer and does not effect the value that is
3117  * saved with outbound messages.
3118  */
3119 static int sctp_setsockopt_context(struct sock *sk, char __user *optval,
3120                                    unsigned int optlen)
3121 {
3122         struct sctp_assoc_value params;
3123         struct sctp_sock *sp;
3124         struct sctp_association *asoc;
3125 
3126         if (optlen != sizeof(struct sctp_assoc_value))
3127                 return -EINVAL;
3128         if (copy_from_user(&params, optval, optlen))
3129                 return -EFAULT;
3130 
3131         sp = sctp_sk(sk);
3132 
3133         if (params.assoc_id != 0) {
3134                 asoc = sctp_id2assoc(sk, params.assoc_id);
3135                 if (!asoc)
3136                         return -EINVAL;
3137                 asoc->default_rcv_context = params.assoc_value;
3138         } else {
3139                 sp->default_rcv_context = params.assoc_value;
3140         }
3141 
3142         return 0;
3143 }
3144 
3145 /*
3146  * 7.1.24.  Get or set fragmented interleave (SCTP_FRAGMENT_INTERLEAVE)
3147  *
3148  * This options will at a minimum specify if the implementation is doing
3149  * fragmented interleave.  Fragmented interleave, for a one to many
3150  * socket, is when subsequent calls to receive a message may return
3151  * parts of messages from different associations.  Some implementations
3152  * may allow you to turn this value on or off.  If so, when turned off,
3153  * no fragment interleave will occur (which will cause a head of line
3154  * blocking amongst multiple associations sharing the same one to many
3155  * socket).  When this option is turned on, then each receive call may
3156  * come from a different association (thus the user must receive data
3157  * with the extended calls (e.g. sctp_recvmsg) to keep track of which
3158  * association each receive belongs to.
3159  *
3160  * This option takes a boolean value.  A non-zero value indicates that
3161  * fragmented interleave is on.  A value of zero indicates that
3162  * fragmented interleave is off.
3163  *
3164  * Note that it is important that an implementation that allows this
3165  * option to be turned on, have it off by default.  Otherwise an unaware
3166  * application using the one to many model may become confused and act
3167  * incorrectly.
3168  */
3169 static int sctp_setsockopt_fragment_interleave(struct sock *sk,
3170                                                char __user *optval,
3171                                                unsigned int optlen)
3172 {
3173         int val;
3174 
3175         if (optlen != sizeof(int))
3176                 return -EINVAL;
3177         if (get_user(val, (int __user *)optval))
3178                 return -EFAULT;
3179 
3180         sctp_sk(sk)->frag_interleave = (val == 0) ? 0 : 1;
3181 
3182         return 0;
3183 }
3184 
3185 /*
3186  * 8.1.21.  Set or Get the SCTP Partial Delivery Point
3187  *       (SCTP_PARTIAL_DELIVERY_POINT)
3188  *
3189  * This option will set or get the SCTP partial delivery point.  This
3190  * point is the size of a message where the partial delivery API will be
3191  * invoked to help free up rwnd space for the peer.  Setting this to a
3192  * lower value will cause partial deliveries to happen more often.  The
3193  * calls argument is an integer that sets or gets the partial delivery
3194  * point.  Note also that the call will fail if the user attempts to set
3195  * this value larger than the socket receive buffer size.
3196  *
3197  * Note that any single message having a length smaller than or equal to
3198  * the SCTP partial delivery point will be delivered in one single read
3199  * call as long as the user provided buffer is large enough to hold the
3200  * message.
3201  */
3202 static int sctp_setsockopt_partial_delivery_point(struct sock *sk,
3203                                                   char __user *optval,
3204                                                   unsigned int optlen)
3205 {
3206         u32 val;
3207 
3208         if (optlen != sizeof(u32))
3209                 return -EINVAL;
3210         if (get_user(val, (int __user *)optval))
3211                 return -EFAULT;
3212 
3213         /* Note: We double the receive buffer from what the user sets
3214          * it to be, also initial rwnd is based on rcvbuf/2.
3215          */
3216         if (val > (sk->sk_rcvbuf >> 1))
3217                 return -EINVAL;
3218 
3219         sctp_sk(sk)->pd_point = val;
3220 
3221         return 0; /* is this the right error code? */
3222 }
3223 
3224 /*
3225  * 7.1.28.  Set or Get the maximum burst (SCTP_MAX_BURST)
3226  *
3227  * This option will allow a user to change the maximum burst of packets
3228  * that can be emitted by this association.  Note that the default value
3229  * is 4, and some implementations may restrict this setting so that it
3230  * can only be lowered.
3231  *
3232  * NOTE: This text doesn't seem right.  Do this on a socket basis with
3233  * future associations inheriting the socket value.
3234  */
3235 static int sctp_setsockopt_maxburst(struct sock *sk,
3236                                     char __user *optval,
3237                                     unsigned int optlen)
3238 {
3239         struct sctp_assoc_value params;
3240         struct sctp_sock *sp;
3241         struct sctp_association *asoc;
3242         int val;
3243         int assoc_id = 0;
3244 
3245         if (optlen == sizeof(int)) {
3246                 pr_warn("Use of int in max_burst socket option deprecated\n");
3247                 pr_warn("Use struct sctp_assoc_value instead\n");
3248                 if (copy_from_user(&val, optval, optlen))
3249                         return -EFAULT;
3250         } else if (optlen == sizeof(struct sctp_assoc_value)) {
3251                 if (copy_from_user(&params, optval, optlen))
3252                         return -EFAULT;
3253                 val = params.assoc_value;
3254                 assoc_id = params.assoc_id;
3255         } else
3256                 return -EINVAL;
3257 
3258         sp = sctp_sk(sk);
3259 
3260         if (assoc_id != 0) {
3261                 asoc = sctp_id2assoc(sk, assoc_id);
3262                 if (!asoc)
3263                         return -EINVAL;
3264                 asoc->max_burst = val;
3265         } else
3266                 sp->max_burst = val;
3267 
3268         return 0;
3269 }
3270 
3271 /*
3272  * 7.1.18.  Add a chunk that must be authenticated (SCTP_AUTH_CHUNK)
3273  *
3274  * This set option adds a chunk type that the user is requesting to be
3275  * received only in an authenticated way.  Changes to the list of chunks
3276  * will only effect future associations on the socket.
3277  */
3278 static int sctp_setsockopt_auth_chunk(struct sock *sk,
3279                                       char __user *optval,
3280                                       unsigned int optlen)
3281 {
3282         struct net *net = sock_net(sk);
3283         struct sctp_authchunk val;
3284 
3285         if (!net->sctp.auth_enable)
3286                 return -EACCES;
3287 
3288         if (optlen != sizeof(struct sctp_authchunk))
3289                 return -EINVAL;
3290         if (copy_from_user(&val, optval, optlen))
3291                 return -EFAULT;
3292 
3293         switch (val.sauth_chunk) {
3294         case SCTP_CID_INIT:
3295         case SCTP_CID_INIT_ACK:
3296         case SCTP_CID_SHUTDOWN_COMPLETE:
3297         case SCTP_CID_AUTH:
3298                 return -EINVAL;
3299         }
3300 
3301         /* add this chunk id to the endpoint */
3302         return sctp_auth_ep_add_chunkid(sctp_sk(sk)->ep, val.sauth_chunk);
3303 }
3304 
3305 /*
3306  * 7.1.19.  Get or set the list of supported HMAC Identifiers (SCTP_HMAC_IDENT)
3307  *
3308  * This option gets or sets the list of HMAC algorithms that the local
3309  * endpoint requires the peer to use.
3310  */
3311 static int sctp_setsockopt_hmac_ident(struct sock *sk,
3312                                       char __user *optval,
3313                                       unsigned int optlen)
3314 {
3315         struct net *net = sock_net(sk);
3316         struct sctp_hmacalgo *hmacs;
3317         u32 idents;
3318         int err;
3319 
3320         if (!net->sctp.auth_enable)
3321                 return -EACCES;
3322 
3323         if (optlen < sizeof(struct sctp_hmacalgo))
3324                 return -EINVAL;
3325 
3326         hmacs= memdup_user(optval, optlen);
3327         if (IS_ERR(hmacs))
3328                 return PTR_ERR(hmacs);
3329 
3330         idents = hmacs->shmac_num_idents;
3331         if (idents == 0 || idents > SCTP_AUTH_NUM_HMACS ||
3332             (idents * sizeof(u16)) > (optlen - sizeof(struct sctp_hmacalgo))) {
3333                 err = -EINVAL;
3334                 goto out;
3335         }
3336 
3337         err = sctp_auth_ep_set_hmacs(sctp_sk(sk)->ep, hmacs);
3338 out:
3339         kfree(hmacs);
3340         return err;
3341 }
3342 
3343 /*
3344  * 7.1.20.  Set a shared key (SCTP_AUTH_KEY)
3345  *
3346  * This option will set a shared secret key which is used to build an
3347  * association shared key.
3348  */
3349 static int sctp_setsockopt_auth_key(struct sock *sk,
3350                                     char __user *optval,
3351                                     unsigned int optlen)
3352 {
3353         struct net *net = sock_net(sk);
3354         struct sctp_authkey *authkey;
3355         struct sctp_association *asoc;
3356         int ret;
3357 
3358         if (!net->sctp.auth_enable)
3359                 return -EACCES;
3360 
3361         if (optlen <= sizeof(struct sctp_authkey))
3362                 return -EINVAL;
3363 
3364         authkey= memdup_user(optval, optlen);
3365         if (IS_ERR(authkey))
3366                 return PTR_ERR(authkey);
3367 
3368         if (authkey->sca_keylength > optlen - sizeof(struct sctp_authkey)) {
3369                 ret = -EINVAL;
3370                 goto out;
3371         }
3372 
3373         asoc = sctp_id2assoc(sk, authkey->sca_assoc_id);
3374         if (!asoc && authkey->sca_assoc_id && sctp_style(sk, UDP)) {
3375                 ret = -EINVAL;
3376                 goto out;
3377         }
3378 
3379         ret = sctp_auth_set_key(sctp_sk(sk)->ep, asoc, authkey);
3380 out:
3381         kzfree(authkey);
3382         return ret;
3383 }
3384 
3385 /*
3386  * 7.1.21.  Get or set the active shared key (SCTP_AUTH_ACTIVE_KEY)
3387  *
3388  * This option will get or set the active shared key to be used to build
3389  * the association shared key.
3390  */
3391 static int sctp_setsockopt_active_key(struct sock *sk,
3392                                       char __user *optval,
3393                                       unsigned int optlen)
3394 {
3395         struct net *net = sock_net(sk);
3396         struct sctp_authkeyid val;
3397         struct sctp_association *asoc;
3398 
3399         if (!net->sctp.auth_enable)
3400                 return -EACCES;
3401 
3402         if (optlen != sizeof(struct sctp_authkeyid))
3403                 return -EINVAL;
3404         if (copy_from_user(&val, optval, optlen))
3405                 return -EFAULT;
3406 
3407         asoc = sctp_id2assoc(sk, val.scact_assoc_id);
3408         if (!asoc && val.scact_assoc_id && sctp_style(sk, UDP))
3409                 return -EINVAL;
3410 
3411         return sctp_auth_set_active_key(sctp_sk(sk)->ep, asoc,
3412                                         val.scact_keynumber);
3413 }
3414 
3415 /*
3416  * 7.1.22.  Delete a shared key (SCTP_AUTH_DELETE_KEY)
3417  *
3418  * This set option will delete a shared secret key from use.
3419  */
3420 static int sctp_setsockopt_del_key(struct sock *sk,
3421                                    char __user *optval,
3422                                    unsigned int optlen)
3423 {
3424         struct net *net = sock_net(sk);
3425         struct sctp_authkeyid val;
3426         struct sctp_association *asoc;
3427 
3428         if (!net->sctp.auth_enable)
3429                 return -EACCES;
3430 
3431         if (optlen != sizeof(struct sctp_authkeyid))
3432                 return -EINVAL;
3433         if (copy_from_user(&val, optval, optlen))
3434                 return -EFAULT;
3435 
3436         asoc = sctp_id2assoc(sk, val.scact_assoc_id);
3437         if (!asoc && val.scact_assoc_id && sctp_style(sk, UDP))
3438                 return -EINVAL;
3439 
3440         return sctp_auth_del_key_id(sctp_sk(sk)->ep, asoc,
3441                                     val.scact_keynumber);
3442 
3443 }
3444 
3445 /*
3446  * 8.1.23 SCTP_AUTO_ASCONF
3447  *
3448  * This option will enable or disable the use of the automatic generation of
3449  * ASCONF chunks to add and delete addresses to an existing association.  Note
3450  * that this option has two caveats namely: a) it only affects sockets that
3451  * are bound to all addresses available to the SCTP stack, and b) the system
3452  * administrator may have an overriding control that turns the ASCONF feature
3453  * off no matter what setting the socket option may have.
3454  * This option expects an integer boolean flag, where a non-zero value turns on
3455  * the option, and a zero value turns off the option.
3456  * Note. In this implementation, socket operation overrides default parameter
3457  * being set by sysctl as well as FreeBSD implementation
3458  */
3459 static int sctp_setsockopt_auto_asconf(struct sock *sk, char __user *optval,
3460                                         unsigned int optlen)
3461 {
3462         int val;
3463         struct sctp_sock *sp = sctp_sk(sk);
3464 
3465         if (optlen < sizeof(int))
3466                 return -EINVAL;
3467         if (get_user(val, (int __user *)optval))
3468                 return -EFAULT;
3469         if (!sctp_is_ep_boundall(sk) && val)
3470                 return -EINVAL;
3471         if ((val && sp->do_auto_asconf) || (!val && !sp->do_auto_asconf))
3472                 return 0;
3473 
3474         if (val == 0 && sp->do_auto_asconf) {
3475                 list_del(&sp->auto_asconf_list);
3476                 sp->do_auto_asconf = 0;
3477         } else if (val && !sp->do_auto_asconf) {
3478                 list_add_tail(&sp->auto_asconf_list,
3479                     &sock_net(sk)->sctp.auto_asconf_splist);
3480                 sp->do_auto_asconf = 1;
3481         }
3482         return 0;
3483 }
3484 
3485 
3486 /*
3487  * SCTP_PEER_ADDR_THLDS
3488  *
3489  * This option allows us to alter the partially failed threshold for one or all
3490  * transports in an association.  See Section 6.1 of:
3491  * http://www.ietf.org/id/draft-nishida-tsvwg-sctp-failover-05.txt
3492  */
3493 static int sctp_setsockopt_paddr_thresholds(struct sock *sk,
3494                                             char __user *optval,
3495                                             unsigned int optlen)
3496 {
3497         struct sctp_paddrthlds val;
3498         struct sctp_transport *trans;
3499         struct sctp_association *asoc;
3500 
3501         if (optlen < sizeof(struct sctp_paddrthlds))
3502                 return -EINVAL;
3503         if (copy_from_user(&val, (struct sctp_paddrthlds __user *)optval,
3504                            sizeof(struct sctp_paddrthlds)))
3505                 return -EFAULT;
3506 
3507 
3508         if (sctp_is_any(sk, (const union sctp_addr *)&val.spt_address)) {
3509                 asoc = sctp_id2assoc(sk, val.spt_assoc_id);
3510                 if (!asoc)
3511                         return -ENOENT;
3512                 list_for_each_entry(trans, &asoc->peer.transport_addr_list,
3513                                     transports) {
3514                         if (val.spt_pathmaxrxt)
3515                                 trans->pathmaxrxt = val.spt_pathmaxrxt;
3516                         trans->pf_retrans = val.spt_pathpfthld;
3517                 }
3518 
3519                 if (val.spt_pathmaxrxt)
3520                         asoc->pathmaxrxt = val.spt_pathmaxrxt;
3521                 asoc->pf_retrans = val.spt_pathpfthld;
3522         } else {
3523                 trans = sctp_addr_id2transport(sk, &val.spt_address,
3524                                                val.spt_assoc_id);
3525                 if (!trans)
3526                         return -ENOENT;
3527 
3528                 if (val.spt_pathmaxrxt)
3529                         trans->pathmaxrxt = val.spt_pathmaxrxt;
3530                 trans->pf_retrans = val.spt_pathpfthld;
3531         }
3532 
3533         return 0;
3534 }
3535 
3536 /* API 6.2 setsockopt(), getsockopt()
3537  *
3538  * Applications use setsockopt() and getsockopt() to set or retrieve
3539  * socket options.  Socket options are used to change the default
3540  * behavior of sockets calls.  They are described in Section 7.
3541  *
3542  * The syntax is:
3543  *
3544  *   ret = getsockopt(int sd, int level, int optname, void __user *optval,
3545  *                    int __user *optlen);
3546  *   ret = setsockopt(int sd, int level, int optname, const void __user *optval,
3547  *                    int optlen);
3548  *
3549  *   sd      - the socket descript.
3550  *   level   - set to IPPROTO_SCTP for all SCTP options.
3551  *   optname - the option name.
3552  *   optval  - the buffer to store the value of the option.
3553  *   optlen  - the size of the buffer.
3554  */
3555 static int sctp_setsockopt(struct sock *sk, int level, int optname,
3556                            char __user *optval, unsigned int optlen)
3557 {
3558         int retval = 0;
3559 
3560         pr_debug("%s: sk:%p, optname:%d\n", __func__, sk, optname);
3561 
3562         /* I can hardly begin to describe how wrong this is.  This is
3563          * so broken as to be worse than useless.  The API draft
3564          * REALLY is NOT helpful here...  I am not convinced that the
3565          * semantics of setsockopt() with a level OTHER THAN SOL_SCTP
3566          * are at all well-founded.
3567          */
3568         if (level != SOL_SCTP) {
3569                 struct sctp_af *af = sctp_sk(sk)->pf->af;
3570                 retval = af->setsockopt(sk, level, optname, optval, optlen);
3571                 goto out_nounlock;
3572         }
3573 
3574         sctp_lock_sock(sk);
3575 
3576         switch (optname) {
3577         case SCTP_SOCKOPT_BINDX_ADD:
3578                 /* 'optlen' is the size of the addresses buffer. */
3579                 retval = sctp_setsockopt_bindx(sk, (struct sockaddr __user *)optval,
3580                                                optlen, SCTP_BINDX_ADD_ADDR);
3581                 break;
3582 
3583         case SCTP_SOCKOPT_BINDX_REM:
3584                 /* 'optlen' is the size of the addresses buffer. */
3585                 retval = sctp_setsockopt_bindx(sk, (struct sockaddr __user *)optval,
3586                                                optlen, SCTP_BINDX_REM_ADDR);
3587                 break;
3588 
3589         case SCTP_SOCKOPT_CONNECTX_OLD:
3590                 /* 'optlen' is the size of the addresses buffer. */
3591                 retval = sctp_setsockopt_connectx_old(sk,
3592                                             (struct sockaddr __user *)optval,
3593                                             optlen);
3594                 break;
3595 
3596         case SCTP_SOCKOPT_CONNECTX:
3597                 /* 'optlen' is the size of the addresses buffer. */
3598                 retval = sctp_setsockopt_connectx(sk,
3599                                             (struct sockaddr __user *)optval,
3600                                             optlen);
3601                 break;
3602 
3603         case SCTP_DISABLE_FRAGMENTS:
3604                 retval = sctp_setsockopt_disable_fragments(sk, optval, optlen);
3605                 break;
3606 
3607         case SCTP_EVENTS:
3608                 retval = sctp_setsockopt_events(sk, optval, optlen);
3609                 break;
3610 
3611         case SCTP_AUTOCLOSE:
3612                 retval = sctp_setsockopt_autoclose(sk, optval, optlen);
3613                 break;
3614 
3615         case SCTP_PEER_ADDR_PARAMS:
3616                 retval = sctp_setsockopt_peer_addr_params(sk, optval, optlen);
3617                 break;
3618 
3619         case SCTP_DELAYED_SACK:
3620                 retval = sctp_setsockopt_delayed_ack(sk, optval, optlen);
3621                 break;
3622         case SCTP_PARTIAL_DELIVERY_POINT:
3623                 retval = sctp_setsockopt_partial_delivery_point(sk, optval, optlen);
3624                 break;
3625 
3626         case SCTP_INITMSG:
3627                 retval = sctp_setsockopt_initmsg(sk, optval, optlen);
3628                 break;
3629         case SCTP_DEFAULT_SEND_PARAM:
3630                 retval = sctp_setsockopt_default_send_param(sk, optval,
3631                                                             optlen);
3632                 break;
3633         case SCTP_PRIMARY_ADDR:
3634                 retval = sctp_setsockopt_primary_addr(sk, optval, optlen);
3635                 break;
3636         case SCTP_SET_PEER_PRIMARY_ADDR:
3637                 retval = sctp_setsockopt_peer_primary_addr(sk, optval, optlen);
3638                 break;
3639         case SCTP_NODELAY:
3640                 retval = sctp_setsockopt_nodelay(sk, optval, optlen);
3641                 break;
3642         case SCTP_RTOINFO:
3643                 retval = sctp_setsockopt_rtoinfo(sk, optval, optlen);
3644                 break;
3645         case SCTP_ASSOCINFO:
3646                 retval = sctp_setsockopt_associnfo(sk, optval, optlen);
3647                 break;
3648         case SCTP_I_WANT_MAPPED_V4_ADDR:
3649                 retval = sctp_setsockopt_mappedv4(sk, optval, optlen);
3650                 break;
3651         case SCTP_MAXSEG:
3652                 retval = sctp_setsockopt_maxseg(sk, optval, optlen);
3653                 break;
3654         case SCTP_ADAPTATION_LAYER:
3655                 retval = sctp_setsockopt_adaptation_layer(sk, optval, optlen);
3656                 break;
3657         case SCTP_CONTEXT:
3658                 retval = sctp_setsockopt_context(sk, optval, optlen);
3659                 break;
3660         case SCTP_FRAGMENT_INTERLEAVE:
3661                 retval = sctp_setsockopt_fragment_interleave(sk, optval, optlen);
3662                 break;
3663         case SCTP_MAX_BURST:
3664                 retval = sctp_setsockopt_maxburst(sk, optval, optlen);
3665                 break;
3666         case SCTP_AUTH_CHUNK:
3667                 retval = sctp_setsockopt_auth_chunk(sk, optval, optlen);
3668                 break;
3669         case SCTP_HMAC_IDENT:
3670                 retval = sctp_setsockopt_hmac_ident(sk, optval, optlen);
3671                 break;
3672         case SCTP_AUTH_KEY:
3673                 retval = sctp_setsockopt_auth_key(sk, optval, optlen);
3674                 break;
3675         case SCTP_AUTH_ACTIVE_KEY:
3676                 retval = sctp_setsockopt_active_key(sk, optval, optlen);
3677                 break;
3678         case SCTP_AUTH_DELETE_KEY:
3679                 retval = sctp_setsockopt_del_key(sk, optval, optlen);
3680                 break;
3681         case SCTP_AUTO_ASCONF:
3682                 retval = sctp_setsockopt_auto_asconf(sk, optval, optlen);
3683                 break;
3684         case SCTP_PEER_ADDR_THLDS:
3685                 retval = sctp_setsockopt_paddr_thresholds(sk, optval, optlen);
3686                 break;
3687         default:
3688                 retval = -ENOPROTOOPT;
3689                 break;
3690         }
3691 
3692         sctp_release_sock(sk);
3693 
3694 out_nounlock:
3695         return retval;
3696 }
3697 
3698 /* API 3.1.6 connect() - UDP Style Syntax
3699  *
3700  * An application may use the connect() call in the UDP model to initiate an
3701  * association without sending data.
3702  *
3703  * The syntax is:
3704  *
3705  * ret = connect(int sd, const struct sockaddr *nam, socklen_t len);
3706  *
3707  * sd: the socket descriptor to have a new association added to.
3708  *
3709  * nam: the address structure (either struct sockaddr_in or struct
3710  *    sockaddr_in6 defined in RFC2553 [7]).
3711  *
3712  * len: the size of the address.
3713  */
3714 static int sctp_connect(struct sock *sk, struct sockaddr *addr,
3715                         int addr_len)
3716 {
3717         int err = 0;
3718         struct sctp_af *af;
3719 
3720         sctp_lock_sock(sk);
3721 
3722         pr_debug("%s: sk:%p, sockaddr:%p, addr_len:%d\n", __func__, sk,
3723                  addr, addr_len);
3724 
3725         /* Validate addr_len before calling common connect/connectx routine. */
3726         af = sctp_get_af_specific(addr->sa_family);
3727         if (!af || addr_len < af->sockaddr_len) {
3728                 err = -EINVAL;
3729         } else {
3730                 /* Pass correct addr len to common routine (so it knows there
3731                  * is only one address being passed.
3732                  */
3733                 err = __sctp_connect(sk, addr, af->sockaddr_len, NULL);
3734         }
3735 
3736         sctp_release_sock(sk);
3737         return err;
3738 }
3739 
3740 /* FIXME: Write comments. */
3741 static int sctp_disconnect(struct sock *sk, int flags)
3742 {
3743         return -EOPNOTSUPP; /* STUB */
3744 }
3745 
3746 /* 4.1.4 accept() - TCP Style Syntax
3747  *
3748  * Applications use accept() call to remove an established SCTP
3749  * association from the accept queue of the endpoint.  A new socket
3750  * descriptor will be returned from accept() to represent the newly
3751  * formed association.
3752  */
3753 static struct sock *sctp_accept(struct sock *sk, int flags, int *err)
3754 {
3755         struct sctp_sock *sp;
3756         struct sctp_endpoint *ep;
3757         struct sock *newsk = NULL;
3758         struct sctp_association *asoc;
3759         long timeo;
3760         int error = 0;
3761 
3762         sctp_lock_sock(sk);
3763 
3764         sp = sctp_sk(sk);
3765         ep = sp->ep;
3766 
3767         if (!sctp_style(sk, TCP)) {
3768                 error = -EOPNOTSUPP;
3769                 goto out;
3770         }
3771 
3772         if (!sctp_sstate(sk, LISTENING)) {
3773                 error = -EINVAL;
3774                 goto out;
3775         }
3776 
3777         timeo = sock_rcvtimeo(sk, flags & O_NONBLOCK);
3778 
3779         error = sctp_wait_for_accept(sk, timeo);
3780         if (error)
3781                 goto out;
3782 
3783         /* We treat the list of associations on the endpoint as the accept
3784          * queue and pick the first association on the list.
3785          */
3786         asoc = list_entry(ep->asocs.next, struct sctp_association, asocs);
3787 
3788         newsk = sp->pf->create_accept_sk(sk, asoc);
3789         if (!newsk) {
3790                 error = -ENOMEM;
3791                 goto out;
3792         }
3793 
3794         /* Populate the fields of the newsk from the oldsk and migrate the
3795          * asoc to the newsk.
3796          */
3797         sctp_sock_migrate(sk, newsk, asoc, SCTP_SOCKET_TCP);
3798 
3799 out:
3800         sctp_release_sock(sk);
3801         *err = error;
3802         return newsk;
3803 }
3804 
3805 /* The SCTP ioctl handler. */
3806 static int sctp_ioctl(struct sock *sk, int cmd, unsigned long arg)
3807 {
3808         int rc = -ENOTCONN;
3809 
3810         sctp_lock_sock(sk);
3811 
3812         /*
3813          * SEQPACKET-style sockets in LISTENING state are valid, for
3814          * SCTP, so only discard TCP-style sockets in LISTENING state.
3815          */
3816         if (sctp_style(sk, TCP) && sctp_sstate(sk, LISTENING))
3817                 goto out;
3818 
3819         switch (cmd) {
3820         case SIOCINQ: {
3821                 struct sk_buff *skb;
3822                 unsigned int amount = 0;
3823 
3824                 skb = skb_peek(&sk->sk_receive_queue);
3825                 if (skb != NULL) {
3826                         /*
3827                          * We will only return the amount of this packet since
3828                          * that is all that will be read.
3829                          */
3830                         amount = skb->len;
3831                 }
3832                 rc = put_user(amount, (int __user *)arg);
3833                 break;
3834         }
3835         default:
3836                 rc = -ENOIOCTLCMD;
3837                 break;
3838         }
3839 out:
3840         sctp_release_sock(sk);
3841         return rc;
3842 }
3843 
3844 /* This is the function which gets called during socket creation to
3845  * initialized the SCTP-specific portion of the sock.
3846  * The sock structure should already be zero-filled memory.
3847  */
3848 static int sctp_init_sock(struct sock *sk)
3849 {
3850         struct net *net = sock_net(sk);
3851         struct sctp_sock *sp;
3852 
3853         pr_debug("%s: sk:%p\n", __func__, sk);
3854 
3855         sp = sctp_sk(sk);
3856 
3857         /* Initialize the SCTP per socket area.  */
3858         switch (sk->sk_type) {
3859         case SOCK_SEQPACKET:
3860                 sp->type = SCTP_SOCKET_UDP;
3861                 break;
3862         case SOCK_STREAM:
3863                 sp->type = SCTP_SOCKET_TCP;
3864                 break;
3865         default:
3866                 return -ESOCKTNOSUPPORT;
3867         }
3868 
3869         /* Initialize default send parameters. These parameters can be
3870          * modified with the SCTP_DEFAULT_SEND_PARAM socket option.
3871          */
3872         sp->default_stream = 0;
3873         sp->default_ppid = 0;
3874         sp->default_flags = 0;
3875         sp->default_context = 0;
3876         sp->default_timetolive = 0;
3877 
3878         sp->default_rcv_context = 0;
3879         sp->max_burst = net->sctp.max_burst;
3880 
3881         sp->sctp_hmac_alg = net->sctp.sctp_hmac_alg;
3882 
3883         /* Initialize default setup parameters. These parameters
3884          * can be modified with the SCTP_INITMSG socket option or
3885          * overridden by the SCTP_INIT CMSG.
3886          */
3887         sp->initmsg.sinit_num_ostreams   = sctp_max_outstreams;
3888         sp->initmsg.sinit_max_instreams  = sctp_max_instreams;
3889         sp->initmsg.sinit_max_attempts   = net->sctp.max_retrans_init;
3890         sp->initmsg.sinit_max_init_timeo = net->sctp.rto_max;
3891 
3892         /* Initialize default RTO related parameters.  These parameters can
3893          * be modified for with the SCTP_RTOINFO socket option.
3894          */
3895         sp->rtoinfo.srto_initial = net->sctp.rto_initial;
3896         sp->rtoinfo.srto_max     = net->sctp.rto_max;
3897         sp->rtoinfo.srto_min     = net->sctp.rto_min;
3898 
3899         /* Initialize default association related parameters. These parameters
3900          * can be modified with the SCTP_ASSOCINFO socket option.
3901          */
3902         sp->assocparams.sasoc_asocmaxrxt = net->sctp.max_retrans_association;
3903         sp->assocparams.sasoc_number_peer_destinations = 0;
3904         sp->assocparams.sasoc_peer_rwnd = 0;
3905         sp->assocparams.sasoc_local_rwnd = 0;
3906         sp->assocparams.sasoc_cookie_life = net->sctp.valid_cookie_life;
3907 
3908         /* Initialize default event subscriptions. By default, all the
3909          * options are off.
3910          */
3911         memset(&sp->subscribe, 0, sizeof(struct sctp_event_subscribe));
3912 
3913         /* Default Peer Address Parameters.  These defaults can
3914          * be modified via SCTP_PEER_ADDR_PARAMS
3915          */
3916         sp->hbinterval  = net->sctp.hb_interval;
3917         sp->pathmaxrxt  = net->sctp.max_retrans_path;
3918         sp->pathmtu     = 0; // allow default discovery
3919         sp->sackdelay   = net->sctp.sack_timeout;
3920         sp->sackfreq    = 2;
3921         sp->param_flags = SPP_HB_ENABLE |
3922                           SPP_PMTUD_ENABLE |
3923                           SPP_SACKDELAY_ENABLE;
3924 
3925         /* If enabled no SCTP message fragmentation will be performed.
3926          * Configure through SCTP_DISABLE_FRAGMENTS socket option.
3927          */
3928         sp->disable_fragments = 0;
3929 
3930         /* Enable Nagle algorithm by default.  */
3931         sp->nodelay           = 0;
3932 
3933         /* Enable by default. */
3934         sp->v4mapped          = 1;
3935 
3936         /* Auto-close idle associations after the configured
3937          * number of seconds.  A value of 0 disables this
3938          * feature.  Configure through the SCTP_AUTOCLOSE socket option,
3939          * for UDP-style sockets only.
3940          */
3941         sp->autoclose         = 0;
3942 
3943         /* User specified fragmentation limit. */
3944         sp->user_frag         = 0;
3945 
3946         sp->adaptation_ind = 0;
3947 
3948         sp->pf = sctp_get_pf_specific(sk->sk_family);
3949 
3950         /* Control variables for partial data delivery. */
3951         atomic_set(&sp->pd_mode, 0);
3952         skb_queue_head_init(&sp->pd_lobby);
3953         sp->frag_interleave = 0;
3954 
3955         /* Create a per socket endpoint structure.  Even if we
3956          * change the data structure relationships, this may still
3957          * be useful for storing pre-connect address information.
3958          */
3959         sp->ep = sctp_endpoint_new(sk, GFP_KERNEL);
3960         if (!sp->ep)
3961                 return -ENOMEM;
3962 
3963         sp->hmac = NULL;
3964 
3965         sk->sk_destruct = sctp_destruct_sock;
3966 
3967         SCTP_DBG_OBJCNT_INC(sock);
3968 
3969         local_bh_disable();
3970         percpu_counter_inc(&sctp_sockets_allocated);
3971         sock_prot_inuse_add(net, sk->sk_prot, 1);
3972         if (net->sctp.default_auto_asconf) {
3973                 list_add_tail(&sp->auto_asconf_list,
3974                     &net->sctp.auto_asconf_splist);
3975                 sp->do_auto_asconf = 1;
3976         } else
3977                 sp->do_auto_asconf = 0;
3978         local_bh_enable();
3979 
3980         return 0;
3981 }
3982 
3983 /* Cleanup any SCTP per socket resources.  */
3984 static void sctp_destroy_sock(struct sock *sk)
3985 {
3986         struct sctp_sock *sp;
3987 
3988         pr_debug("%s: sk:%p\n", __func__, sk);
3989 
3990         /* Release our hold on the endpoint. */
3991         sp = sctp_sk(sk);
3992         /* This could happen during socket init, thus we bail out
3993          * early, since the rest of the below is not setup either.
3994          */
3995         if (sp->ep == NULL)
3996                 return;
3997 
3998         if (sp->do_auto_asconf) {
3999                 sp->do_auto_asconf = 0;
4000                 list_del(&sp->auto_asconf_list);
4001         }
4002         sctp_endpoint_free(sp->ep);
4003         local_bh_disable();
4004         percpu_counter_dec(&sctp_sockets_allocated);
4005         sock_prot_inuse_add(sock_net(sk), sk->sk_prot, -1);
4006         local_bh_enable();
4007 }
4008 
4009 /* Triggered when there are no references on the socket anymore */
4010 static void sctp_destruct_sock(struct sock *sk)
4011 {
4012         struct sctp_sock *sp = sctp_sk(sk);
4013 
4014         /* Free up the HMAC transform. */
4015         crypto_free_hash(sp->hmac);
4016 
4017         inet_sock_destruct(sk);
4018 }
4019 
4020 /* API 4.1.7 shutdown() - TCP Style Syntax
4021  *     int shutdown(int socket, int how);
4022  *
4023  *     sd      - the socket descriptor of the association to be closed.
4024  *     how     - Specifies the type of shutdown.  The  values  are
4025  *               as follows:
4026  *               SHUT_RD
4027  *                     Disables further receive operations. No SCTP
4028  *                     protocol action is taken.
4029  *               SHUT_WR
4030  *                     Disables further send operations, and initiates
4031  *                     the SCTP shutdown sequence.
4032  *               SHUT_RDWR
4033  *                     Disables further send  and  receive  operations
4034  *                     and initiates the SCTP shutdown sequence.
4035  */
4036 static void sctp_shutdown(struct sock *sk, int how)
4037 {
4038         struct net *net = sock_net(sk);
4039         struct sctp_endpoint *ep;
4040         struct sctp_association *asoc;
4041 
4042         if (!sctp_style(sk, TCP))
4043                 return;
4044 
4045         if (how & SEND_SHUTDOWN) {
4046                 ep = sctp_sk(sk)->ep;
4047                 if (!list_empty(&ep->asocs)) {
4048                         asoc = list_entry(ep->asocs.next,
4049                                           struct sctp_association, asocs);
4050                         sctp_primitive_SHUTDOWN(net, asoc, NULL);
4051                 }
4052         }
4053 }
4054 
4055 /* 7.2.1 Association Status (SCTP_STATUS)
4056 
4057  * Applications can retrieve current status information about an
4058  * association, including association state, peer receiver window size,
4059  * number of unacked data chunks, and number of data chunks pending
4060  * receipt.  This information is read-only.
4061  */
4062 static int sctp_getsockopt_sctp_status(struct sock *sk, int len,
4063                                        char __user *optval,
4064                                        int __user *optlen)
4065 {
4066         struct sctp_status status;
4067         struct sctp_association *asoc = NULL;
4068         struct sctp_transport *transport;
4069         sctp_assoc_t associd;
4070         int retval = 0;
4071 
4072         if (len < sizeof(status)) {
4073                 retval = -EINVAL;
4074                 goto out;
4075         }
4076 
4077         len = sizeof(status);
4078         if (copy_from_user(&status, optval, len)) {
4079                 retval = -EFAULT;
4080                 goto out;
4081         }
4082 
4083         associd = status.sstat_assoc_id;
4084         asoc = sctp_id2assoc(sk, associd);
4085         if (!asoc) {
4086                 retval = -EINVAL;
4087                 goto out;
4088         }
4089 
4090         transport = asoc->peer.primary_path;
4091 
4092         status.sstat_assoc_id = sctp_assoc2id(asoc);
4093         status.sstat_state = asoc->state;
4094         status.sstat_rwnd =  asoc->peer.rwnd;
4095         status.sstat_unackdata = asoc->unack_data;
4096 
4097         status.sstat_penddata = sctp_tsnmap_pending(&asoc->peer.tsn_map);
4098         status.sstat_instrms = asoc->c.sinit_max_instreams;
4099         status.sstat_outstrms = asoc->c.sinit_num_ostreams;
4100         status.sstat_fragmentation_point = asoc->frag_point;
4101         status.sstat_primary.spinfo_assoc_id = sctp_assoc2id(transport->asoc);
4102         memcpy(&status.sstat_primary.spinfo_address, &transport->ipaddr,
4103                         transport->af_specific->sockaddr_len);
4104         /* Map ipv4 address into v4-mapped-on-v6 address.  */
4105         sctp_get_pf_specific(sk->sk_family)->addr_v4map(sctp_sk(sk),
4106                 (union sctp_addr *)&status.sstat_primary.spinfo_address);
4107         status.sstat_primary.spinfo_state = transport->state;
4108         status.sstat_primary.spinfo_cwnd = transport->cwnd;
4109         status.sstat_primary.spinfo_srtt = transport->srtt;
4110         status.sstat_primary.spinfo_rto = jiffies_to_msecs(transport->rto);
4111         status.sstat_primary.spinfo_mtu = transport->pathmtu;
4112 
4113         if (status.sstat_primary.spinfo_state == SCTP_UNKNOWN)
4114                 status.sstat_primary.spinfo_state = SCTP_ACTIVE;
4115 
4116         if (put_user(len, optlen)) {
4117                 retval = -EFAULT;
4118                 goto out;
4119         }
4120 
4121         pr_debug("%s: len:%d, state:%d, rwnd:%d, assoc_id:%d\n",
4122                  __func__, len, status.sstat_state, status.sstat_rwnd,
4123                  status.sstat_assoc_id);
4124 
4125         if (copy_to_user(optval, &status, len)) {
4126                 retval = -EFAULT;
4127                 goto out;
4128         }
4129 
4130 out:
4131         return retval;
4132 }
4133 
4134 
4135 /* 7.2.2 Peer Address Information (SCTP_GET_PEER_ADDR_INFO)
4136  *
4137  * Applications can retrieve information about a specific peer address
4138  * of an association, including its reachability state, congestion
4139  * window, and retransmission timer values.  This information is
4140  * read-only.
4141  */
4142 static int sctp_getsockopt_peer_addr_info(struct sock *sk, int len,
4143                                           char __user *optval,
4144                                           int __user *optlen)
4145 {
4146         struct sctp_paddrinfo pinfo;
4147         struct sctp_transport *transport;
4148         int retval = 0;
4149 
4150         if (len < sizeof(pinfo)) {
4151                 retval = -EINVAL;
4152                 goto out;
4153         }
4154 
4155         len = sizeof(pinfo);
4156         if (copy_from_user(&pinfo, optval, len)) {
4157                 retval = -EFAULT;
4158                 goto out;
4159         }
4160 
4161         transport = sctp_addr_id2transport(sk, &pinfo.spinfo_address,
4162                                            pinfo.spinfo_assoc_id);
4163         if (!transport)
4164                 return -EINVAL;
4165 
4166         pinfo.spinfo_assoc_id = sctp_assoc2id(transport->asoc);
4167         pinfo.spinfo_state = transport->state;
4168         pinfo.spinfo_cwnd = transport->cwnd;
4169         pinfo.spinfo_srtt = transport->srtt;
4170         pinfo.spinfo_rto = jiffies_to_msecs(transport->rto);
4171         pinfo.spinfo_mtu = transport->pathmtu;
4172 
4173         if (pinfo.spinfo_state == SCTP_UNKNOWN)
4174                 pinfo.spinfo_state = SCTP_ACTIVE;
4175 
4176         if (put_user(len, optlen)) {
4177                 retval = -EFAULT;
4178                 goto out;
4179         }
4180 
4181         if (copy_to_user(optval, &pinfo, len)) {
4182                 retval = -EFAULT;
4183                 goto out;
4184         }
4185 
4186 out:
4187         return retval;
4188 }
4189 
4190 /* 7.1.12 Enable/Disable message fragmentation (SCTP_DISABLE_FRAGMENTS)
4191  *
4192  * This option is a on/off flag.  If enabled no SCTP message
4193  * fragmentation will be performed.  Instead if a message being sent
4194  * exceeds the current PMTU size, the message will NOT be sent and
4195  * instead a error will be indicated to the user.
4196  */
4197 static int sctp_getsockopt_disable_fragments(struct sock *sk, int len,
4198                                         char __user *optval, int __user *optlen)
4199 {
4200         int val;
4201 
4202         if (len < sizeof(int))
4203                 return -EINVAL;
4204 
4205         len = sizeof(int);
4206         val = (sctp_sk(sk)->disable_fragments == 1);
4207         if (put_user(len, optlen))
4208                 return -EFAULT;
4209         if (copy_to_user(optval, &val, len))
4210                 return -EFAULT;
4211         return 0;
4212 }
4213 
4214 /* 7.1.15 Set notification and ancillary events (SCTP_EVENTS)
4215  *
4216  * This socket option is used to specify various notifications and
4217  * ancillary data the user wishes to receive.
4218  */
4219 static int sctp_getsockopt_events(struct sock *sk, int len, char __user *optval,
4220                                   int __user *optlen)
4221 {
4222         if (len <= 0)
4223                 return -EINVAL;
4224         if (len > sizeof(struct sctp_event_subscribe))
4225                 len = sizeof(struct sctp_event_subscribe);
4226         if (put_user(len, optlen))
4227                 return -EFAULT;
4228         if (copy_to_user(optval, &sctp_sk(sk)->subscribe, len))
4229                 return -EFAULT;
4230         return 0;
4231 }
4232 
4233 /* 7.1.8 Automatic Close of associations (SCTP_AUTOCLOSE)
4234  *
4235  * This socket option is applicable to the UDP-style socket only.  When
4236  * set it will cause associations that are idle for more than the
4237  * specified number of seconds to automatically close.  An association
4238  * being idle is defined an association that has NOT sent or received
4239  * user data.  The special value of '' indicates that no automatic
4240  * close of any associations should be performed.  The option expects an
4241  * integer defining the number of seconds of idle time before an
4242  * association is closed.
4243  */
4244 static int sctp_getsockopt_autoclose(struct sock *sk, int len, char __user *optval, int __user *optlen)
4245 {
4246         /* Applicable to UDP-style socket only */
4247         if (sctp_style(sk, TCP))
4248                 return -EOPNOTSUPP;
4249         if (len < sizeof(int))
4250                 return -EINVAL;
4251         len = sizeof(int);
4252         if (put_user(len, optlen))
4253                 return -EFAULT;
4254         if (copy_to_user(optval, &sctp_sk(sk)->autoclose, sizeof(int)))
4255                 return -EFAULT;
4256         return 0;
4257 }
4258 
4259 /* Helper routine to branch off an association to a new socket.  */
4260 int sctp_do_peeloff(struct sock *sk, sctp_assoc_t id, struct socket **sockp)
4261 {
4262         struct sctp_association *asoc = sctp_id2assoc(sk, id);
4263         struct socket *sock;
4264         struct sctp_af *af;
4265         int err = 0;
4266 
4267         if (!asoc)
4268                 return -EINVAL;
4269 
4270         /* An association cannot be branched off from an already peeled-off
4271          * socket, nor is this supported for tcp style sockets.
4272          */
4273         if (!sctp_style(sk, UDP))
4274                 return -EINVAL;
4275 
4276         /* Create a new socket.  */
4277         err = sock_create(sk->sk_family, SOCK_SEQPACKET, IPPROTO_SCTP, &sock);
4278         if (err < 0)
4279                 return err;
4280 
4281         sctp_copy_sock(sock->sk, sk, asoc);
4282 
4283         /* Make peeled-off sockets more like 1-1 accepted sockets.
4284          * Set the daddr and initialize id to something more random
4285          */
4286         af = sctp_get_af_specific(asoc->peer.primary_addr.sa.sa_family);
4287         af->to_sk_daddr(&asoc->peer.primary_addr, sk);
4288 
4289         /* Populate the fields of the newsk from the oldsk and migrate the
4290          * asoc to the newsk.
4291          */
4292         sctp_sock_migrate(sk, sock->sk, asoc, SCTP_SOCKET_UDP_HIGH_BANDWIDTH);
4293 
4294         *sockp = sock;
4295 
4296         return err;
4297 }
4298 EXPORT_SYMBOL(sctp_do_peeloff);
4299 
4300 static int sctp_getsockopt_peeloff(struct sock *sk, int len, char __user *optval, int __user *optlen)
4301 {
4302         sctp_peeloff_arg_t peeloff;
4303         struct socket *newsock;
4304         struct file *newfile;
4305         int retval = 0;
4306 
4307         if (len < sizeof(sctp_peeloff_arg_t))
4308                 return -EINVAL;
4309         len = sizeof(sctp_peeloff_arg_t);
4310         if (copy_from_user(&peeloff, optval, len))
4311                 return -EFAULT;
4312 
4313         retval = sctp_do_peeloff(sk, peeloff.associd, &newsock);
4314         if (retval < 0)
4315                 goto out;
4316 
4317         /* Map the socket to an unused fd that can be returned to the user.  */
4318         retval = get_unused_fd_flags(0);
4319         if (retval < 0) {
4320                 sock_release(newsock);
4321                 goto out;
4322         }
4323 
4324         newfile = sock_alloc_file(newsock, 0, NULL);
4325         if (unlikely(IS_ERR(newfile))) {
4326                 put_unused_fd(retval);
4327                 sock_release(newsock);
4328                 return PTR_ERR(newfile);
4329         }
4330 
4331         pr_debug("%s: sk:%p, newsk:%p, sd:%d\n", __func__, sk, newsock->sk,
4332                  retval);
4333 
4334         /* Return the fd mapped to the new socket.  */
4335         if (put_user(len, optlen)) {
4336                 fput(newfile);
4337                 put_unused_fd(retval);
4338                 return -EFAULT;
4339         }
4340         peeloff.sd = retval;
4341         if (copy_to_user(optval, &peeloff, len)) {
4342                 fput(newfile);
4343                 put_unused_fd(retval);
4344                 return -EFAULT;
4345         }
4346         fd_install(retval, newfile);
4347 out:
4348         return retval;
4349 }
4350 
4351 /* 7.1.13 Peer Address Parameters (SCTP_PEER_ADDR_PARAMS)
4352  *
4353  * Applications can enable or disable heartbeats for any peer address of
4354  * an association, modify an address's heartbeat interval, force a
4355  * heartbeat to be sent immediately, and adjust the address's maximum
4356  * number of retransmissions sent before an address is considered
4357  * unreachable.  The following structure is used to access and modify an
4358  * address's parameters:
4359  *
4360  *  struct sctp_paddrparams {
4361  *     sctp_assoc_t            spp_assoc_id;
4362  *     struct sockaddr_storage spp_address;
4363  *     uint32_t                spp_hbinterval;
4364  *     uint16_t                spp_pathmaxrxt;
4365  *     uint32_t                spp_pathmtu;
4366  *     uint32_t                spp_sackdelay;
4367  *     uint32_t                spp_flags;
4368  * };
4369  *
4370  *   spp_assoc_id    - (one-to-many style socket) This is filled in the
4371  *                     application, and identifies the association for
4372  *                     this query.
4373  *   spp_address     - This specifies which address is of interest.
4374  *   spp_hbinterval  - This contains the value of the heartbeat interval,
4375  *                     in milliseconds.  If a  value of zero
4376  *                     is present in this field then no changes are to
4377  *                     be made to this parameter.
4378  *   spp_pathmaxrxt  - This contains the maximum number of
4379  *                     retransmissions before this address shall be
4380  *                     considered unreachable. If a  value of zero
4381  *                     is present in this field then no changes are to
4382  *                     be made to this parameter.
4383  *   spp_pathmtu     - When Path MTU discovery is disabled the value
4384  *                     specified here will be the "fixed" path mtu.
4385  *                     Note that if the spp_address field is empty
4386  *                     then all associations on this address will
4387  *                     have this fixed path mtu set upon them.
4388  *
4389  *   spp_sackdelay   - When delayed sack is enabled, this value specifies
4390  *                     the number of milliseconds that sacks will be delayed
4391  *                     for. This value will apply to all addresses of an
4392  *                     association if the spp_address field is empty. Note
4393  *                     also, that if delayed sack is enabled and this
4394  *                     value is set to 0, no change is made to the last
4395  *                     recorded delayed sack timer value.
4396  *
4397  *   spp_flags       - These flags are used to control various features
4398  *                     on an association. The flag field may contain
4399  *                     zero or more of the following options.
4400  *
4401  *                     SPP_HB_ENABLE  - Enable heartbeats on the
4402  *                     specified address. Note that if the address
4403  *                     field is empty all addresses for the association
4404  *                     have heartbeats enabled upon them.
4405  *
4406  *                     SPP_HB_DISABLE - Disable heartbeats on the
4407  *                     speicifed address. Note that if the address
4408  *                     field is empty all addresses for the association
4409  *                     will have their heartbeats disabled. Note also
4410  *                     that SPP_HB_ENABLE and SPP_HB_DISABLE are
4411  *                     mutually exclusive, only one of these two should
4412  *                     be specified. Enabling both fields will have
4413  *                     undetermined results.
4414  *
4415  *                     SPP_HB_DEMAND - Request a user initiated heartbeat
4416  *                     to be made immediately.
4417  *
4418  *                     SPP_PMTUD_ENABLE - This field will enable PMTU
4419  *                     discovery upon the specified address. Note that
4420  *                     if the address feild is empty then all addresses
4421  *                     on the association are effected.
4422  *
4423  *                     SPP_PMTUD_DISABLE - This field will disable PMTU
4424  *                     discovery upon the specified address. Note that
4425  *                     if the address feild is empty then all addresses
4426  *                     on the association are effected. Not also that
4427  *                     SPP_PMTUD_ENABLE and SPP_PMTUD_DISABLE are mutually
4428  *                     exclusive. Enabling both will have undetermined
4429  *                     results.
4430  *
4431  *                     SPP_SACKDELAY_ENABLE - Setting this flag turns
4432  *                     on delayed sack. The time specified in spp_sackdelay
4433  *                     is used to specify the sack delay for this address. Note
4434  *                     that if spp_address is empty then all addresses will
4435  *                     enable delayed sack and take on the sack delay
4436  *                     value specified in spp_sackdelay.
4437  *                     SPP_SACKDELAY_DISABLE - Setting this flag turns
4438  *                     off delayed sack. If the spp_address field is blank then
4439  *                     delayed sack is disabled for the entire association. Note
4440  *                     also that this field is mutually exclusive to
4441  *                     SPP_SACKDELAY_ENABLE, setting both will have undefined
4442  *                     results.
4443  */
4444 static int sctp_getsockopt_peer_addr_params(struct sock *sk, int len,
4445                                             char __user *optval, int __user *optlen)
4446 {
4447         struct sctp_paddrparams  params;
4448         struct sctp_transport   *trans = NULL;
4449         struct sctp_association *asoc = NULL;
4450         struct sctp_sock        *sp = sctp_sk(sk);
4451 
4452         if (len < sizeof(struct sctp_paddrparams))
4453                 return -EINVAL;
4454         len = sizeof(struct sctp_paddrparams);
4455         if (copy_from_user(&params, optval, len))
4456                 return -EFAULT;
4457 
4458         /* If an address other than INADDR_ANY is specified, and
4459          * no transport is found, then the request is invalid.
4460          */
4461         if (!sctp_is_any(sk, ( union sctp_addr *)&params.spp_address)) {
4462                 trans = sctp_addr_id2transport(sk, &params.spp_address,
4463                                                params.spp_assoc_id);
4464                 if (!trans) {
4465                         pr_debug("%s: failed no transport\n", __func__);
4466                         return -EINVAL;
4467                 }
4468         }
4469 
4470         /* Get association, if assoc_id != 0 and the socket is a one
4471          * to many style socket, and an association was not found, then
4472          * the id was invalid.
4473          */
4474         asoc = sctp_id2assoc(sk, params.spp_assoc_id);
4475         if (!asoc && params.spp_assoc_id && sctp_style(sk, UDP)) {
4476                 pr_debug("%s: failed no association\n", __func__);
4477                 return -EINVAL;
4478         }
4479 
4480         if (trans) {
4481                 /* Fetch transport values. */
4482                 params.spp_hbinterval = jiffies_to_msecs(trans->hbinterval);
4483                 params.spp_pathmtu    = trans->pathmtu;
4484                 params.spp_pathmaxrxt = trans->pathmaxrxt;
4485                 params.spp_sackdelay  = jiffies_to_msecs(trans->sackdelay);
4486 
4487                 /*draft-11 doesn't say what to return in spp_flags*/
4488                 params.spp_flags      = trans->param_flags;
4489         } else if (asoc) {
4490                 /* Fetch association values. */
4491                 params.spp_hbinterval = jiffies_to_msecs(asoc->hbinterval);
4492                 params.spp_pathmtu    = asoc->pathmtu;
4493                 params.spp_pathmaxrxt = asoc->pathmaxrxt;
4494                 params.spp_sackdelay  = jiffies_to_msecs(asoc->sackdelay);
4495 
4496                 /*draft-11 doesn't say what to return in spp_flags*/
4497                 params.spp_flags      = asoc->param_flags;
4498         } else {
4499                 /* Fetch socket values. */
4500                 params.spp_hbinterval = sp->hbinterval;
4501                 params.spp_pathmtu    = sp->pathmtu;
4502                 params.spp_sackdelay  = sp->sackdelay;
4503                 params.spp_pathmaxrxt = sp->pathmaxrxt;
4504 
4505                 /*draft-11 doesn't say what to return in spp_flags*/
4506                 params.spp_flags      = sp->param_flags;
4507         }
4508 
4509         if (copy_to_user(optval, &params, len))
4510                 return -EFAULT;
4511 
4512         if (put_user(len, optlen))
4513                 return -EFAULT;
4514 
4515         return 0;
4516 }
4517 
4518 /*
4519  * 7.1.23.  Get or set delayed ack timer (SCTP_DELAYED_SACK)
4520  *
4521  * This option will effect the way delayed acks are performed.  This
4522  * option allows you to get or set the delayed ack time, in
4523  * milliseconds.  It also allows changing the delayed ack frequency.
4524  * Changing the frequency to 1 disables the delayed sack algorithm.  If
4525  * the assoc_id is 0, then this sets or gets the endpoints default
4526  * values.  If the assoc_id field is non-zero, then the set or get
4527  * effects the specified association for the one to many model (the
4528  * assoc_id field is ignored by the one to one model).  Note that if
4529  * sack_delay or sack_freq are 0 when setting this option, then the
4530  * current values will remain unchanged.
4531  *
4532  * struct sctp_sack_info {
4533  *     sctp_assoc_t            sack_assoc_id;
4534  *     uint32_t                sack_delay;
4535  *     uint32_t                sack_freq;
4536  * };
4537  *
4538  * sack_assoc_id -  This parameter, indicates which association the user
4539  *    is performing an action upon.  Note that if this field's value is
4540  *    zero then the endpoints default value is changed (effecting future
4541  *    associations only).
4542  *
4543  * sack_delay -  This parameter contains the number of milliseconds that
4544  *    the user is requesting the delayed ACK timer be set to.  Note that
4545  *    this value is defined in the standard to be between 200 and 500
4546  *    milliseconds.
4547  *
4548  * sack_freq -  This parameter contains the number of packets that must
4549  *    be received before a sack is sent without waiting for the delay
4550  *    timer to expire.  The default value for this is 2, setting this
4551  *    value to 1 will disable the delayed sack algorithm.
4552  */
4553 static int sctp_getsockopt_delayed_ack(struct sock *sk, int len,
4554                                             char __user *optval,
4555                                             int __user *optlen)
4556 {
4557         struct sctp_sack_info    params;
4558         struct sctp_association *asoc = NULL;
4559         struct sctp_sock        *sp = sctp_sk(sk);
4560 
4561         if (len >= sizeof(struct sctp_sack_info)) {
4562                 len = sizeof(struct sctp_sack_info);
4563 
4564                 if (copy_from_user(&params, optval, len))
4565                         return -EFAULT;
4566         } else if (len == sizeof(struct sctp_assoc_value)) {
4567                 pr_warn("Use of struct sctp_assoc_value in delayed_ack socket option deprecated\n");
4568                 pr_warn("Use struct sctp_sack_info instead\n");
4569                 if (copy_from_user(&params, optval, len))
4570                         return -EFAULT;
4571         } else
4572                 return - EINVAL;
4573 
4574         /* Get association, if sack_assoc_id != 0 and the socket is a one
4575          * to many style socket, and an association was not found, then
4576          * the id was invalid.
4577          */
4578         asoc = sctp_id2assoc(sk, params.sack_assoc_id);
4579         if (!asoc && params.sack_assoc_id && sctp_style(sk, UDP))
4580                 return -EINVAL;
4581 
4582         if (asoc) {
4583                 /* Fetch association values. */
4584                 if (asoc->param_flags & SPP_SACKDELAY_ENABLE) {
4585                         params.sack_delay = jiffies_to_msecs(
4586                                 asoc->sackdelay);
4587                         params.sack_freq = asoc->sackfreq;
4588 
4589                 } else {
4590                         params.sack_delay = 0;
4591                         params.sack_freq = 1;
4592                 }
4593         } else {
4594                 /* Fetch socket values. */
4595                 if (sp->param_flags & SPP_SACKDELAY_ENABLE) {
4596                         params.sack_delay  = sp->sackdelay;
4597                         params.sack_freq = sp->sackfreq;
4598                 } else {
4599                         params.sack_delay  = 0;
4600                         params.sack_freq = 1;
4601                 }
4602         }
4603 
4604         if (copy_to_user(optval, &params, len))
4605                 return -EFAULT;
4606 
4607         if (put_user(len, optlen))
4608                 return -EFAULT;
4609 
4610         return 0;
4611 }
4612 
4613 /* 7.1.3 Initialization Parameters (SCTP_INITMSG)
4614  *
4615  * Applications can specify protocol parameters for the default association
4616  * initialization.  The option name argument to setsockopt() and getsockopt()
4617  * is SCTP_INITMSG.
4618  *
4619  * Setting initialization parameters is effective only on an unconnected
4620  * socket (for UDP-style sockets only future associations are effected
4621  * by the change).  With TCP-style sockets, this option is inherited by
4622  * sockets derived from a listener socket.
4623  */
4624 static int sctp_getsockopt_initmsg(struct sock *sk, int len, char __user *optval, int __user *optlen)
4625 {
4626         if (len < sizeof(struct sctp_initmsg))
4627                 return -EINVAL;
4628         len = sizeof(struct sctp_initmsg);
4629         if (put_user(len, optlen))
4630                 return -EFAULT;
4631         if (copy_to_user(optval, &sctp_sk(sk)->initmsg, len))
4632                 return -EFAULT;
4633         return 0;
4634 }
4635 
4636 
4637 static int sctp_getsockopt_peer_addrs(struct sock *sk, int len,
4638                                       char __user *optval, int __user *optlen)
4639 {
4640         struct sctp_association *asoc;
4641         int cnt = 0;
4642         struct sctp_getaddrs getaddrs;
4643         struct sctp_transport *from;
4644         void __user *to;
4645         union sctp_addr temp;
4646         struct sctp_sock *sp = sctp_sk(sk);
4647         int addrlen;
4648         size_t space_left;
4649         int bytes_copied;
4650 
4651         if (len < sizeof(struct sctp_getaddrs))
4652                 return -EINVAL;
4653 
4654         if (copy_from_user(&getaddrs, optval, sizeof(struct sctp_getaddrs)))
4655                 return -EFAULT;
4656 
4657         /* For UDP-style sockets, id specifies the association to query.  */
4658         asoc = sctp_id2assoc(sk, getaddrs.assoc_id);
4659         if (!asoc)
4660                 return -EINVAL;
4661 
4662         to = optval + offsetof(struct sctp_getaddrs,addrs);
4663         space_left = len - offsetof(struct sctp_getaddrs,addrs);
4664 
4665         list_for_each_entry(from, &asoc->peer.transport_addr_list,
4666                                 transports) {
4667                 memcpy(&temp, &from->ipaddr, sizeof(temp));
4668                 sctp_get_pf_specific(sk->sk_family)->addr_v4map(sp, &temp);
4669                 addrlen = sctp_get_af_specific(temp.sa.sa_family)->sockaddr_len;
4670                 if (space_left < addrlen)
4671                         return -ENOMEM;
4672                 if (copy_to_user(to, &temp, addrlen))
4673                         return -EFAULT;
4674                 to += addrlen;
4675                 cnt++;
4676                 space_left -= addrlen;
4677         }
4678 
4679         if (put_user(cnt, &((struct sctp_getaddrs __user *)optval)->addr_num))
4680                 return -EFAULT;
4681         bytes_copied = ((char __user *)to) - optval;
4682         if (put_user(bytes_copied, optlen))
4683                 return -EFAULT;
4684 
4685         return 0;
4686 }
4687 
4688 static int sctp_copy_laddrs(struct sock *sk, __u16 port, void *to,
4689                             size_t space_left, int *bytes_copied)
4690 {
4691         struct sctp_sockaddr_entry *addr;
4692         union sctp_addr temp;
4693         int cnt = 0;
4694         int addrlen;
4695         struct net *net = sock_net(sk);
4696 
4697         rcu_read_lock();
4698         list_for_each_entry_rcu(addr, &net->sctp.local_addr_list, list) {
4699                 if (!addr->valid)
4700                         continue;
4701 
4702                 if ((PF_INET == sk->sk_family) &&
4703                     (AF_INET6 == addr->a.sa.sa_family))
4704                         continue;
4705                 if ((PF_INET6 == sk->sk_family) &&
4706                     inet_v6_ipv6only(sk) &&
4707                     (AF_INET == addr->a.sa.sa_family))
4708                         continue;
4709                 memcpy(&temp, &addr->a, sizeof(temp));
4710                 if (!temp.v4.sin_port)
4711                         temp.v4.sin_port = htons(port);
4712 
4713                 sctp_get_pf_specific(sk->sk_family)->addr_v4map(sctp_sk(sk),
4714                                                                 &temp);
4715                 addrlen = sctp_get_af_specific(temp.sa.sa_family)->sockaddr_len;
4716                 if (space_left < addrlen) {
4717                         cnt =  -ENOMEM;
4718                         break;
4719                 }
4720                 memcpy(to, &temp, addrlen);
4721 
4722                 to += addrlen;
4723                 cnt ++;
4724                 space_left -= addrlen;
4725                 *bytes_copied += addrlen;
4726         }
4727         rcu_read_unlock();
4728 
4729         return cnt;
4730 }
4731 
4732 
4733 static int sctp_getsockopt_local_addrs(struct sock *sk, int len,
4734                                        char __user *optval, int __user *optlen)
4735 {
4736         struct sctp_bind_addr *bp;
4737         struct sctp_association *asoc;
4738         int cnt = 0;
4739         struct sctp_getaddrs getaddrs;
4740         struct sctp_sockaddr_entry *addr;
4741         void __user *to;
4742         union sctp_addr temp;
4743         struct sctp_sock *sp = sctp_sk(sk);
4744         int addrlen;
4745         int err = 0;
4746         size_t space_left;
4747         int bytes_copied = 0;
4748         void *addrs;
4749         void *buf;
4750 
4751         if (len < sizeof(struct sctp_getaddrs))
4752                 return -EINVAL;
4753 
4754         if (copy_from_user(&getaddrs, optval, sizeof(struct sctp_getaddrs)))
4755                 return -EFAULT;
4756 
4757         /*
4758          *  For UDP-style sockets, id specifies the association to query.
4759          *  If the id field is set to the value '' then the locally bound
4760          *  addresses are returned without regard to any particular
4761          *  association.
4762          */
4763         if (0 == getaddrs.assoc_id) {
4764                 bp = &sctp_sk(sk)->ep->base.bind_addr;
4765         } else {
4766                 asoc = sctp_id2assoc(sk, getaddrs.assoc_id);
4767                 if (!asoc)
4768                         return -EINVAL;
4769                 bp = &asoc->base.bind_addr;
4770         }
4771 
4772         to = optval + offsetof(struct sctp_getaddrs,addrs);
4773         space_left = len - offsetof(struct sctp_getaddrs,addrs);
4774 
4775         addrs = kmalloc(space_left, GFP_KERNEL);
4776         if (!addrs)
4777                 return -ENOMEM;
4778 
4779         /* If the endpoint is bound to 0.0.0.0 or ::0, get the valid
4780          * addresses from the global local address list.
4781          */
4782         if (sctp_list_single_entry(&bp->address_list)) {
4783                 addr = list_entry(bp->address_list.next,
4784                                   struct sctp_sockaddr_entry, list);
4785                 if (sctp_is_any(sk, &addr->a)) {
4786                         cnt = sctp_copy_laddrs(sk, bp->port, addrs,
4787                                                 space_left, &bytes_copied);
4788                         if (cnt < 0) {
4789                                 err = cnt;
4790                                 goto out;
4791                         }
4792                         goto copy_getaddrs;
4793                 }
4794         }
4795 
4796         buf = addrs;
4797         /* Protection on the bound address list is not needed since
4798          * in the socket option context we hold a socket lock and
4799          * thus the bound address list can't change.
4800          */
4801         list_for_each_entry(addr, &bp->address_list, list) {
4802                 memcpy(&temp, &addr->a, sizeof(temp));
4803                 sctp_get_pf_specific(sk->sk_family)->addr_v4map(sp, &temp);
4804                 addrlen = sctp_get_af_specific(temp.sa.sa_family)->sockaddr_len;
4805                 if (space_left < addrlen) {
4806                         err =  -ENOMEM; /*fixme: right error?*/
4807                         goto out;
4808                 }
4809                 memcpy(buf, &temp, addrlen);
4810                 buf += addrlen;
4811                 bytes_copied += addrlen;
4812                 cnt ++;
4813                 space_left -= addrlen;
4814         }
4815 
4816 copy_getaddrs:
4817         if (copy_to_user(to, addrs, bytes_copied)) {
4818                 err = -EFAULT;
4819                 goto out;
4820         }
4821         if (put_user(cnt, &((struct sctp_getaddrs __user *)optval)->addr_num)) {
4822                 err = -EFAULT;
4823                 goto out;
4824         }
4825         if (put_user(bytes_copied, optlen))
4826                 err = -EFAULT;
4827 out:
4828         kfree(addrs);
4829         return err;
4830 }
4831 
4832 /* 7.1.10 Set Primary Address (SCTP_PRIMARY_ADDR)
4833  *
4834  * Requests that the local SCTP stack use the enclosed peer address as
4835  * the association primary.  The enclosed address must be one of the
4836  * association peer's addresses.
4837  */
4838 static int sctp_getsockopt_primary_addr(struct sock *sk, int len,
4839                                         char __user *optval, int __user *optlen)
4840 {
4841         struct sctp_prim prim;
4842         struct sctp_association *asoc;
4843         struct sctp_sock *sp = sctp_sk(sk);
4844 
4845         if (len < sizeof(struct sctp_prim))
4846                 return -EINVAL;
4847 
4848         len = sizeof(struct sctp_prim);
4849 
4850         if (copy_from_user(&prim, optval, len))
4851                 return -EFAULT;
4852 
4853         asoc = sctp_id2assoc(sk, prim.ssp_assoc_id);
4854         if (!asoc)
4855                 return -EINVAL;
4856 
4857         if (!asoc->peer.primary_path)
4858                 return -ENOTCONN;
4859 
4860         memcpy(&prim.ssp_addr, &asoc->peer.primary_path->ipaddr,
4861                 asoc->peer.primary_path->af_specific->sockaddr_len);
4862 
4863         sctp_get_pf_specific(sk->sk_family)->addr_v4map(sp,
4864                         (union sctp_addr *)&prim.ssp_addr);
4865 
4866         if (put_user(len, optlen))
4867                 return -EFAULT;
4868         if (copy_to_user(optval, &prim, len))
4869                 return -EFAULT;
4870 
4871         return 0;
4872 }
4873 
4874 /*
4875  * 7.1.11  Set Adaptation Layer Indicator (SCTP_ADAPTATION_LAYER)
4876  *
4877  * Requests that the local endpoint set the specified Adaptation Layer
4878  * Indication parameter for all future INIT and INIT-ACK exchanges.
4879  */
4880 static int sctp_getsockopt_adaptation_layer(struct sock *sk, int len,
4881                                   char __user *optval, int __user *optlen)
4882 {
4883         struct sctp_setadaptation adaptation;
4884 
4885         if (len < sizeof(struct sctp_setadaptation))
4886                 return -EINVAL;
4887 
4888         len = sizeof(struct sctp_setadaptation);
4889 
4890         adaptation.ssb_adaptation_ind = sctp_sk(sk)->adaptation_ind;
4891 
4892         if (put_user(len, optlen))
4893                 return -EFAULT;
4894         if (copy_to_user(optval, &adaptation, len))
4895                 return -EFAULT;
4896 
4897         return 0;
4898 }
4899 
4900 /*
4901  *
4902  * 7.1.14 Set default send parameters (SCTP_DEFAULT_SEND_PARAM)
4903  *
4904  *   Applications that wish to use the sendto() system call may wish to
4905  *   specify a default set of parameters that would normally be supplied
4906  *   through the inclusion of ancillary data.  This socket option allows
4907  *   such an application to set the default sctp_sndrcvinfo structure.
4908 
4909 
4910  *   The application that wishes to use this socket option simply passes
4911  *   in to this call the sctp_sndrcvinfo structure defined in Section
4912  *   5.2.2) The input parameters accepted by this call include
4913  *   sinfo_stream, sinfo_flags, sinfo_ppid, sinfo_context,
4914  *   sinfo_timetolive.  The user must provide the sinfo_assoc_id field in
4915  *   to this call if the caller is using the UDP model.
4916  *
4917  *   For getsockopt, it get the default sctp_sndrcvinfo structure.
4918  */
4919 static int sctp_getsockopt_default_send_param(struct sock *sk,
4920                                         int len, char __user *optval,
4921                                         int __user *optlen)
4922 {
4923         struct sctp_sndrcvinfo info;
4924         struct sctp_association *asoc;
4925         struct sctp_sock *sp = sctp_sk(sk);
4926 
4927         if (len < sizeof(struct sctp_sndrcvinfo))
4928                 return -EINVAL;
4929 
4930         len = sizeof(struct sctp_sndrcvinfo);
4931 
4932         if (copy_from_user(&info, optval, len))
4933                 return -EFAULT;
4934 
4935         asoc = sctp_id2assoc(sk, info.sinfo_assoc_id);
4936         if (!asoc && info.sinfo_assoc_id && sctp_style(sk, UDP))
4937                 return -EINVAL;
4938 
4939         if (asoc) {
4940                 info.sinfo_stream = asoc->default_stream;
4941                 info.sinfo_flags = asoc->default_flags;
4942                 info.sinfo_ppid = asoc->default_ppid;
4943                 info.sinfo_context = asoc->default_context;
4944                 info.sinfo_timetolive = asoc->default_timetolive;
4945         } else {
4946                 info.sinfo_stream = sp->default_stream;
4947                 info.sinfo_flags = sp->default_flags;
4948                 info.sinfo_ppid = sp->default_ppid;
4949                 info.sinfo_context = sp->default_context;
4950                 info.sinfo_timetolive = sp->default_timetolive;
4951         }
4952 
4953         if (put_user(len, optlen))
4954                 return -EFAULT;
4955         if (copy_to_user(optval, &info, len))
4956                 return -EFAULT;
4957 
4958         return 0;
4959 }
4960 
4961 /*
4962  *
4963  * 7.1.5 SCTP_NODELAY
4964  *
4965  * Turn on/off any Nagle-like algorithm.  This means that packets are
4966  * generally sent as soon as possible and no unnecessary delays are
4967  * introduced, at the cost of more packets in the network.  Expects an
4968  * integer boolean flag.
4969  */
4970 
4971 static int sctp_getsockopt_nodelay(struct sock *sk, int len,
4972                                    char __user *optval, int __user *optlen)
4973 {
4974         int val;
4975 
4976         if (len < sizeof(int))
4977                 return -EINVAL;
4978 
4979         len = sizeof(int);
4980         val = (sctp_sk(sk)->nodelay == 1);
4981         if (put_user(len, optlen))
4982                 return -EFAULT;
4983         if (copy_to_user(optval, &val, len))
4984                 return -EFAULT;
4985         return 0;
4986 }
4987 
4988 /*
4989  *
4990  * 7.1.1 SCTP_RTOINFO
4991  *
4992  * The protocol parameters used to initialize and bound retransmission
4993  * timeout (RTO) are tunable. sctp_rtoinfo structure is used to access
4994  * and modify these parameters.
4995  * All parameters are time values, in milliseconds.  A value of 0, when
4996  * modifying the parameters, indicates that the current value should not
4997  * be changed.
4998  *
4999  */
5000 static int sctp_getsockopt_rtoinfo(struct sock *sk, int len,
5001                                 char __user *optval,
5002                                 int __user *optlen) {
5003         struct sctp_rtoinfo rtoinfo;
5004         struct sctp_association *asoc;
5005 
5006         if (len < sizeof (struct sctp_rtoinfo))
5007                 return -EINVAL;
5008 
5009         len = sizeof(struct sctp_rtoinfo);
5010 
5011         if (copy_from_user(&rtoinfo, optval, len))
5012                 return -EFAULT;
5013 
5014         asoc = sctp_id2assoc(sk, rtoinfo.srto_assoc_id);
5015 
5016         if (!asoc && rtoinfo.srto_assoc_id && sctp_style(sk, UDP))
5017                 return -EINVAL;
5018 
5019         /* Values corresponding to the specific association. */
5020         if (asoc) {
5021                 rtoinfo.srto_initial = jiffies_to_msecs(asoc->rto_initial);
5022                 rtoinfo.srto_max = jiffies_to_msecs(asoc->rto_max);
5023                 rtoinfo.srto_min = jiffies_to_msecs(asoc->rto_min);
5024         } else {
5025                 /* Values corresponding to the endpoint. */
5026                 struct sctp_sock *sp = sctp_sk(sk);
5027 
5028                 rtoinfo.srto_initial = sp->rtoinfo.srto_initial;
5029                 rtoinfo.srto_max = sp->rtoinfo.srto_max;
5030                 rtoinfo.srto_min = sp->rtoinfo.srto_min;
5031         }
5032 
5033         if (put_user(len, optlen))
5034                 return -EFAULT;
5035 
5036         if (copy_to_user(optval, &rtoinfo, len))
5037                 return -EFAULT;
5038 
5039         return 0;
5040 }
5041 
5042 /*
5043  *
5044  * 7.1.2 SCTP_ASSOCINFO
5045  *
5046  * This option is used to tune the maximum retransmission attempts
5047  * of the association.
5048  * Returns an error if the new association retransmission value is
5049  * greater than the sum of the retransmission value  of the peer.
5050  * See [SCTP] for more information.
5051  *
5052  */
5053 static int sctp_getsockopt_associnfo(struct sock *sk, int len,
5054                                      char __user *optval,
5055                                      int __user *optlen)
5056 {
5057 
5058         struct sctp_assocparams assocparams;
5059         struct sctp_association *asoc;
5060         struct list_head *pos;
5061         int cnt = 0;
5062 
5063         if (len < sizeof (struct sctp_assocparams))
5064                 return -EINVAL;
5065 
5066         len = sizeof(struct sctp_assocparams);
5067 
5068         if (copy_from_user(&assocparams, optval, len))
5069                 return -EFAULT;
5070 
5071         asoc = sctp_id2assoc(sk, assocparams.sasoc_assoc_id);
5072 
5073         if (!asoc && assocparams.sasoc_assoc_id && sctp_style(sk, UDP))
5074                 return -EINVAL;
5075 
5076         /* Values correspoinding to the specific association */
5077         if (asoc) {
5078                 assocparams.sasoc_asocmaxrxt = asoc->max_retrans;
5079                 assocparams.sasoc_peer_rwnd = asoc->peer.rwnd;
5080                 assocparams.sasoc_local_rwnd = asoc->a_rwnd;
5081                 assocparams.sasoc_cookie_life = ktime_to_ms(asoc->cookie_life);
5082 
5083                 list_for_each(pos, &asoc->peer.transport_addr_list) {
5084                         cnt ++;
5085                 }
5086 
5087                 assocparams.sasoc_number_peer_destinations = cnt;
5088         } else {
5089                 /* Values corresponding to the endpoint */
5090                 struct sctp_sock *sp = sctp_sk(sk);
5091 
5092                 assocparams.sasoc_asocmaxrxt = sp->assocparams.sasoc_asocmaxrxt;
5093                 assocparams.sasoc_peer_rwnd = sp->assocparams.sasoc_peer_rwnd;
5094                 assocparams.sasoc_local_rwnd = sp->assocparams.sasoc_local_rwnd;
5095                 assocparams.sasoc_cookie_life =
5096                                         sp->assocparams.sasoc_cookie_life;
5097                 assocparams.sasoc_number_peer_destinations =
5098                                         sp->assocparams.
5099                                         sasoc_number_peer_destinations;
5100         }
5101 
5102         if (put_user(len, optlen))
5103                 return -EFAULT;
5104 
5105         if (copy_to_user(optval, &assocparams, len))
5106                 return -EFAULT;
5107 
5108         return 0;
5109 }
5110 
5111 /*
5112  * 7.1.16 Set/clear IPv4 mapped addresses (SCTP_I_WANT_MAPPED_V4_ADDR)
5113  *
5114  * This socket option is a boolean flag which turns on or off mapped V4
5115  * addresses.  If this option is turned on and the socket is type
5116  * PF_INET6, then IPv4 addresses will be mapped to V6 representation.
5117  * If this option is turned off, then no mapping will be done of V4
5118  * addresses and a user will receive both PF_INET6 and PF_INET type
5119  * addresses on the socket.
5120  */
5121 static int sctp_getsockopt_mappedv4(struct sock *sk, int len,
5122                                     char __user *optval, int __user *optlen)
5123 {
5124         int val;
5125         struct sctp_sock *sp = sctp_sk(sk);
5126 
5127         if (len < sizeof(int))
5128                 return -EINVAL;
5129 
5130         len = sizeof(int);
5131         val = sp->v4mapped;
5132         if (put_user(len, optlen))
5133                 return -EFAULT;
5134         if (copy_to_user(optval, &val, len))
5135                 return -EFAULT;
5136 
5137         return 0;
5138 }
5139 
5140 /*
5141  * 7.1.29.  Set or Get the default context (SCTP_CONTEXT)
5142  * (chapter and verse is quoted at sctp_setsockopt_context())
5143  */
5144 static int sctp_getsockopt_context(struct sock *sk, int len,
5145                                    char __user *optval, int __user *optlen)
5146 {
5147         struct sctp_assoc_value params;
5148         struct sctp_sock *sp;
5149         struct sctp_association *asoc;
5150 
5151         if (len < sizeof(struct sctp_assoc_value))
5152                 return -EINVAL;
5153 
5154         len = sizeof(struct sctp_assoc_value);
5155 
5156         if (copy_from_user(&params, optval, len))
5157                 return -EFAULT;
5158 
5159         sp = sctp_sk(sk);
5160 
5161         if (params.assoc_id != 0) {
5162                 asoc = sctp_id2assoc(sk, params.assoc_id);
5163                 if (!asoc)
5164                         return -EINVAL;
5165                 params.assoc_value = asoc->default_rcv_context;
5166         } else {
5167                 params.assoc_value = sp->default_rcv_context;
5168         }
5169 
5170         if (put_user(len, optlen))
5171                 return -EFAULT;
5172         if (copy_to_user(optval, &params, len))
5173                 return -EFAULT;
5174 
5175         return 0;
5176 }
5177 
5178 /*
5179  * 8.1.16.  Get or Set the Maximum Fragmentation Size (SCTP_MAXSEG)
5180  * This option will get or set the maximum size to put in any outgoing
5181  * SCTP DATA chunk.  If a message is larger than this size it will be
5182  * fragmented by SCTP into the specified size.  Note that the underlying
5183  * SCTP implementation may fragment into smaller sized chunks when the
5184  * PMTU of the underlying association is smaller than the value set by
5185  * the user.  The default value for this option is '' which indicates
5186  * the user is NOT limiting fragmentation and only the PMTU will effect
5187  * SCTP's choice of DATA chunk size.  Note also that values set larger
5188  * than the maximum size of an IP datagram will effectively let SCTP
5189  * control fragmentation (i.e. the same as setting this option to 0).
5190  *
5191  * The following structure is used to access and modify this parameter:
5192  *
5193  * struct sctp_assoc_value {
5194  *   sctp_assoc_t assoc_id;
5195  *   uint32_t assoc_value;
5196  * };
5197  *
5198  * assoc_id:  This parameter is ignored for one-to-one style sockets.
5199  *    For one-to-many style sockets this parameter indicates which
5200  *    association the user is performing an action upon.  Note that if
5201  *    this field's value is zero then the endpoints default value is
5202  *    changed (effecting future associations only).
5203  * assoc_value:  This parameter specifies the maximum size in bytes.
5204  */
5205 static int sctp_getsockopt_maxseg(struct sock *sk, int len,
5206                                   char __user *optval, int __user *optlen)
5207 {
5208         struct sctp_assoc_value params;
5209         struct sctp_association *asoc;
5210 
5211         if (len == sizeof(int)) {
5212                 pr_warn("Use of int in maxseg socket option deprecated\n");
5213                 pr_warn("Use struct sctp_assoc_value instead\n");
5214                 params.assoc_id = 0;
5215         } else if (len >= sizeof(struct sctp_assoc_value)) {
5216                 len = sizeof(struct sctp_assoc_value);
5217                 if (copy_from_user(&params, optval, sizeof(params)))
5218                         return -EFAULT;
5219         } else
5220                 return -EINVAL;
5221 
5222         asoc = sctp_id2assoc(sk, params.assoc_id);
5223         if (!asoc && params.assoc_id && sctp_style(sk, UDP))
5224                 return -EINVAL;
5225 
5226         if (asoc)
5227                 params.assoc_value = asoc->frag_point;
5228         else
5229                 params.assoc_value = sctp_sk(sk)->user_frag;
5230 
5231         if (put_user(len, optlen))
5232                 return -EFAULT;
5233         if (len == sizeof(int)) {
5234                 if (copy_to_user(optval, &params.assoc_value, len))
5235                         return -EFAULT;
5236         } else {
5237                 if (copy_to_user(optval, &params, len))
5238                         return -EFAULT;
5239         }
5240 
5241         return 0;
5242 }
5243 
5244 /*
5245  * 7.1.24.  Get or set fragmented interleave (SCTP_FRAGMENT_INTERLEAVE)
5246  * (chapter and verse is quoted at sctp_setsockopt_fragment_interleave())
5247  */
5248 static int sctp_getsockopt_fragment_interleave(struct sock *sk, int len,
5249                                                char __user *optval, int __user *optlen)
5250 {
5251         int val;
5252 
5253         if (len < sizeof(int))
5254                 return -EINVAL;
5255 
5256         len = sizeof(int);
5257 
5258         val = sctp_sk(sk)->frag_interleave;
5259         if (put_user(len, optlen))
5260                 return -EFAULT;
5261         if (copy_to_user(optval, &val, len))
5262                 return -EFAULT;
5263 
5264         return 0;
5265 }
5266 
5267 /*
5268  * 7.1.25.  Set or Get the sctp partial delivery point
5269  * (chapter and verse is quoted at sctp_setsockopt_partial_delivery_point())
5270  */
5271 static int sctp_getsockopt_partial_delivery_point(struct sock *sk, int len,
5272                                                   char __user *optval,
5273                                                   int __user *optlen)
5274 {
5275         u32 val;
5276 
5277         if (len < sizeof(u32))
5278                 return -EINVAL;
5279 
5280         len = sizeof(u32);
5281 
5282         val = sctp_sk(sk)->pd_point;
5283         if (put_user(len, optlen))
5284                 return -EFAULT;
5285         if (copy_to_user(optval, &val, len))
5286                 return -EFAULT;
5287 
5288         return 0;
5289 }
5290 
5291 /*
5292  * 7.1.28.  Set or Get the maximum burst (SCTP_MAX_BURST)
5293  * (chapter and verse is quoted at sctp_setsockopt_maxburst())
5294  */
5295 static int sctp_getsockopt_maxburst(struct sock *sk, int len,
5296                                     char __user *optval,
5297                                     int __user *optlen)
5298 {
5299         struct sctp_assoc_value params;
5300         struct sctp_sock *sp;
5301         struct sctp_association *asoc;
5302 
5303         if (len == sizeof(int)) {
5304                 pr_warn("Use of int in max_burst socket option deprecated\n");
5305                 pr_warn("Use struct sctp_assoc_value instead\n");
5306                 params.assoc_id = 0;
5307         } else if (len >= sizeof(struct sctp_assoc_value)) {
5308                 len = sizeof(struct sctp_assoc_value);
5309                 if (copy_from_user(&params, optval, len))
5310                         return -EFAULT;
5311         } else
5312                 return -EINVAL;
5313 
5314         sp = sctp_sk(sk);
5315 
5316         if (params.assoc_id != 0) {
5317                 asoc = sctp_id2assoc(sk, params.assoc_id);
5318                 if (!asoc)
5319                         return -EINVAL;
5320                 params.assoc_value = asoc->max_burst;
5321         } else
5322                 params.assoc_value = sp->max_burst;
5323 
5324         if (len == sizeof(int)) {
5325                 if (copy_to_user(optval, &params.assoc_value, len))
5326                         return -EFAULT;
5327         } else {
5328                 if (copy_to_user(optval, &params, len))
5329                         return -EFAULT;
5330         }
5331 
5332         return 0;
5333 
5334 }
5335 
5336 static int sctp_getsockopt_hmac_ident(struct sock *sk, int len,
5337                                     char __user *optval, int __user *optlen)
5338 {
5339         struct net *net = sock_net(sk);
5340         struct sctp_hmacalgo  __user *p = (void __user *)optval;
5341         struct sctp_hmac_algo_param *hmacs;
5342         __u16 data_len = 0;
5343         u32 num_idents;
5344 
5345         if (!net->sctp.auth_enable)
5346                 return -EACCES;
5347 
5348         hmacs = sctp_sk(sk)->ep->auth_hmacs_list;
5349         data_len = ntohs(hmacs->param_hdr.length) - sizeof(sctp_paramhdr_t);
5350 
5351         if (len < sizeof(struct sctp_hmacalgo) + data_len)
5352                 return -EINVAL;
5353 
5354         len = sizeof(struct sctp_hmacalgo) + data_len;
5355         num_idents = data_len / sizeof(u16);
5356 
5357         if (put_user(len, optlen))
5358                 return -EFAULT;
5359         if (put_user(num_idents, &p->shmac_num_idents))
5360                 return -EFAULT;
5361         if (copy_to_user(p->shmac_idents, hmacs->hmac_ids, data_len))
5362                 return -EFAULT;
5363         return 0;
5364 }
5365 
5366 static int sctp_getsockopt_active_key(struct sock *sk, int len,
5367                                     char __user *optval, int __user *optlen)
5368 {
5369         struct net *net = sock_net(sk);
5370         struct sctp_authkeyid val;
5371         struct sctp_association *asoc;
5372 
5373         if (!net->sctp.auth_enable)
5374                 return -EACCES;
5375 
5376         if (len < sizeof(struct sctp_authkeyid))
5377                 return -EINVAL;
5378         if (copy_from_user(&val, optval, sizeof(struct sctp_authkeyid)))
5379                 return -EFAULT;
5380 
5381         asoc = sctp_id2assoc(sk, val.scact_assoc_id);
5382         if (!asoc && val.scact_assoc_id && sctp_style(sk, UDP))
5383                 return -EINVAL;
5384 
5385         if (asoc)
5386                 val.scact_keynumber = asoc->active_key_id;
5387         else
5388                 val.scact_keynumber = sctp_sk(sk)->ep->active_key_id;
5389 
5390         len = sizeof(struct sctp_authkeyid);
5391         if (put_user(len, optlen))
5392                 return -EFAULT;
5393         if (copy_to_user(optval, &val, len))
5394                 return -EFAULT;
5395 
5396         return 0;
5397 }
5398 
5399 static int sctp_getsockopt_peer_auth_chunks(struct sock *sk, int len,
5400                                     char __user *optval, int __user *optlen)
5401 {
5402         struct net *net = sock_net(sk);
5403         struct sctp_authchunks __user *p = (void __user *)optval;
5404         struct sctp_authchunks val;
5405         struct sctp_association *asoc;
5406         struct sctp_chunks_param *ch;
5407         u32    num_chunks = 0;
5408         char __user *to;
5409 
5410         if (!net->sctp.auth_enable)
5411                 return -EACCES;
5412 
5413         if (len < sizeof(struct sctp_authchunks))
5414                 return -EINVAL;
5415 
5416         if (copy_from_user(&val, optval, sizeof(struct sctp_authchunks)))
5417                 return -EFAULT;
5418 
5419         to = p->gauth_chunks;
5420         asoc = sctp_id2assoc(sk, val.gauth_assoc_id);
5421         if (!asoc)
5422                 return -EINVAL;
5423 
5424         ch = asoc->peer.peer_chunks;
5425         if (!ch)
5426                 goto num;
5427 
5428         /* See if the user provided enough room for all the data */
5429         num_chunks = ntohs(ch->param_hdr.length) - sizeof(sctp_paramhdr_t);
5430         if (len < num_chunks)
5431                 return -EINVAL;
5432 
5433         if (copy_to_user(to, ch->chunks, num_chunks))
5434                 return -EFAULT;
5435 num:
5436         len = sizeof(struct sctp_authchunks) + num_chunks;
5437         if (put_user(len, optlen)) return -EFAULT;
5438         if (put_user(num_chunks, &p->gauth_number_of_chunks))
5439                 return -EFAULT;
5440         return 0;
5441 }
5442 
5443 static int sctp_getsockopt_local_auth_chunks(struct sock *sk, int len,
5444                                     char __user *optval, int __user *optlen)
5445 {
5446         struct net *net = sock_net(sk);
5447         struct sctp_authchunks __user *p = (void __user *)optval;
5448         struct sctp_authchunks val;
5449         struct sctp_association *asoc;
5450         struct sctp_chunks_param *ch;
5451         u32    num_chunks = 0;
5452         char __user *to;
5453 
5454         if (!net->sctp.auth_enable)
5455                 return -EACCES;
5456 
5457         if (len < sizeof(struct sctp_authchunks))
5458                 return -EINVAL;
5459 
5460         if (copy_from_user(&val, optval, sizeof(struct sctp_authchunks)))
5461                 return -EFAULT;
5462 
5463         to = p->gauth_chunks;
5464         asoc = sctp_id2assoc(sk, val.gauth_assoc_id);
5465         if (!asoc && val.gauth_assoc_id && sctp_style(sk, UDP))
5466                 return -EINVAL;
5467 
5468         if (asoc)
5469                 ch = (struct sctp_chunks_param*)asoc->c.auth_chunks;
5470         else
5471                 ch = sctp_sk(sk)->ep->auth_chunk_list;
5472 
5473         if (!ch)
5474                 goto num;
5475 
5476         num_chunks = ntohs(ch->param_hdr.length) - sizeof(sctp_paramhdr_t);
5477         if (len < sizeof(struct sctp_authchunks) + num_chunks)
5478                 return -EINVAL;
5479 
5480         if (copy_to_user(to, ch->chunks, num_chunks))
5481                 return -EFAULT;
5482 num:
5483         len = sizeof(struct sctp_authchunks) + num_chunks;
5484         if (put_user(len, optlen))
5485                 return -EFAULT;
5486         if (put_user(num_chunks, &p->gauth_number_of_chunks))
5487                 return -EFAULT;
5488 
5489         return 0;
5490 }
5491 
5492 /*
5493  * 8.2.5.  Get the Current Number of Associations (SCTP_GET_ASSOC_NUMBER)
5494  * This option gets the current number of associations that are attached
5495  * to a one-to-many style socket.  The option value is an uint32_t.
5496  */
5497 static int sctp_getsockopt_assoc_number(struct sock *sk, int len,
5498                                     char __user *optval, int __user *optlen)
5499 {
5500         struct sctp_sock *sp = sctp_sk(sk);
5501         struct sctp_association *asoc;
5502         u32 val = 0;
5503 
5504         if (sctp_style(sk, TCP))
5505                 return -EOPNOTSUPP;
5506 
5507         if (len < sizeof(u32))
5508                 return -EINVAL;
5509 
5510         len = sizeof(u32);
5511 
5512         list_for_each_entry(asoc, &(sp->ep->asocs), asocs) {
5513                 val++;
5514         }
5515 
5516         if (put_user(len, optlen))
5517                 return -EFAULT;
5518         if (copy_to_user(optval, &val, len))
5519                 return -EFAULT;
5520 
5521         return 0;
5522 }
5523 
5524 /*
5525  * 8.1.23 SCTP_AUTO_ASCONF
5526  * See the corresponding setsockopt entry as description
5527  */
5528 static int sctp_getsockopt_auto_asconf(struct sock *sk, int len,
5529                                    char __user *optval, int __user *optlen)
5530 {
5531         int val = 0;
5532 
5533         if (len < sizeof(int))
5534                 return -EINVAL;
5535 
5536         len = sizeof(int);
5537         if (sctp_sk(sk)->do_auto_asconf && sctp_is_ep_boundall(sk))
5538                 val = 1;
5539         if (put_user(len, optlen))
5540                 return -EFAULT;
5541         if (copy_to_user(optval, &val, len))
5542                 return -EFAULT;
5543         return 0;
5544 }
5545 
5546 /*
5547  * 8.2.6. Get the Current Identifiers of Associations
5548  *        (SCTP_GET_ASSOC_ID_LIST)
5549  *
5550  * This option gets the current list of SCTP association identifiers of
5551  * the SCTP associations handled by a one-to-many style socket.
5552  */
5553 static int sctp_getsockopt_assoc_ids(struct sock *sk, int len,
5554                                     char __user *optval, int __user *optlen)
5555 {
5556         struct sctp_sock *sp = sctp_sk(sk);
5557         struct sctp_association *asoc;
5558         struct sctp_assoc_ids *ids;
5559         u32 num = 0;
5560 
5561         if (sctp_style(sk, TCP))
5562                 return -EOPNOTSUPP;
5563 
5564         if (len < sizeof(struct sctp_assoc_ids))
5565                 return -EINVAL;
5566 
5567         list_for_each_entry(asoc, &(sp->ep->asocs), asocs) {
5568                 num++;
5569         }
5570 
5571         if (len < sizeof(struct sctp_assoc_ids) + sizeof(sctp_assoc_t) * num)
5572                 return -EINVAL;
5573 
5574         len = sizeof(struct sctp_assoc_ids) + sizeof(sctp_assoc_t) * num;
5575 
5576         ids = kmalloc(len, GFP_KERNEL);
5577         if (unlikely(!ids))
5578                 return -ENOMEM;
5579 
5580         ids->gaids_number_of_ids = num;
5581         num = 0;
5582         list_for_each_entry(asoc, &(sp->ep->asocs), asocs) {
5583                 ids->gaids_assoc_id[num++] = asoc->assoc_id;
5584         }
5585 
5586         if (put_user(len, optlen) || copy_to_user(optval, ids, len)) {
5587                 kfree(ids);
5588                 return -EFAULT;
5589         }
5590 
5591         kfree(ids);
5592         return 0;
5593 }
5594 
5595 /*
5596  * SCTP_PEER_ADDR_THLDS
5597  *
5598  * This option allows us to fetch the partially failed threshold for one or all
5599  * transports in an association.  See Section 6.1 of:
5600  * http://www.ietf.org/id/draft-nishida-tsvwg-sctp-failover-05.txt
5601  */
5602 static int sctp_getsockopt_paddr_thresholds(struct sock *sk,
5603                                             char __user *optval,
5604                                             int len,
5605                                             int __user *optlen)
5606 {
5607         struct sctp_paddrthlds val;
5608         struct sctp_transport *trans;
5609         struct sctp_association *asoc;
5610 
5611         if (len < sizeof(struct sctp_paddrthlds))
5612                 return -EINVAL;
5613         len = sizeof(struct sctp_paddrthlds);
5614         if (copy_from_user(&val, (struct sctp_paddrthlds __user *)optval, len))
5615                 return -EFAULT;
5616 
5617         if (sctp_is_any(sk, (const union sctp_addr *)&val.spt_address)) {
5618                 asoc = sctp_id2assoc(sk, val.spt_assoc_id);
5619                 if (!asoc)
5620                         return -ENOENT;
5621 
5622                 val.spt_pathpfthld = asoc->pf_retrans;
5623                 val.spt_pathmaxrxt = asoc->pathmaxrxt;
5624         } else {
5625                 trans = sctp_addr_id2transport(sk, &val.spt_address,
5626                                                val.spt_assoc_id);
5627                 if (!trans)
5628                         return -ENOENT;
5629 
5630                 val.spt_pathmaxrxt = trans->pathmaxrxt;
5631                 val.spt_pathpfthld = trans->pf_retrans;
5632         }
5633 
5634         if (put_user(len, optlen) || copy_to_user(optval, &val, len))
5635                 return -EFAULT;
5636 
5637         return 0;
5638 }
5639 
5640 /*
5641  * SCTP_GET_ASSOC_STATS
5642  *
5643  * This option retrieves local per endpoint statistics. It is modeled
5644  * after OpenSolaris' implementation
5645  */
5646 static int sctp_getsockopt_assoc_stats(struct sock *sk, int len,
5647                                        char __user *optval,
5648                                        int __user *optlen)
5649 {
5650         struct sctp_assoc_stats sas;
5651         struct sctp_association *asoc = NULL;
5652 
5653         /* User must provide at least the assoc id */
5654         if (len < sizeof(sctp_assoc_t))
5655                 return -EINVAL;
5656 
5657         /* Allow the struct to grow and fill in as much as possible */
5658         len = min_t(size_t, len, sizeof(sas));
5659 
5660         if (copy_from_user(&sas, optval, len))
5661                 return -EFAULT;
5662 
5663         asoc = sctp_id2assoc(sk, sas.sas_assoc_id);
5664         if (!asoc)
5665                 return -EINVAL;
5666 
5667         sas.sas_rtxchunks = asoc->stats.rtxchunks;
5668         sas.sas_gapcnt = asoc->stats.gapcnt;
5669         sas.sas_outofseqtsns = asoc->stats.outofseqtsns;
5670         sas.sas_osacks = asoc->stats.osacks;
5671         sas.sas_isacks = asoc->stats.isacks;
5672         sas.sas_octrlchunks = asoc->stats.octrlchunks;
5673         sas.sas_ictrlchunks = asoc->stats.ictrlchunks;
5674         sas.sas_oodchunks = asoc->stats.oodchunks;
5675         sas.sas_iodchunks = asoc->stats.iodchunks;
5676         sas.sas_ouodchunks = asoc->stats.ouodchunks;
5677         sas.sas_iuodchunks = asoc->stats.iuodchunks;
5678         sas.sas_idupchunks = asoc->stats.idupchunks;
5679         sas.sas_opackets = asoc->stats.opackets;
5680         sas.sas_ipackets = asoc->stats.ipackets;
5681 
5682         /* New high max rto observed, will return 0 if not a single
5683          * RTO update took place. obs_rto_ipaddr will be bogus
5684          * in such a case
5685          */
5686         sas.sas_maxrto = asoc->stats.max_obs_rto;
5687         memcpy(&sas.sas_obs_rto_ipaddr, &asoc->stats.obs_rto_ipaddr,
5688                 sizeof(struct sockaddr_storage));
5689 
5690         /* Mark beginning of a new observation period */
5691         asoc->stats.max_obs_rto = asoc->rto_min;
5692 
5693         if (put_user(len, optlen))
5694                 return -EFAULT;
5695 
5696         pr_debug("%s: len:%d, assoc_id:%d\n", __func__, len, sas.sas_assoc_id);
5697 
5698         if (copy_to_user(optval, &sas, len))
5699                 return -EFAULT;
5700 
5701         return 0;
5702 }
5703 
5704 static int sctp_getsockopt(struct sock *sk, int level, int optname,
5705                            char __user *optval, int __user *optlen)
5706 {
5707         int retval = 0;
5708         int len;
5709 
5710         pr_debug("%s: sk:%p, optname:%d\n", __func__, sk, optname);
5711 
5712         /* I can hardly begin to describe how wrong this is.  This is
5713          * so broken as to be worse than useless.  The API draft
5714          * REALLY is NOT helpful here...  I am not convinced that the
5715          * semantics of getsockopt() with a level OTHER THAN SOL_SCTP
5716          * are at all well-founded.
5717          */
5718         if (level != SOL_SCTP) {
5719                 struct sctp_af *af = sctp_sk(sk)->pf->af;
5720 
5721                 retval = af->getsockopt(sk, level, optname, optval, optlen);
5722                 return retval;
5723         }
5724 
5725         if (get_user(len, optlen))
5726                 return -EFAULT;
5727 
5728         sctp_lock_sock(sk);
5729 
5730         switch (optname) {
5731         case SCTP_STATUS:
5732                 retval = sctp_getsockopt_sctp_status(sk, len, optval, optlen);
5733                 break;
5734         case SCTP_DISABLE_FRAGMENTS:
5735                 retval = sctp_getsockopt_disable_fragments(sk, len, optval,
5736                                                            optlen);
5737                 break;
5738         case SCTP_EVENTS:
5739                 retval = sctp_getsockopt_events(sk, len, optval, optlen);
5740                 break;
5741         case SCTP_AUTOCLOSE:
5742                 retval = sctp_getsockopt_autoclose(sk, len, optval, optlen);
5743                 break;
5744         case SCTP_SOCKOPT_PEELOFF:
5745                 retval = sctp_getsockopt_peeloff(sk, len, optval, optlen);
5746                 break;
5747         case SCTP_PEER_ADDR_PARAMS:
5748                 retval = sctp_getsockopt_peer_addr_params(sk, len, optval,
5749                                                           optlen);
5750                 break;
5751         case SCTP_DELAYED_SACK:
5752                 retval = sctp_getsockopt_delayed_ack(sk, len, optval,
5753                                                           optlen);
5754                 break;
5755         case SCTP_INITMSG:
5756                 retval = sctp_getsockopt_initmsg(sk, len, optval, optlen);
5757                 break;
5758         case SCTP_GET_PEER_ADDRS:
5759                 retval = sctp_getsockopt_peer_addrs(sk, len, optval,
5760                                                     optlen);
5761                 break;
5762         case SCTP_GET_LOCAL_ADDRS:
5763                 retval = sctp_getsockopt_local_addrs(sk, len, optval,
5764                                                      optlen);
5765                 break;
5766         case SCTP_SOCKOPT_CONNECTX3:
5767                 retval = sctp_getsockopt_connectx3(sk, len, optval, optlen);
5768                 break;
5769         case SCTP_DEFAULT_SEND_PARAM:
5770                 retval = sctp_getsockopt_default_send_param(sk, len,
5771                                                             optval, optlen);
5772                 break;
5773         case SCTP_PRIMARY_ADDR:
5774                 retval = sctp_getsockopt_primary_addr(sk, len, optval, optlen);
5775                 break;
5776         case SCTP_NODELAY:
5777                 retval = sctp_getsockopt_nodelay(sk, len, optval, optlen);
5778                 break;
5779         case SCTP_RTOINFO:
5780                 retval = sctp_getsockopt_rtoinfo(sk, len, optval, optlen);
5781                 break;
5782         case SCTP_ASSOCINFO:
5783                 retval = sctp_getsockopt_associnfo(sk, len, optval, optlen);
5784                 break;
5785         case SCTP_I_WANT_MAPPED_V4_ADDR:
5786                 retval = sctp_getsockopt_mappedv4(sk, len, optval, optlen);
5787                 break;
5788         case SCTP_MAXSEG:
5789                 retval = sctp_getsockopt_maxseg(sk, len, optval, optlen);
5790                 break;
5791         case SCTP_GET_PEER_ADDR_INFO:
5792                 retval = sctp_getsockopt_peer_addr_info(sk, len, optval,
5793                                                         optlen);
5794                 break;
5795         case SCTP_ADAPTATION_LAYER:
5796                 retval = sctp_getsockopt_adaptation_layer(sk, len, optval,
5797                                                         optlen);
5798                 break;
5799         case SCTP_CONTEXT:
5800                 retval = sctp_getsockopt_context(sk, len, optval, optlen);
5801                 break;
5802         case SCTP_FRAGMENT_INTERLEAVE:
5803                 retval = sctp_getsockopt_fragment_interleave(sk, len, optval,
5804                                                              optlen);
5805                 break;
5806         case SCTP_PARTIAL_DELIVERY_POINT:
5807                 retval = sctp_getsockopt_partial_delivery_point(sk, len, optval,
5808                                                                 optlen);
5809                 break;
5810         case SCTP_MAX_BURST:
5811                 retval = sctp_getsockopt_maxburst(sk, len, optval, optlen);
5812                 break;
5813         case SCTP_AUTH_KEY:
5814         case SCTP_AUTH_CHUNK:
5815         case SCTP_AUTH_DELETE_KEY:
5816                 retval = -EOPNOTSUPP;
5817                 break;
5818         case SCTP_HMAC_IDENT:
5819                 retval = sctp_getsockopt_hmac_ident(sk, len, optval, optlen);
5820                 break;
5821         case SCTP_AUTH_ACTIVE_KEY:
5822                 retval = sctp_getsockopt_active_key(sk, len, optval, optlen);
5823                 break;
5824         case SCTP_PEER_AUTH_CHUNKS:
5825                 retval = sctp_getsockopt_peer_auth_chunks(sk, len, optval,
5826                                                         optlen);
5827                 break;
5828         case SCTP_LOCAL_AUTH_CHUNKS:
5829                 retval = sctp_getsockopt_local_auth_chunks(sk, len, optval,
5830                                                         optlen);
5831                 break;
5832         case SCTP_GET_ASSOC_NUMBER:
5833                 retval = sctp_getsockopt_assoc_number(sk, len, optval, optlen);
5834                 break;
5835         case SCTP_GET_ASSOC_ID_LIST:
5836                 retval = sctp_getsockopt_assoc_ids(sk, len, optval, optlen);
5837                 break;
5838         case SCTP_AUTO_ASCONF:
5839                 retval = sctp_getsockopt_auto_asconf(sk, len, optval, optlen);
5840                 break;
5841         case SCTP_PEER_ADDR_THLDS:
5842                 retval = sctp_getsockopt_paddr_thresholds(sk, optval, len, optlen);
5843                 break;
5844         case SCTP_GET_ASSOC_STATS:
5845                 retval = sctp_getsockopt_assoc_stats(sk, len, optval, optlen);
5846                 break;
5847         default:
5848                 retval = -ENOPROTOOPT;
5849                 break;
5850         }
5851 
5852         sctp_release_sock(sk);
5853         return retval;
5854 }
5855 
5856 static void sctp_hash(struct sock *sk)
5857 {
5858         /* STUB */
5859 }
5860 
5861 static void sctp_unhash(struct sock *sk)
5862 {
5863         /* STUB */
5864 }
5865 
5866 /* Check if port is acceptable.  Possibly find first available port.
5867  *
5868  * The port hash table (contained in the 'global' SCTP protocol storage
5869  * returned by struct sctp_protocol *sctp_get_protocol()). The hash
5870  * table is an array of 4096 lists (sctp_bind_hashbucket). Each
5871  * list (the list number is the port number hashed out, so as you
5872  * would expect from a hash function, all the ports in a given list have
5873  * such a number that hashes out to the same list number; you were
5874  * expecting that, right?); so each list has a set of ports, with a
5875  * link to the socket (struct sock) that uses it, the port number and
5876  * a fastreuse flag (FIXME: NPI ipg).
5877  */
5878 static struct sctp_bind_bucket *sctp_bucket_create(
5879         struct sctp_bind_hashbucket *head, struct net *, unsigned short snum);
5880 
5881 static long sctp_get_port_local(struct sock *sk, union sctp_addr *addr)
5882 {
5883         struct sctp_bind_hashbucket *head; /* hash list */
5884         struct sctp_bind_bucket *pp;
5885         unsigned short snum;
5886         int ret;
5887 
5888         snum = ntohs(addr->v4.sin_port);
5889 
5890         pr_debug("%s: begins, snum:%d\n", __func__, snum);
5891 
5892         sctp_local_bh_disable();
5893 
5894         if (snum == 0) {
5895                 /* Search for an available port. */
5896                 int low, high, remaining, index;
5897                 unsigned int rover;
5898 
5899                 inet_get_local_port_range(&low, &high);
5900                 remaining = (high - low) + 1;
5901                 rover = net_random() % remaining + low;
5902 
5903                 do {
5904                         rover++;
5905                         if ((rover < low) || (rover > high))
5906                                 rover = low;
5907                         if (inet_is_reserved_local_port(rover))
5908                                 continue;
5909                         index = sctp_phashfn(sock_net(sk), rover);
5910                         head = &sctp_port_hashtable[index];
5911                         sctp_spin_lock(&head->lock);
5912                         sctp_for_each_hentry(pp, &head->chain)
5913                                 if ((pp->port == rover) &&
5914                                     net_eq(sock_net(sk), pp->net))
5915                                         goto next;
5916                         break;
5917                 next:
5918                         sctp_spin_unlock(&head->lock);
5919                 } while (--remaining > 0);
5920 
5921                 /* Exhausted local port range during search? */
5922                 ret = 1;
5923                 if (remaining <= 0)
5924                         goto fail;
5925 
5926                 /* OK, here is the one we will use.  HEAD (the port
5927                  * hash table list entry) is non-NULL and we hold it's
5928                  * mutex.
5929                  */
5930                 snum = rover;
5931         } else {
5932                 /* We are given an specific port number; we verify
5933                  * that it is not being used. If it is used, we will
5934                  * exahust the search in the hash list corresponding
5935                  * to the port number (snum) - we detect that with the
5936                  * port iterator, pp being NULL.
5937                  */
5938                 head = &sctp_port_hashtable[sctp_phashfn(sock_net(sk), snum)];
5939                 sctp_spin_lock(&head->lock);
5940                 sctp_for_each_hentry(pp, &head->chain) {
5941                         if ((pp->port == snum) && net_eq(pp->net, sock_net(sk)))
5942                                 goto pp_found;
5943                 }
5944         }
5945         pp = NULL;
5946         goto pp_not_found;
5947 pp_found:
5948         if (!hlist_empty(&pp->owner)) {
5949                 /* We had a port hash table hit - there is an
5950                  * available port (pp != NULL) and it is being
5951                  * used by other socket (pp->owner not empty); that other
5952                  * socket is going to be sk2.
5953                  */
5954                 int reuse = sk->sk_reuse;
5955                 struct sock *sk2;
5956 
5957                 pr_debug("%s: found a possible match\n", __func__);
5958 
5959                 if (pp->fastreuse && sk->sk_reuse &&
5960                         sk->sk_state != SCTP_SS_LISTENING)
5961                         goto success;
5962 
5963                 /* Run through the list of sockets bound to the port
5964                  * (pp->port) [via the pointers bind_next and
5965                  * bind_pprev in the struct sock *sk2 (pp->sk)]. On each one,
5966                  * we get the endpoint they describe and run through
5967                  * the endpoint's list of IP (v4 or v6) addresses,
5968                  * comparing each of the addresses with the address of
5969                  * the socket sk. If we find a match, then that means
5970                  * that this port/socket (sk) combination are already
5971                  * in an endpoint.
5972                  */
5973                 sk_for_each_bound(sk2, &pp->owner) {
5974                         struct sctp_endpoint *ep2;
5975                         ep2 = sctp_sk(sk2)->ep;
5976 
5977                         if (sk == sk2 ||
5978                             (reuse && sk2->sk_reuse &&
5979                              sk2->sk_state != SCTP_SS_LISTENING))
5980                                 continue;
5981 
5982                         if (sctp_bind_addr_conflict(&ep2->base.bind_addr, addr,
5983                                                  sctp_sk(sk2), sctp_sk(sk))) {
5984                                 ret = (long)sk2;
5985                                 goto fail_unlock;
5986                         }
5987                 }
5988 
5989                 pr_debug("%s: found a match\n", __func__);
5990         }
5991 pp_not_found:
5992         /* If there was a hash table miss, create a new port.  */
5993         ret = 1;
5994         if (!pp && !(pp = sctp_bucket_create(head, sock_net(sk), snum)))
5995                 goto fail_unlock;
5996 
5997         /* In either case (hit or miss), make sure fastreuse is 1 only
5998          * if sk->sk_reuse is too (that is, if the caller requested
5999          * SO_REUSEADDR on this socket -sk-).
6000          */
6001         if (hlist_empty(&pp->owner)) {
6002                 if (sk->sk_reuse && sk->sk_state != SCTP_SS_LISTENING)
6003                         pp->fastreuse = 1;
6004                 else
6005                         pp->fastreuse = 0;
6006         } else if (pp->fastreuse &&
6007                 (!sk->sk_reuse || sk->sk_state == SCTP_SS_LISTENING))
6008                 pp->fastreuse = 0;
6009 
6010         /* We are set, so fill up all the data in the hash table
6011          * entry, tie the socket list information with the rest of the
6012          * sockets FIXME: Blurry, NPI (ipg).
6013          */
6014 success:
6015         if (!sctp_sk(sk)->bind_hash) {
6016                 inet_sk(sk)->inet_num = snum;
6017                 sk_add_bind_node(sk, &pp->owner);
6018                 sctp_sk(sk)->bind_hash = pp;
6019         }
6020         ret = 0;
6021 
6022 fail_unlock:
6023         sctp_spin_unlock(&head->lock);
6024 
6025 fail:
6026         sctp_local_bh_enable();
6027         return ret;
6028 }
6029 
6030 /* Assign a 'snum' port to the socket.  If snum == 0, an ephemeral
6031  * port is requested.
6032  */
6033 static int sctp_get_port(struct sock *sk, unsigned short snum)
6034 {
6035         union sctp_addr addr;
6036         struct sctp_af *af = sctp_sk(sk)->pf->af;
6037 
6038         /* Set up a dummy address struct from the sk. */
6039         af->from_sk(&addr, sk);
6040         addr.v4.sin_port = htons(snum);
6041 
6042         /* Note: sk->sk_num gets filled in if ephemeral port request. */
6043         return !!sctp_get_port_local(sk, &addr);
6044 }
6045 
6046 /*
6047  *  Move a socket to LISTENING state.
6048  */
6049 static int sctp_listen_start(struct sock *sk, int backlog)
6050 {
6051         struct sctp_sock *sp = sctp_sk(sk);
6052         struct sctp_endpoint *ep = sp->ep;
6053         struct crypto_hash *tfm = NULL;
6054         char alg[32];
6055 
6056         /* Allocate HMAC for generating cookie. */
6057         if (!sp->hmac && sp->sctp_hmac_alg) {
6058                 sprintf(alg, "hmac(%s)", sp->sctp_hmac_alg);
6059                 tfm = crypto_alloc_hash(alg, 0, CRYPTO_ALG_ASYNC);
6060                 if (IS_ERR(tfm)) {
6061                         net_info_ratelimited("failed to load transform for %s: %ld\n",
6062                                              sp->sctp_hmac_alg, PTR_ERR(tfm));
6063                         return -ENOSYS;
6064                 }
6065                 sctp_sk(sk)->hmac = tfm;
6066         }
6067 
6068         /*
6069          * If a bind() or sctp_bindx() is not called prior to a listen()
6070          * call that allows new associations to be accepted, the system
6071          * picks an ephemeral port and will choose an address set equivalent
6072          * to binding with a wildcard address.
6073          *
6074          * This is not currently spelled out in the SCTP sockets
6075          * extensions draft, but follows the practice as seen in TCP
6076          * sockets.
6077          *
6078          */
6079         sk->sk_state = SCTP_SS_LISTENING;
6080         if (!ep->base.bind_addr.port) {
6081                 if (sctp_autobind(sk))
6082                         return -EAGAIN;
6083         } else {
6084                 if (sctp_get_port(sk, inet_sk(sk)->inet_num)) {
6085                         sk->sk_state = SCTP_SS_CLOSED;
6086                         return -EADDRINUSE;
6087                 }
6088         }
6089 
6090         sk->sk_max_ack_backlog = backlog;
6091         sctp_hash_endpoint(ep);
6092         return 0;
6093 }
6094 
6095 /*
6096  * 4.1.3 / 5.1.3 listen()
6097  *
6098  *   By default, new associations are not accepted for UDP style sockets.
6099  *   An application uses listen() to mark a socket as being able to
6100  *   accept new associations.
6101  *
6102  *   On TCP style sockets, applications use listen() to ready the SCTP
6103  *   endpoint for accepting inbound associations.
6104  *
6105  *   On both types of endpoints a backlog of '' disables listening.
6106  *
6107  *  Move a socket to LISTENING state.
6108  */
6109 int sctp_inet_listen(struct socket *sock, int backlog)
6110 {
6111         struct sock *sk = sock->sk;
6112         struct sctp_endpoint *ep = sctp_sk(sk)->ep;
6113         int err = -EINVAL;
6114 
6115         if (unlikely(backlog < 0))
6116                 return err;
6117 
6118         sctp_lock_sock(sk);
6119 
6120         /* Peeled-off sockets are not allowed to listen().  */
6121         if (sctp_style(sk, UDP_HIGH_BANDWIDTH))
6122                 goto out;
6123 
6124         if (sock->state != SS_UNCONNECTED)
6125                 goto out;
6126 
6127         /* If backlog is zero, disable listening. */
6128         if (!backlog) {
6129                 if (sctp_sstate(sk, CLOSED))
6130                         goto out;
6131 
6132                 err = 0;
6133                 sctp_unhash_endpoint(ep);
6134                 sk->sk_state = SCTP_SS_CLOSED;
6135                 if (sk->sk_reuse)
6136                         sctp_sk(sk)->bind_hash->fastreuse = 1;
6137                 goto out;
6138         }
6139 
6140         /* If we are already listening, just update the backlog */
6141         if (sctp_sstate(sk, LISTENING))
6142                 sk->sk_max_ack_backlog = backlog;
6143         else {
6144                 err = sctp_listen_start(sk, backlog);
6145                 if (err)
6146                         goto out;
6147         }
6148 
6149         err = 0;
6150 out:
6151         sctp_release_sock(sk);
6152         return err;
6153 }
6154 
6155 /*
6156  * This function is done by modeling the current datagram_poll() and the
6157  * tcp_poll().  Note that, based on these implementations, we don't
6158  * lock the socket in this function, even though it seems that,
6159  * ideally, locking or some other mechanisms can be used to ensure
6160  * the integrity of the counters (sndbuf and wmem_alloc) used
6161  * in this place.  We assume that we don't need locks either until proven
6162  * otherwise.
6163  *
6164  * Another thing to note is that we include the Async I/O support
6165  * here, again, by modeling the current TCP/UDP code.  We don't have
6166  * a good way to test with it yet.
6167  */
6168 unsigned int sctp_poll(struct file *file, struct socket *sock, poll_table *wait)
6169 {
6170         struct sock *sk = sock->sk;
6171         struct sctp_sock *sp = sctp_sk(sk);
6172         unsigned int mask;
6173 
6174         poll_wait(file, sk_sleep(sk), wait);
6175 
6176         /* A TCP-style listening socket becomes readable when the accept queue
6177          * is not empty.
6178          */
6179         if (sctp_style(sk, TCP) && sctp_sstate(sk, LISTENING))
6180                 return (!list_empty(&sp->ep->asocs)) ?
6181                         (POLLIN | POLLRDNORM) : 0;
6182 
6183         mask = 0;
6184 
6185         /* Is there any exceptional events?  */
6186         if (sk->sk_err || !skb_queue_empty(&sk->sk_error_queue))
6187                 mask |= POLLERR |
6188                         (sock_flag(sk, SOCK_SELECT_ERR_QUEUE) ? POLLPRI : 0);
6189         if (sk->sk_shutdown & RCV_SHUTDOWN)
6190                 mask |= POLLRDHUP | POLLIN | POLLRDNORM;
6191         if (sk->sk_shutdown == SHUTDOWN_MASK)
6192                 mask |= POLLHUP;
6193 
6194         /* Is it readable?  Reconsider this code with TCP-style support.  */
6195         if (!skb_queue_empty(&sk->sk_receive_queue))
6196                 mask |= POLLIN | POLLRDNORM;
6197 
6198         /* The association is either gone or not ready.  */
6199         if (!sctp_style(sk, UDP) && sctp_sstate(sk, CLOSED))
6200                 return mask;
6201 
6202         /* Is it writable?  */
6203         if (sctp_writeable(sk)) {
6204                 mask |= POLLOUT | POLLWRNORM;
6205         } else {
6206                 set_bit(SOCK_ASYNC_NOSPACE, &sk->sk_socket->flags);
6207                 /*
6208                  * Since the socket is not locked, the buffer
6209                  * might be made available after the writeable check and
6210                  * before the bit is set.  This could cause a lost I/O
6211                  * signal.  tcp_poll() has a race breaker for this race
6212                  * condition.  Based on their implementation, we put
6213                  * in the following code to cover it as well.
6214                  */
6215                 if (sctp_writeable(sk))
6216                         mask |= POLLOUT | POLLWRNORM;
6217         }
6218         return mask;
6219 }
6220 
6221 /********************************************************************
6222  * 2nd Level Abstractions
6223  ********************************************************************/
6224 
6225 static struct sctp_bind_bucket *sctp_bucket_create(
6226         struct sctp_bind_hashbucket *head, struct net *net, unsigned short snum)
6227 {
6228         struct sctp_bind_bucket *pp;
6229 
6230         pp = kmem_cache_alloc(sctp_bucket_cachep, GFP_ATOMIC);
6231         if (pp) {
6232                 SCTP_DBG_OBJCNT_INC(bind_bucket);
6233                 pp->port = snum;
6234                 pp->fastreuse = 0;
6235                 INIT_HLIST_HEAD(&pp->owner);
6236                 pp->net = net;
6237                 hlist_add_head(&pp->node, &head->chain);
6238         }
6239         return pp;
6240 }
6241 
6242 /* Caller must hold hashbucket lock for this tb with local BH disabled */
6243 static void sctp_bucket_destroy(struct sctp_bind_bucket *pp)
6244 {
6245         if (pp && hlist_empty(&pp->owner)) {
6246                 __hlist_del(&pp->node);
6247                 kmem_cache_free(sctp_bucket_cachep, pp);
6248                 SCTP_DBG_OBJCNT_DEC(bind_bucket);
6249         }
6250 }
6251 
6252 /* Release this socket's reference to a local port.  */
6253 static inline void __sctp_put_port(struct sock *sk)
6254 {
6255         struct sctp_bind_hashbucket *head =
6256                 &sctp_port_hashtable[sctp_phashfn(sock_net(sk),
6257                                                   inet_sk(sk)->inet_num)];
6258         struct sctp_bind_bucket *pp;
6259 
6260         sctp_spin_lock(&head->lock);
6261         pp = sctp_sk(sk)->bind_hash;
6262         __sk_del_bind_node(sk);
6263         sctp_sk(sk)->bind_hash = NULL;
6264         inet_sk(sk)->inet_num = 0;
6265         sctp_bucket_destroy(pp);
6266         sctp_spin_unlock(&head->lock);
6267 }
6268 
6269 void sctp_put_port(struct sock *sk)
6270 {
6271         sctp_local_bh_disable();
6272         __sctp_put_port(sk);
6273         sctp_local_bh_enable();
6274 }
6275 
6276 /*
6277  * The system picks an ephemeral port and choose an address set equivalent
6278  * to binding with a wildcard address.
6279  * One of those addresses will be the primary address for the association.
6280  * This automatically enables the multihoming capability of SCTP.
6281  */
6282 static int sctp_autobind(struct sock *sk)
6283 {
6284         union sctp_addr autoaddr;
6285         struct sctp_af *af;
6286         __be16 port;
6287 
6288         /* Initialize a local sockaddr structure to INADDR_ANY. */
6289         af = sctp_sk(sk)->pf->af;
6290 
6291         port = htons(inet_sk(sk)->inet_num);
6292         af->inaddr_any(&autoaddr, port);
6293 
6294         return sctp_do_bind(sk, &autoaddr, af->sockaddr_len);
6295 }
6296 
6297 /* Parse out IPPROTO_SCTP CMSG headers.  Perform only minimal validation.
6298  *
6299  * From RFC 2292
6300  * 4.2 The cmsghdr Structure *
6301  *
6302  * When ancillary data is sent or received, any number of ancillary data
6303  * objects can be specified by the msg_control and msg_controllen members of
6304  * the msghdr structure, because each object is preceded by
6305  * a cmsghdr structure defining the object's length (the cmsg_len member).
6306  * Historically Berkeley-derived implementations have passed only one object
6307  * at a time, but this API allows multiple objects to be
6308  * passed in a single call to sendmsg() or recvmsg(). The following example
6309  * shows two ancillary data objects in a control buffer.
6310  *
6311  *   |<--------------------------- msg_controllen -------------------------->|
6312  *   |                                                                       |
6313  *
6314  *   |<----- ancillary data object ----->|<----- ancillary data object ----->|
6315  *
6316  *   |<---------- CMSG_SPACE() --------->|<---------- CMSG_SPACE() --------->|
6317  *   |                                   |                                   |
6318  *
6319  *   |<---------- cmsg_len ---------->|  |<--------- cmsg_len ----------->|  |
6320  *
6321  *   |<--------- CMSG_LEN() --------->|  |<-------- CMSG_LEN() ---------->|  |
6322  *   |                                |  |                                |  |
6323  *
6324  *   +-----+-----+-----+--+-----------+--+-----+-----+-----+--+-----------+--+
6325  *   |cmsg_|cmsg_|cmsg_|XX|           |XX|cmsg_|cmsg_|cmsg_|XX|           |XX|
6326  *
6327  *   |len  |level|type |XX|cmsg_data[]|XX|len  |level|type |XX|cmsg_data[]|XX|
6328  *
6329  *   +-----+-----+-----+--+-----------+--+-----+-----+-----+--+-----------+--+
6330  *    ^
6331  *    |
6332  *
6333  * msg_control
6334  * points here
6335  */
6336 static int sctp_msghdr_parse(const struct msghdr *msg, sctp_cmsgs_t *cmsgs)
6337 {
6338         struct cmsghdr *cmsg;
6339         struct msghdr *my_msg = (struct msghdr *)msg;
6340 
6341         for (cmsg = CMSG_FIRSTHDR(msg);
6342              cmsg != NULL;
6343              cmsg = CMSG_NXTHDR(my_msg, cmsg)) {
6344                 if (!CMSG_OK(my_msg, cmsg))
6345                         return -EINVAL;
6346 
6347                 /* Should we parse this header or ignore?  */
6348                 if (cmsg->cmsg_level != IPPROTO_SCTP)
6349                         continue;
6350 
6351                 /* Strictly check lengths following example in SCM code.  */
6352                 switch (cmsg->cmsg_type) {
6353                 case SCTP_INIT:
6354                         /* SCTP Socket API Extension
6355                          * 5.2.1 SCTP Initiation Structure (SCTP_INIT)
6356                          *
6357                          * This cmsghdr structure provides information for
6358                          * initializing new SCTP associations with sendmsg().
6359                          * The SCTP_INITMSG socket option uses this same data
6360                          * structure.  This structure is not used for
6361                          * recvmsg().
6362                          *
6363                          * cmsg_level    cmsg_type      cmsg_data[]
6364                          * ------------  ------------   ----------------------
6365                          * IPPROTO_SCTP  SCTP_INIT      struct sctp_initmsg
6366                          */
6367                         if (cmsg->cmsg_len !=
6368                             CMSG_LEN(sizeof(struct sctp_initmsg)))
6369                                 return -EINVAL;
6370                         cmsgs->init = (struct sctp_initmsg *)CMSG_DATA(cmsg);
6371                         break;
6372 
6373                 case SCTP_SNDRCV:
6374                         /* SCTP Socket API Extension
6375                          * 5.2.2 SCTP Header Information Structure(SCTP_SNDRCV)
6376                          *
6377                          * This cmsghdr structure specifies SCTP options for
6378                          * sendmsg() and describes SCTP header information
6379                          * about a received message through recvmsg().
6380                          *
6381                          * cmsg_level    cmsg_type      cmsg_data[]
6382                          * ------------  ------------   ----------------------
6383                          * IPPROTO_SCTP  SCTP_SNDRCV    struct sctp_sndrcvinfo
6384                          */
6385                         if (cmsg->cmsg_len !=
6386                             CMSG_LEN(sizeof(struct sctp_sndrcvinfo)))
6387                                 return -EINVAL;
6388 
6389                         cmsgs->info =
6390                                 (struct sctp_sndrcvinfo *)CMSG_DATA(cmsg);
6391 
6392                         /* Minimally, validate the sinfo_flags. */
6393                         if (cmsgs->info->sinfo_flags &
6394                             ~(SCTP_UNORDERED | SCTP_ADDR_OVER |
6395                               SCTP_ABORT | SCTP_EOF))
6396                                 return -EINVAL;
6397                         break;
6398 
6399                 default:
6400                         return -EINVAL;
6401                 }
6402         }
6403         return 0;
6404 }
6405 
6406 /*
6407  * Wait for a packet..
6408  * Note: This function is the same function as in core/datagram.c
6409  * with a few modifications to make lksctp work.
6410  */
6411 static int sctp_wait_for_packet(struct sock * sk, int *err, long *timeo_p)
6412 {
6413         int error;
6414         DEFINE_WAIT(wait);
6415 
6416         prepare_to_wait_exclusive(sk_sleep(sk), &wait, TASK_INTERRUPTIBLE);
6417 
6418         /* Socket errors? */
6419         error = sock_error(sk);
6420         if (error)
6421                 goto out;
6422 
6423         if (!skb_queue_empty(&sk->sk_receive_queue))
6424                 goto ready;
6425 
6426         /* Socket shut down?  */
6427         if (sk->sk_shutdown & RCV_SHUTDOWN)
6428                 goto out;
6429 
6430         /* Sequenced packets can come disconnected.  If so we report the
6431          * problem.
6432          */
6433         error = -ENOTCONN;
6434 
6435         /* Is there a good reason to think that we may receive some data?  */
6436         if (list_empty(&sctp_sk(sk)->ep->asocs) && !sctp_sstate(sk, LISTENING))
6437                 goto out;
6438 
6439         /* Handle signals.  */
6440         if (signal_pending(current))
6441                 goto interrupted;
6442 
6443         /* Let another process have a go.  Since we are going to sleep
6444          * anyway.  Note: This may cause odd behaviors if the message
6445          * does not fit in the user's buffer, but this seems to be the
6446          * only way to honor MSG_DONTWAIT realistically.
6447          */
6448         sctp_release_sock(sk);
6449         *timeo_p = schedule_timeout(*timeo_p);
6450         sctp_lock_sock(sk);
6451 
6452 ready:
6453         finish_wait(sk_sleep(sk), &wait);
6454         return 0;
6455 
6456 interrupted:
6457         error = sock_intr_errno(*timeo_p);
6458 
6459 out:
6460         finish_wait(sk_sleep(sk), &wait);
6461         *err = error;
6462         return error;
6463 }
6464 
6465 /* Receive a datagram.
6466  * Note: This is pretty much the same routine as in core/datagram.c
6467  * with a few changes to make lksctp work.
6468  */
6469 static struct sk_buff *sctp_skb_recv_datagram(struct sock *sk, int flags,
6470                                               int noblock, int *err)
6471 {
6472         int error;
6473         struct sk_buff *skb;
6474         long timeo;
6475 
6476         timeo = sock_rcvtimeo(sk, noblock);
6477 
6478         pr_debug("%s: timeo:%ld, max:%ld\n", __func__, timeo,
6479                  MAX_SCHEDULE_TIMEOUT);
6480 
6481         do {
6482                 /* Again only user level code calls this function,
6483                  * so nothing interrupt level
6484                  * will suddenly eat the receive_queue.
6485                  *
6486                  *  Look at current nfs client by the way...
6487                  *  However, this function was correct in any case. 8)
6488                  */
6489                 if (flags & MSG_PEEK) {
6490                         spin_lock_bh(&sk->sk_receive_queue.lock);
6491                         skb = skb_peek(&sk->sk_receive_queue);
6492                         if (skb)
6493                                 atomic_inc(&skb->users);
6494                         spin_unlock_bh(&sk->sk_receive_queue.lock);
6495                 } else {
6496                         skb = skb_dequeue(&sk->sk_receive_queue);
6497                 }
6498 
6499                 if (skb)
6500                         return skb;
6501 
6502                 /* Caller is allowed not to check sk->sk_err before calling. */
6503                 error = sock_error(sk);
6504                 if (error)
6505                         goto no_packet;
6506 
6507                 if (sk->sk_shutdown & RCV_SHUTDOWN)
6508                         break;
6509 
6510                 /* User doesn't want to wait.  */
6511                 error = -EAGAIN;
6512                 if (!timeo)
6513                         goto no_packet;
6514         } while (sctp_wait_for_packet(sk, err, &timeo) == 0);
6515 
6516         return NULL;
6517 
6518 no_packet:
6519         *err = error;
6520         return NULL;
6521 }
6522 
6523 /* If sndbuf has changed, wake up per association sndbuf waiters.  */
6524 static void __sctp_write_space(struct sctp_association *asoc)
6525 {
6526         struct sock *sk = asoc->base.sk;
6527         struct socket *sock = sk->sk_socket;
6528 
6529         if ((sctp_wspace(asoc) > 0) && sock) {
6530                 if (waitqueue_active(&asoc->wait))
6531                         wake_up_interruptible(&asoc->wait);
6532 
6533                 if (sctp_writeable(sk)) {
6534                         wait_queue_head_t *wq = sk_sleep(sk);
6535 
6536                         if (wq && waitqueue_active(wq))
6537                                 wake_up_interruptible(wq);
6538 
6539                         /* Note that we try to include the Async I/O support
6540                          * here by modeling from the current TCP/UDP code.
6541                          * We have not tested with it yet.
6542                          */
6543                         if (!(sk->sk_shutdown & SEND_SHUTDOWN))
6544                                 sock_wake_async(sock,
6545                                                 SOCK_WAKE_SPACE, POLL_OUT);
6546                 }
6547         }
6548 }
6549 
6550 /* Do accounting for the sndbuf space.
6551  * Decrement the used sndbuf space of the corresponding association by the
6552  * data size which was just transmitted(freed).
6553  */
6554 static void sctp_wfree(struct sk_buff *skb)
6555 {
6556         struct sctp_association *asoc;
6557         struct sctp_chunk *chunk;
6558         struct sock *sk;
6559 
6560         /* Get the saved chunk pointer.  */
6561         chunk = *((struct sctp_chunk **)(skb->cb));