Merge tag 'linux-kselftest-next-6.3-rc1' of git://git.kernel.org/pub/scm/linux/kernel...
[linux-2.6-block.git] / net / sctp / protocol.c
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /* SCTP kernel implementation
3  * (C) Copyright IBM Corp. 2001, 2004
4  * Copyright (c) 1999-2000 Cisco, Inc.
5  * Copyright (c) 1999-2001 Motorola, Inc.
6  * Copyright (c) 2001 Intel Corp.
7  * Copyright (c) 2001 Nokia, Inc.
8  * Copyright (c) 2001 La Monte H.P. Yarroll
9  *
10  * This file is part of the SCTP kernel implementation
11  *
12  * Initialization/cleanup for SCTP protocol support.
13  *
14  * Please send any bug reports or fixes you make to the
15  * email address(es):
16  *    lksctp developers <linux-sctp@vger.kernel.org>
17  *
18  * Written or modified by:
19  *    La Monte H.P. Yarroll <piggy@acm.org>
20  *    Karl Knutson <karl@athena.chicago.il.us>
21  *    Jon Grimm <jgrimm@us.ibm.com>
22  *    Sridhar Samudrala <sri@us.ibm.com>
23  *    Daisy Chang <daisyc@us.ibm.com>
24  *    Ardelle Fan <ardelle.fan@intel.com>
25  */
26
27 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
28
29 #include <linux/module.h>
30 #include <linux/init.h>
31 #include <linux/netdevice.h>
32 #include <linux/inetdevice.h>
33 #include <linux/seq_file.h>
34 #include <linux/memblock.h>
35 #include <linux/highmem.h>
36 #include <linux/slab.h>
37 #include <net/net_namespace.h>
38 #include <net/protocol.h>
39 #include <net/ip.h>
40 #include <net/ipv6.h>
41 #include <net/route.h>
42 #include <net/sctp/sctp.h>
43 #include <net/addrconf.h>
44 #include <net/inet_common.h>
45 #include <net/inet_ecn.h>
46 #include <net/udp_tunnel.h>
47
48 #define MAX_SCTP_PORT_HASH_ENTRIES (64 * 1024)
49
50 /* Global data structures. */
51 struct sctp_globals sctp_globals __read_mostly;
52
53 struct idr sctp_assocs_id;
54 DEFINE_SPINLOCK(sctp_assocs_id_lock);
55
56 static struct sctp_pf *sctp_pf_inet6_specific;
57 static struct sctp_pf *sctp_pf_inet_specific;
58 static struct sctp_af *sctp_af_v4_specific;
59 static struct sctp_af *sctp_af_v6_specific;
60
61 struct kmem_cache *sctp_chunk_cachep __read_mostly;
62 struct kmem_cache *sctp_bucket_cachep __read_mostly;
63
64 long sysctl_sctp_mem[3];
65 int sysctl_sctp_rmem[3];
66 int sysctl_sctp_wmem[3];
67
68 /* Private helper to extract ipv4 address and stash them in
69  * the protocol structure.
70  */
71 static void sctp_v4_copy_addrlist(struct list_head *addrlist,
72                                   struct net_device *dev)
73 {
74         struct in_device *in_dev;
75         struct in_ifaddr *ifa;
76         struct sctp_sockaddr_entry *addr;
77
78         rcu_read_lock();
79         if ((in_dev = __in_dev_get_rcu(dev)) == NULL) {
80                 rcu_read_unlock();
81                 return;
82         }
83
84         in_dev_for_each_ifa_rcu(ifa, in_dev) {
85                 /* Add the address to the local list.  */
86                 addr = kzalloc(sizeof(*addr), GFP_ATOMIC);
87                 if (addr) {
88                         addr->a.v4.sin_family = AF_INET;
89                         addr->a.v4.sin_addr.s_addr = ifa->ifa_local;
90                         addr->valid = 1;
91                         INIT_LIST_HEAD(&addr->list);
92                         list_add_tail(&addr->list, addrlist);
93                 }
94         }
95
96         rcu_read_unlock();
97 }
98
99 /* Extract our IP addresses from the system and stash them in the
100  * protocol structure.
101  */
102 static void sctp_get_local_addr_list(struct net *net)
103 {
104         struct net_device *dev;
105         struct list_head *pos;
106         struct sctp_af *af;
107
108         rcu_read_lock();
109         for_each_netdev_rcu(net, dev) {
110                 list_for_each(pos, &sctp_address_families) {
111                         af = list_entry(pos, struct sctp_af, list);
112                         af->copy_addrlist(&net->sctp.local_addr_list, dev);
113                 }
114         }
115         rcu_read_unlock();
116 }
117
118 /* Free the existing local addresses.  */
119 static void sctp_free_local_addr_list(struct net *net)
120 {
121         struct sctp_sockaddr_entry *addr;
122         struct list_head *pos, *temp;
123
124         list_for_each_safe(pos, temp, &net->sctp.local_addr_list) {
125                 addr = list_entry(pos, struct sctp_sockaddr_entry, list);
126                 list_del(pos);
127                 kfree(addr);
128         }
129 }
130
131 /* Copy the local addresses which are valid for 'scope' into 'bp'.  */
132 int sctp_copy_local_addr_list(struct net *net, struct sctp_bind_addr *bp,
133                               enum sctp_scope scope, gfp_t gfp, int copy_flags)
134 {
135         struct sctp_sockaddr_entry *addr;
136         union sctp_addr laddr;
137         int error = 0;
138
139         rcu_read_lock();
140         list_for_each_entry_rcu(addr, &net->sctp.local_addr_list, list) {
141                 if (!addr->valid)
142                         continue;
143                 if (!sctp_in_scope(net, &addr->a, scope))
144                         continue;
145
146                 /* Now that the address is in scope, check to see if
147                  * the address type is really supported by the local
148                  * sock as well as the remote peer.
149                  */
150                 if (addr->a.sa.sa_family == AF_INET &&
151                     (!(copy_flags & SCTP_ADDR4_ALLOWED) ||
152                      !(copy_flags & SCTP_ADDR4_PEERSUPP)))
153                         continue;
154                 if (addr->a.sa.sa_family == AF_INET6 &&
155                     (!(copy_flags & SCTP_ADDR6_ALLOWED) ||
156                      !(copy_flags & SCTP_ADDR6_PEERSUPP)))
157                         continue;
158
159                 laddr = addr->a;
160                 /* also works for setting ipv6 address port */
161                 laddr.v4.sin_port = htons(bp->port);
162                 if (sctp_bind_addr_state(bp, &laddr) != -1)
163                         continue;
164
165                 error = sctp_add_bind_addr(bp, &addr->a, sizeof(addr->a),
166                                            SCTP_ADDR_SRC, GFP_ATOMIC);
167                 if (error)
168                         break;
169         }
170
171         rcu_read_unlock();
172         return error;
173 }
174
175 /* Copy over any ip options */
176 static void sctp_v4_copy_ip_options(struct sock *sk, struct sock *newsk)
177 {
178         struct inet_sock *newinet, *inet = inet_sk(sk);
179         struct ip_options_rcu *inet_opt, *newopt = NULL;
180
181         newinet = inet_sk(newsk);
182
183         rcu_read_lock();
184         inet_opt = rcu_dereference(inet->inet_opt);
185         if (inet_opt) {
186                 newopt = sock_kmalloc(newsk, sizeof(*inet_opt) +
187                                       inet_opt->opt.optlen, GFP_ATOMIC);
188                 if (newopt)
189                         memcpy(newopt, inet_opt, sizeof(*inet_opt) +
190                                inet_opt->opt.optlen);
191                 else
192                         pr_err("%s: Failed to copy ip options\n", __func__);
193         }
194         RCU_INIT_POINTER(newinet->inet_opt, newopt);
195         rcu_read_unlock();
196 }
197
198 /* Account for the IP options */
199 static int sctp_v4_ip_options_len(struct sock *sk)
200 {
201         struct inet_sock *inet = inet_sk(sk);
202         struct ip_options_rcu *inet_opt;
203         int len = 0;
204
205         rcu_read_lock();
206         inet_opt = rcu_dereference(inet->inet_opt);
207         if (inet_opt)
208                 len = inet_opt->opt.optlen;
209
210         rcu_read_unlock();
211         return len;
212 }
213
214 /* Initialize a sctp_addr from in incoming skb.  */
215 static void sctp_v4_from_skb(union sctp_addr *addr, struct sk_buff *skb,
216                              int is_saddr)
217 {
218         /* Always called on head skb, so this is safe */
219         struct sctphdr *sh = sctp_hdr(skb);
220         struct sockaddr_in *sa = &addr->v4;
221
222         addr->v4.sin_family = AF_INET;
223
224         if (is_saddr) {
225                 sa->sin_port = sh->source;
226                 sa->sin_addr.s_addr = ip_hdr(skb)->saddr;
227         } else {
228                 sa->sin_port = sh->dest;
229                 sa->sin_addr.s_addr = ip_hdr(skb)->daddr;
230         }
231         memset(sa->sin_zero, 0, sizeof(sa->sin_zero));
232 }
233
234 /* Initialize an sctp_addr from a socket. */
235 static void sctp_v4_from_sk(union sctp_addr *addr, struct sock *sk)
236 {
237         addr->v4.sin_family = AF_INET;
238         addr->v4.sin_port = 0;
239         addr->v4.sin_addr.s_addr = inet_sk(sk)->inet_rcv_saddr;
240         memset(addr->v4.sin_zero, 0, sizeof(addr->v4.sin_zero));
241 }
242
243 /* Initialize sk->sk_rcv_saddr from sctp_addr. */
244 static void sctp_v4_to_sk_saddr(union sctp_addr *addr, struct sock *sk)
245 {
246         inet_sk(sk)->inet_rcv_saddr = addr->v4.sin_addr.s_addr;
247 }
248
249 /* Initialize sk->sk_daddr from sctp_addr. */
250 static void sctp_v4_to_sk_daddr(union sctp_addr *addr, struct sock *sk)
251 {
252         inet_sk(sk)->inet_daddr = addr->v4.sin_addr.s_addr;
253 }
254
255 /* Initialize a sctp_addr from an address parameter. */
256 static bool sctp_v4_from_addr_param(union sctp_addr *addr,
257                                     union sctp_addr_param *param,
258                                     __be16 port, int iif)
259 {
260         if (ntohs(param->v4.param_hdr.length) < sizeof(struct sctp_ipv4addr_param))
261                 return false;
262
263         addr->v4.sin_family = AF_INET;
264         addr->v4.sin_port = port;
265         addr->v4.sin_addr.s_addr = param->v4.addr.s_addr;
266         memset(addr->v4.sin_zero, 0, sizeof(addr->v4.sin_zero));
267
268         return true;
269 }
270
271 /* Initialize an address parameter from a sctp_addr and return the length
272  * of the address parameter.
273  */
274 static int sctp_v4_to_addr_param(const union sctp_addr *addr,
275                                  union sctp_addr_param *param)
276 {
277         int length = sizeof(struct sctp_ipv4addr_param);
278
279         param->v4.param_hdr.type = SCTP_PARAM_IPV4_ADDRESS;
280         param->v4.param_hdr.length = htons(length);
281         param->v4.addr.s_addr = addr->v4.sin_addr.s_addr;
282
283         return length;
284 }
285
286 /* Initialize a sctp_addr from a dst_entry. */
287 static void sctp_v4_dst_saddr(union sctp_addr *saddr, struct flowi4 *fl4,
288                               __be16 port)
289 {
290         saddr->v4.sin_family = AF_INET;
291         saddr->v4.sin_port = port;
292         saddr->v4.sin_addr.s_addr = fl4->saddr;
293         memset(saddr->v4.sin_zero, 0, sizeof(saddr->v4.sin_zero));
294 }
295
296 /* Compare two addresses exactly. */
297 static int sctp_v4_cmp_addr(const union sctp_addr *addr1,
298                             const union sctp_addr *addr2)
299 {
300         if (addr1->sa.sa_family != addr2->sa.sa_family)
301                 return 0;
302         if (addr1->v4.sin_port != addr2->v4.sin_port)
303                 return 0;
304         if (addr1->v4.sin_addr.s_addr != addr2->v4.sin_addr.s_addr)
305                 return 0;
306
307         return 1;
308 }
309
310 /* Initialize addr struct to INADDR_ANY. */
311 static void sctp_v4_inaddr_any(union sctp_addr *addr, __be16 port)
312 {
313         addr->v4.sin_family = AF_INET;
314         addr->v4.sin_addr.s_addr = htonl(INADDR_ANY);
315         addr->v4.sin_port = port;
316         memset(addr->v4.sin_zero, 0, sizeof(addr->v4.sin_zero));
317 }
318
319 /* Is this a wildcard address? */
320 static int sctp_v4_is_any(const union sctp_addr *addr)
321 {
322         return htonl(INADDR_ANY) == addr->v4.sin_addr.s_addr;
323 }
324
325 /* This function checks if the address is a valid address to be used for
326  * SCTP binding.
327  *
328  * Output:
329  * Return 0 - If the address is a non-unicast or an illegal address.
330  * Return 1 - If the address is a unicast.
331  */
332 static int sctp_v4_addr_valid(union sctp_addr *addr,
333                               struct sctp_sock *sp,
334                               const struct sk_buff *skb)
335 {
336         /* IPv4 addresses not allowed */
337         if (sp && ipv6_only_sock(sctp_opt2sk(sp)))
338                 return 0;
339
340         /* Is this a non-unicast address or a unusable SCTP address? */
341         if (IS_IPV4_UNUSABLE_ADDRESS(addr->v4.sin_addr.s_addr))
342                 return 0;
343
344         /* Is this a broadcast address? */
345         if (skb && skb_rtable(skb)->rt_flags & RTCF_BROADCAST)
346                 return 0;
347
348         return 1;
349 }
350
351 /* Should this be available for binding?   */
352 static int sctp_v4_available(union sctp_addr *addr, struct sctp_sock *sp)
353 {
354         struct sock *sk = &sp->inet.sk;
355         struct net *net = sock_net(sk);
356         int tb_id = RT_TABLE_LOCAL;
357         int ret;
358
359         tb_id = l3mdev_fib_table_by_index(net, sk->sk_bound_dev_if) ?: tb_id;
360         ret = inet_addr_type_table(net, addr->v4.sin_addr.s_addr, tb_id);
361         if (addr->v4.sin_addr.s_addr != htonl(INADDR_ANY) &&
362            ret != RTN_LOCAL &&
363            !sp->inet.freebind &&
364             !READ_ONCE(net->ipv4.sysctl_ip_nonlocal_bind))
365                 return 0;
366
367         if (ipv6_only_sock(sctp_opt2sk(sp)))
368                 return 0;
369
370         return 1;
371 }
372
373 /* Checking the loopback, private and other address scopes as defined in
374  * RFC 1918.   The IPv4 scoping is based on the draft for SCTP IPv4
375  * scoping <draft-stewart-tsvwg-sctp-ipv4-00.txt>.
376  *
377  * Level 0 - unusable SCTP addresses
378  * Level 1 - loopback address
379  * Level 2 - link-local addresses
380  * Level 3 - private addresses.
381  * Level 4 - global addresses
382  * For INIT and INIT-ACK address list, let L be the level of
383  * requested destination address, sender and receiver
384  * SHOULD include all of its addresses with level greater
385  * than or equal to L.
386  *
387  * IPv4 scoping can be controlled through sysctl option
388  * net.sctp.addr_scope_policy
389  */
390 static enum sctp_scope sctp_v4_scope(union sctp_addr *addr)
391 {
392         enum sctp_scope retval;
393
394         /* Check for unusable SCTP addresses. */
395         if (IS_IPV4_UNUSABLE_ADDRESS(addr->v4.sin_addr.s_addr)) {
396                 retval =  SCTP_SCOPE_UNUSABLE;
397         } else if (ipv4_is_loopback(addr->v4.sin_addr.s_addr)) {
398                 retval = SCTP_SCOPE_LOOPBACK;
399         } else if (ipv4_is_linklocal_169(addr->v4.sin_addr.s_addr)) {
400                 retval = SCTP_SCOPE_LINK;
401         } else if (ipv4_is_private_10(addr->v4.sin_addr.s_addr) ||
402                    ipv4_is_private_172(addr->v4.sin_addr.s_addr) ||
403                    ipv4_is_private_192(addr->v4.sin_addr.s_addr) ||
404                    ipv4_is_test_198(addr->v4.sin_addr.s_addr)) {
405                 retval = SCTP_SCOPE_PRIVATE;
406         } else {
407                 retval = SCTP_SCOPE_GLOBAL;
408         }
409
410         return retval;
411 }
412
413 /* Returns a valid dst cache entry for the given source and destination ip
414  * addresses. If an association is passed, trys to get a dst entry with a
415  * source address that matches an address in the bind address list.
416  */
417 static void sctp_v4_get_dst(struct sctp_transport *t, union sctp_addr *saddr,
418                                 struct flowi *fl, struct sock *sk)
419 {
420         struct sctp_association *asoc = t->asoc;
421         struct rtable *rt;
422         struct flowi _fl;
423         struct flowi4 *fl4 = &_fl.u.ip4;
424         struct sctp_bind_addr *bp;
425         struct sctp_sockaddr_entry *laddr;
426         struct dst_entry *dst = NULL;
427         union sctp_addr *daddr = &t->ipaddr;
428         union sctp_addr dst_saddr;
429         __u8 tos = inet_sk(sk)->tos;
430
431         if (t->dscp & SCTP_DSCP_SET_MASK)
432                 tos = t->dscp & SCTP_DSCP_VAL_MASK;
433         memset(&_fl, 0x0, sizeof(_fl));
434         fl4->daddr  = daddr->v4.sin_addr.s_addr;
435         fl4->fl4_dport = daddr->v4.sin_port;
436         fl4->flowi4_proto = IPPROTO_SCTP;
437         if (asoc) {
438                 fl4->flowi4_tos = RT_CONN_FLAGS_TOS(asoc->base.sk, tos);
439                 fl4->flowi4_oif = asoc->base.sk->sk_bound_dev_if;
440                 fl4->fl4_sport = htons(asoc->base.bind_addr.port);
441         }
442         if (saddr) {
443                 fl4->saddr = saddr->v4.sin_addr.s_addr;
444                 if (!fl4->fl4_sport)
445                         fl4->fl4_sport = saddr->v4.sin_port;
446         }
447
448         pr_debug("%s: dst:%pI4, src:%pI4 - ", __func__, &fl4->daddr,
449                  &fl4->saddr);
450
451         rt = ip_route_output_key(sock_net(sk), fl4);
452         if (!IS_ERR(rt)) {
453                 dst = &rt->dst;
454                 t->dst = dst;
455                 memcpy(fl, &_fl, sizeof(_fl));
456         }
457
458         /* If there is no association or if a source address is passed, no
459          * more validation is required.
460          */
461         if (!asoc || saddr)
462                 goto out;
463
464         bp = &asoc->base.bind_addr;
465
466         if (dst) {
467                 /* Walk through the bind address list and look for a bind
468                  * address that matches the source address of the returned dst.
469                  */
470                 sctp_v4_dst_saddr(&dst_saddr, fl4, htons(bp->port));
471                 rcu_read_lock();
472                 list_for_each_entry_rcu(laddr, &bp->address_list, list) {
473                         if (!laddr->valid || (laddr->state == SCTP_ADDR_DEL) ||
474                             (laddr->state != SCTP_ADDR_SRC &&
475                             !asoc->src_out_of_asoc_ok))
476                                 continue;
477                         if (sctp_v4_cmp_addr(&dst_saddr, &laddr->a))
478                                 goto out_unlock;
479                 }
480                 rcu_read_unlock();
481
482                 /* None of the bound addresses match the source address of the
483                  * dst. So release it.
484                  */
485                 dst_release(dst);
486                 dst = NULL;
487         }
488
489         /* Walk through the bind address list and try to get a dst that
490          * matches a bind address as the source address.
491          */
492         rcu_read_lock();
493         list_for_each_entry_rcu(laddr, &bp->address_list, list) {
494                 struct net_device *odev;
495
496                 if (!laddr->valid)
497                         continue;
498                 if (laddr->state != SCTP_ADDR_SRC ||
499                     AF_INET != laddr->a.sa.sa_family)
500                         continue;
501
502                 fl4->fl4_sport = laddr->a.v4.sin_port;
503                 flowi4_update_output(fl4,
504                                      asoc->base.sk->sk_bound_dev_if,
505                                      RT_CONN_FLAGS_TOS(asoc->base.sk, tos),
506                                      daddr->v4.sin_addr.s_addr,
507                                      laddr->a.v4.sin_addr.s_addr);
508
509                 rt = ip_route_output_key(sock_net(sk), fl4);
510                 if (IS_ERR(rt))
511                         continue;
512
513                 /* Ensure the src address belongs to the output
514                  * interface.
515                  */
516                 odev = __ip_dev_find(sock_net(sk), laddr->a.v4.sin_addr.s_addr,
517                                      false);
518                 if (!odev || odev->ifindex != fl4->flowi4_oif) {
519                         if (!dst) {
520                                 dst = &rt->dst;
521                                 t->dst = dst;
522                                 memcpy(fl, &_fl, sizeof(_fl));
523                         } else {
524                                 dst_release(&rt->dst);
525                         }
526                         continue;
527                 }
528
529                 dst_release(dst);
530                 dst = &rt->dst;
531                 t->dst = dst;
532                 memcpy(fl, &_fl, sizeof(_fl));
533                 break;
534         }
535
536 out_unlock:
537         rcu_read_unlock();
538 out:
539         if (dst) {
540                 pr_debug("rt_dst:%pI4, rt_src:%pI4\n",
541                          &fl->u.ip4.daddr, &fl->u.ip4.saddr);
542         } else {
543                 t->dst = NULL;
544                 pr_debug("no route\n");
545         }
546 }
547
548 /* For v4, the source address is cached in the route entry(dst). So no need
549  * to cache it separately and hence this is an empty routine.
550  */
551 static void sctp_v4_get_saddr(struct sctp_sock *sk,
552                               struct sctp_transport *t,
553                               struct flowi *fl)
554 {
555         union sctp_addr *saddr = &t->saddr;
556         struct rtable *rt = (struct rtable *)t->dst;
557
558         if (rt) {
559                 saddr->v4.sin_family = AF_INET;
560                 saddr->v4.sin_addr.s_addr = fl->u.ip4.saddr;
561         }
562 }
563
564 /* What interface did this skb arrive on? */
565 static int sctp_v4_skb_iif(const struct sk_buff *skb)
566 {
567         return inet_iif(skb);
568 }
569
570 static int sctp_v4_skb_sdif(const struct sk_buff *skb)
571 {
572         return inet_sdif(skb);
573 }
574
575 /* Was this packet marked by Explicit Congestion Notification? */
576 static int sctp_v4_is_ce(const struct sk_buff *skb)
577 {
578         return INET_ECN_is_ce(ip_hdr(skb)->tos);
579 }
580
581 /* Create and initialize a new sk for the socket returned by accept(). */
582 static struct sock *sctp_v4_create_accept_sk(struct sock *sk,
583                                              struct sctp_association *asoc,
584                                              bool kern)
585 {
586         struct sock *newsk = sk_alloc(sock_net(sk), PF_INET, GFP_KERNEL,
587                         sk->sk_prot, kern);
588         struct inet_sock *newinet;
589
590         if (!newsk)
591                 goto out;
592
593         sock_init_data(NULL, newsk);
594
595         sctp_copy_sock(newsk, sk, asoc);
596         sock_reset_flag(newsk, SOCK_ZAPPED);
597
598         sctp_v4_copy_ip_options(sk, newsk);
599
600         newinet = inet_sk(newsk);
601
602         newinet->inet_daddr = asoc->peer.primary_addr.v4.sin_addr.s_addr;
603
604         if (newsk->sk_prot->init(newsk)) {
605                 sk_common_release(newsk);
606                 newsk = NULL;
607         }
608
609 out:
610         return newsk;
611 }
612
613 static int sctp_v4_addr_to_user(struct sctp_sock *sp, union sctp_addr *addr)
614 {
615         /* No address mapping for V4 sockets */
616         memset(addr->v4.sin_zero, 0, sizeof(addr->v4.sin_zero));
617         return sizeof(struct sockaddr_in);
618 }
619
620 /* Dump the v4 addr to the seq file. */
621 static void sctp_v4_seq_dump_addr(struct seq_file *seq, union sctp_addr *addr)
622 {
623         seq_printf(seq, "%pI4 ", &addr->v4.sin_addr);
624 }
625
626 static void sctp_v4_ecn_capable(struct sock *sk)
627 {
628         INET_ECN_xmit(sk);
629 }
630
631 static void sctp_addr_wq_timeout_handler(struct timer_list *t)
632 {
633         struct net *net = from_timer(net, t, sctp.addr_wq_timer);
634         struct sctp_sockaddr_entry *addrw, *temp;
635         struct sctp_sock *sp;
636
637         spin_lock_bh(&net->sctp.addr_wq_lock);
638
639         list_for_each_entry_safe(addrw, temp, &net->sctp.addr_waitq, list) {
640                 pr_debug("%s: the first ent in wq:%p is addr:%pISc for cmd:%d at "
641                          "entry:%p\n", __func__, &net->sctp.addr_waitq, &addrw->a.sa,
642                          addrw->state, addrw);
643
644 #if IS_ENABLED(CONFIG_IPV6)
645                 /* Now we send an ASCONF for each association */
646                 /* Note. we currently don't handle link local IPv6 addressees */
647                 if (addrw->a.sa.sa_family == AF_INET6) {
648                         struct in6_addr *in6;
649
650                         if (ipv6_addr_type(&addrw->a.v6.sin6_addr) &
651                             IPV6_ADDR_LINKLOCAL)
652                                 goto free_next;
653
654                         in6 = (struct in6_addr *)&addrw->a.v6.sin6_addr;
655                         if (ipv6_chk_addr(net, in6, NULL, 0) == 0 &&
656                             addrw->state == SCTP_ADDR_NEW) {
657                                 unsigned long timeo_val;
658
659                                 pr_debug("%s: this is on DAD, trying %d sec "
660                                          "later\n", __func__,
661                                          SCTP_ADDRESS_TICK_DELAY);
662
663                                 timeo_val = jiffies;
664                                 timeo_val += msecs_to_jiffies(SCTP_ADDRESS_TICK_DELAY);
665                                 mod_timer(&net->sctp.addr_wq_timer, timeo_val);
666                                 break;
667                         }
668                 }
669 #endif
670                 list_for_each_entry(sp, &net->sctp.auto_asconf_splist, auto_asconf_list) {
671                         struct sock *sk;
672
673                         sk = sctp_opt2sk(sp);
674                         /* ignore bound-specific endpoints */
675                         if (!sctp_is_ep_boundall(sk))
676                                 continue;
677                         bh_lock_sock(sk);
678                         if (sctp_asconf_mgmt(sp, addrw) < 0)
679                                 pr_debug("%s: sctp_asconf_mgmt failed\n", __func__);
680                         bh_unlock_sock(sk);
681                 }
682 #if IS_ENABLED(CONFIG_IPV6)
683 free_next:
684 #endif
685                 list_del(&addrw->list);
686                 kfree(addrw);
687         }
688         spin_unlock_bh(&net->sctp.addr_wq_lock);
689 }
690
691 static void sctp_free_addr_wq(struct net *net)
692 {
693         struct sctp_sockaddr_entry *addrw;
694         struct sctp_sockaddr_entry *temp;
695
696         spin_lock_bh(&net->sctp.addr_wq_lock);
697         del_timer(&net->sctp.addr_wq_timer);
698         list_for_each_entry_safe(addrw, temp, &net->sctp.addr_waitq, list) {
699                 list_del(&addrw->list);
700                 kfree(addrw);
701         }
702         spin_unlock_bh(&net->sctp.addr_wq_lock);
703 }
704
705 /* lookup the entry for the same address in the addr_waitq
706  * sctp_addr_wq MUST be locked
707  */
708 static struct sctp_sockaddr_entry *sctp_addr_wq_lookup(struct net *net,
709                                         struct sctp_sockaddr_entry *addr)
710 {
711         struct sctp_sockaddr_entry *addrw;
712
713         list_for_each_entry(addrw, &net->sctp.addr_waitq, list) {
714                 if (addrw->a.sa.sa_family != addr->a.sa.sa_family)
715                         continue;
716                 if (addrw->a.sa.sa_family == AF_INET) {
717                         if (addrw->a.v4.sin_addr.s_addr ==
718                             addr->a.v4.sin_addr.s_addr)
719                                 return addrw;
720                 } else if (addrw->a.sa.sa_family == AF_INET6) {
721                         if (ipv6_addr_equal(&addrw->a.v6.sin6_addr,
722                             &addr->a.v6.sin6_addr))
723                                 return addrw;
724                 }
725         }
726         return NULL;
727 }
728
729 void sctp_addr_wq_mgmt(struct net *net, struct sctp_sockaddr_entry *addr, int cmd)
730 {
731         struct sctp_sockaddr_entry *addrw;
732         unsigned long timeo_val;
733
734         /* first, we check if an opposite message already exist in the queue.
735          * If we found such message, it is removed.
736          * This operation is a bit stupid, but the DHCP client attaches the
737          * new address after a couple of addition and deletion of that address
738          */
739
740         spin_lock_bh(&net->sctp.addr_wq_lock);
741         /* Offsets existing events in addr_wq */
742         addrw = sctp_addr_wq_lookup(net, addr);
743         if (addrw) {
744                 if (addrw->state != cmd) {
745                         pr_debug("%s: offsets existing entry for %d, addr:%pISc "
746                                  "in wq:%p\n", __func__, addrw->state, &addrw->a.sa,
747                                  &net->sctp.addr_waitq);
748
749                         list_del(&addrw->list);
750                         kfree(addrw);
751                 }
752                 spin_unlock_bh(&net->sctp.addr_wq_lock);
753                 return;
754         }
755
756         /* OK, we have to add the new address to the wait queue */
757         addrw = kmemdup(addr, sizeof(struct sctp_sockaddr_entry), GFP_ATOMIC);
758         if (addrw == NULL) {
759                 spin_unlock_bh(&net->sctp.addr_wq_lock);
760                 return;
761         }
762         addrw->state = cmd;
763         list_add_tail(&addrw->list, &net->sctp.addr_waitq);
764
765         pr_debug("%s: add new entry for cmd:%d, addr:%pISc in wq:%p\n",
766                  __func__, addrw->state, &addrw->a.sa, &net->sctp.addr_waitq);
767
768         if (!timer_pending(&net->sctp.addr_wq_timer)) {
769                 timeo_val = jiffies;
770                 timeo_val += msecs_to_jiffies(SCTP_ADDRESS_TICK_DELAY);
771                 mod_timer(&net->sctp.addr_wq_timer, timeo_val);
772         }
773         spin_unlock_bh(&net->sctp.addr_wq_lock);
774 }
775
776 /* Event handler for inet address addition/deletion events.
777  * The sctp_local_addr_list needs to be protocted by a spin lock since
778  * multiple notifiers (say IPv4 and IPv6) may be running at the same
779  * time and thus corrupt the list.
780  * The reader side is protected with RCU.
781  */
782 static int sctp_inetaddr_event(struct notifier_block *this, unsigned long ev,
783                                void *ptr)
784 {
785         struct in_ifaddr *ifa = (struct in_ifaddr *)ptr;
786         struct sctp_sockaddr_entry *addr = NULL;
787         struct sctp_sockaddr_entry *temp;
788         struct net *net = dev_net(ifa->ifa_dev->dev);
789         int found = 0;
790
791         switch (ev) {
792         case NETDEV_UP:
793                 addr = kzalloc(sizeof(*addr), GFP_ATOMIC);
794                 if (addr) {
795                         addr->a.v4.sin_family = AF_INET;
796                         addr->a.v4.sin_addr.s_addr = ifa->ifa_local;
797                         addr->valid = 1;
798                         spin_lock_bh(&net->sctp.local_addr_lock);
799                         list_add_tail_rcu(&addr->list, &net->sctp.local_addr_list);
800                         sctp_addr_wq_mgmt(net, addr, SCTP_ADDR_NEW);
801                         spin_unlock_bh(&net->sctp.local_addr_lock);
802                 }
803                 break;
804         case NETDEV_DOWN:
805                 spin_lock_bh(&net->sctp.local_addr_lock);
806                 list_for_each_entry_safe(addr, temp,
807                                         &net->sctp.local_addr_list, list) {
808                         if (addr->a.sa.sa_family == AF_INET &&
809                                         addr->a.v4.sin_addr.s_addr ==
810                                         ifa->ifa_local) {
811                                 sctp_addr_wq_mgmt(net, addr, SCTP_ADDR_DEL);
812                                 found = 1;
813                                 addr->valid = 0;
814                                 list_del_rcu(&addr->list);
815                                 break;
816                         }
817                 }
818                 spin_unlock_bh(&net->sctp.local_addr_lock);
819                 if (found)
820                         kfree_rcu(addr, rcu);
821                 break;
822         }
823
824         return NOTIFY_DONE;
825 }
826
827 /*
828  * Initialize the control inode/socket with a control endpoint data
829  * structure.  This endpoint is reserved exclusively for the OOTB processing.
830  */
831 static int sctp_ctl_sock_init(struct net *net)
832 {
833         int err;
834         sa_family_t family = PF_INET;
835
836         if (sctp_get_pf_specific(PF_INET6))
837                 family = PF_INET6;
838
839         err = inet_ctl_sock_create(&net->sctp.ctl_sock, family,
840                                    SOCK_SEQPACKET, IPPROTO_SCTP, net);
841
842         /* If IPv6 socket could not be created, try the IPv4 socket */
843         if (err < 0 && family == PF_INET6)
844                 err = inet_ctl_sock_create(&net->sctp.ctl_sock, AF_INET,
845                                            SOCK_SEQPACKET, IPPROTO_SCTP,
846                                            net);
847
848         if (err < 0) {
849                 pr_err("Failed to create the SCTP control socket\n");
850                 return err;
851         }
852         return 0;
853 }
854
855 static int sctp_udp_rcv(struct sock *sk, struct sk_buff *skb)
856 {
857         SCTP_INPUT_CB(skb)->encap_port = udp_hdr(skb)->source;
858
859         skb_set_transport_header(skb, sizeof(struct udphdr));
860         sctp_rcv(skb);
861         return 0;
862 }
863
864 int sctp_udp_sock_start(struct net *net)
865 {
866         struct udp_tunnel_sock_cfg tuncfg = {NULL};
867         struct udp_port_cfg udp_conf = {0};
868         struct socket *sock;
869         int err;
870
871         udp_conf.family = AF_INET;
872         udp_conf.local_ip.s_addr = htonl(INADDR_ANY);
873         udp_conf.local_udp_port = htons(net->sctp.udp_port);
874         err = udp_sock_create(net, &udp_conf, &sock);
875         if (err) {
876                 pr_err("Failed to create the SCTP UDP tunneling v4 sock\n");
877                 return err;
878         }
879
880         tuncfg.encap_type = 1;
881         tuncfg.encap_rcv = sctp_udp_rcv;
882         tuncfg.encap_err_lookup = sctp_udp_v4_err;
883         setup_udp_tunnel_sock(net, sock, &tuncfg);
884         net->sctp.udp4_sock = sock->sk;
885
886 #if IS_ENABLED(CONFIG_IPV6)
887         memset(&udp_conf, 0, sizeof(udp_conf));
888
889         udp_conf.family = AF_INET6;
890         udp_conf.local_ip6 = in6addr_any;
891         udp_conf.local_udp_port = htons(net->sctp.udp_port);
892         udp_conf.use_udp6_rx_checksums = true;
893         udp_conf.ipv6_v6only = true;
894         err = udp_sock_create(net, &udp_conf, &sock);
895         if (err) {
896                 pr_err("Failed to create the SCTP UDP tunneling v6 sock\n");
897                 udp_tunnel_sock_release(net->sctp.udp4_sock->sk_socket);
898                 net->sctp.udp4_sock = NULL;
899                 return err;
900         }
901
902         tuncfg.encap_type = 1;
903         tuncfg.encap_rcv = sctp_udp_rcv;
904         tuncfg.encap_err_lookup = sctp_udp_v6_err;
905         setup_udp_tunnel_sock(net, sock, &tuncfg);
906         net->sctp.udp6_sock = sock->sk;
907 #endif
908
909         return 0;
910 }
911
912 void sctp_udp_sock_stop(struct net *net)
913 {
914         if (net->sctp.udp4_sock) {
915                 udp_tunnel_sock_release(net->sctp.udp4_sock->sk_socket);
916                 net->sctp.udp4_sock = NULL;
917         }
918         if (net->sctp.udp6_sock) {
919                 udp_tunnel_sock_release(net->sctp.udp6_sock->sk_socket);
920                 net->sctp.udp6_sock = NULL;
921         }
922 }
923
924 /* Register address family specific functions. */
925 int sctp_register_af(struct sctp_af *af)
926 {
927         switch (af->sa_family) {
928         case AF_INET:
929                 if (sctp_af_v4_specific)
930                         return 0;
931                 sctp_af_v4_specific = af;
932                 break;
933         case AF_INET6:
934                 if (sctp_af_v6_specific)
935                         return 0;
936                 sctp_af_v6_specific = af;
937                 break;
938         default:
939                 return 0;
940         }
941
942         INIT_LIST_HEAD(&af->list);
943         list_add_tail(&af->list, &sctp_address_families);
944         return 1;
945 }
946
947 /* Get the table of functions for manipulating a particular address
948  * family.
949  */
950 struct sctp_af *sctp_get_af_specific(sa_family_t family)
951 {
952         switch (family) {
953         case AF_INET:
954                 return sctp_af_v4_specific;
955         case AF_INET6:
956                 return sctp_af_v6_specific;
957         default:
958                 return NULL;
959         }
960 }
961
962 /* Common code to initialize a AF_INET msg_name. */
963 static void sctp_inet_msgname(char *msgname, int *addr_len)
964 {
965         struct sockaddr_in *sin;
966
967         sin = (struct sockaddr_in *)msgname;
968         *addr_len = sizeof(struct sockaddr_in);
969         sin->sin_family = AF_INET;
970         memset(sin->sin_zero, 0, sizeof(sin->sin_zero));
971 }
972
973 /* Copy the primary address of the peer primary address as the msg_name. */
974 static void sctp_inet_event_msgname(struct sctp_ulpevent *event, char *msgname,
975                                     int *addr_len)
976 {
977         struct sockaddr_in *sin, *sinfrom;
978
979         if (msgname) {
980                 struct sctp_association *asoc;
981
982                 asoc = event->asoc;
983                 sctp_inet_msgname(msgname, addr_len);
984                 sin = (struct sockaddr_in *)msgname;
985                 sinfrom = &asoc->peer.primary_addr.v4;
986                 sin->sin_port = htons(asoc->peer.port);
987                 sin->sin_addr.s_addr = sinfrom->sin_addr.s_addr;
988         }
989 }
990
991 /* Initialize and copy out a msgname from an inbound skb. */
992 static void sctp_inet_skb_msgname(struct sk_buff *skb, char *msgname, int *len)
993 {
994         if (msgname) {
995                 struct sctphdr *sh = sctp_hdr(skb);
996                 struct sockaddr_in *sin = (struct sockaddr_in *)msgname;
997
998                 sctp_inet_msgname(msgname, len);
999                 sin->sin_port = sh->source;
1000                 sin->sin_addr.s_addr = ip_hdr(skb)->saddr;
1001         }
1002 }
1003
1004 /* Do we support this AF? */
1005 static int sctp_inet_af_supported(sa_family_t family, struct sctp_sock *sp)
1006 {
1007         /* PF_INET only supports AF_INET addresses. */
1008         return AF_INET == family;
1009 }
1010
1011 /* Address matching with wildcards allowed. */
1012 static int sctp_inet_cmp_addr(const union sctp_addr *addr1,
1013                               const union sctp_addr *addr2,
1014                               struct sctp_sock *opt)
1015 {
1016         /* PF_INET only supports AF_INET addresses. */
1017         if (addr1->sa.sa_family != addr2->sa.sa_family)
1018                 return 0;
1019         if (htonl(INADDR_ANY) == addr1->v4.sin_addr.s_addr ||
1020             htonl(INADDR_ANY) == addr2->v4.sin_addr.s_addr)
1021                 return 1;
1022         if (addr1->v4.sin_addr.s_addr == addr2->v4.sin_addr.s_addr)
1023                 return 1;
1024
1025         return 0;
1026 }
1027
1028 /* Verify that provided sockaddr looks bindable.  Common verification has
1029  * already been taken care of.
1030  */
1031 static int sctp_inet_bind_verify(struct sctp_sock *opt, union sctp_addr *addr)
1032 {
1033         return sctp_v4_available(addr, opt);
1034 }
1035
1036 /* Verify that sockaddr looks sendable.  Common verification has already
1037  * been taken care of.
1038  */
1039 static int sctp_inet_send_verify(struct sctp_sock *opt, union sctp_addr *addr)
1040 {
1041         return 1;
1042 }
1043
1044 /* Fill in Supported Address Type information for INIT and INIT-ACK
1045  * chunks.  Returns number of addresses supported.
1046  */
1047 static int sctp_inet_supported_addrs(const struct sctp_sock *opt,
1048                                      __be16 *types)
1049 {
1050         types[0] = SCTP_PARAM_IPV4_ADDRESS;
1051         return 1;
1052 }
1053
1054 /* Wrapper routine that calls the ip transmit routine. */
1055 static inline int sctp_v4_xmit(struct sk_buff *skb, struct sctp_transport *t)
1056 {
1057         struct dst_entry *dst = dst_clone(t->dst);
1058         struct flowi4 *fl4 = &t->fl.u.ip4;
1059         struct sock *sk = skb->sk;
1060         struct inet_sock *inet = inet_sk(sk);
1061         __u8 dscp = inet->tos;
1062         __be16 df = 0;
1063
1064         pr_debug("%s: skb:%p, len:%d, src:%pI4, dst:%pI4\n", __func__, skb,
1065                  skb->len, &fl4->saddr, &fl4->daddr);
1066
1067         if (t->dscp & SCTP_DSCP_SET_MASK)
1068                 dscp = t->dscp & SCTP_DSCP_VAL_MASK;
1069
1070         inet->pmtudisc = t->param_flags & SPP_PMTUD_ENABLE ? IP_PMTUDISC_DO
1071                                                            : IP_PMTUDISC_DONT;
1072         SCTP_INC_STATS(sock_net(sk), SCTP_MIB_OUTSCTPPACKS);
1073
1074         if (!t->encap_port || !sctp_sk(sk)->udp_port) {
1075                 skb_dst_set(skb, dst);
1076                 return __ip_queue_xmit(sk, skb, &t->fl, dscp);
1077         }
1078
1079         if (skb_is_gso(skb))
1080                 skb_shinfo(skb)->gso_type |= SKB_GSO_UDP_TUNNEL_CSUM;
1081
1082         if (ip_dont_fragment(sk, dst) && !skb->ignore_df)
1083                 df = htons(IP_DF);
1084
1085         skb->encapsulation = 1;
1086         skb_reset_inner_mac_header(skb);
1087         skb_reset_inner_transport_header(skb);
1088         skb_set_inner_ipproto(skb, IPPROTO_SCTP);
1089         udp_tunnel_xmit_skb((struct rtable *)dst, sk, skb, fl4->saddr,
1090                             fl4->daddr, dscp, ip4_dst_hoplimit(dst), df,
1091                             sctp_sk(sk)->udp_port, t->encap_port, false, false);
1092         return 0;
1093 }
1094
1095 static struct sctp_af sctp_af_inet;
1096
1097 static struct sctp_pf sctp_pf_inet = {
1098         .event_msgname = sctp_inet_event_msgname,
1099         .skb_msgname   = sctp_inet_skb_msgname,
1100         .af_supported  = sctp_inet_af_supported,
1101         .cmp_addr      = sctp_inet_cmp_addr,
1102         .bind_verify   = sctp_inet_bind_verify,
1103         .send_verify   = sctp_inet_send_verify,
1104         .supported_addrs = sctp_inet_supported_addrs,
1105         .create_accept_sk = sctp_v4_create_accept_sk,
1106         .addr_to_user  = sctp_v4_addr_to_user,
1107         .to_sk_saddr   = sctp_v4_to_sk_saddr,
1108         .to_sk_daddr   = sctp_v4_to_sk_daddr,
1109         .copy_ip_options = sctp_v4_copy_ip_options,
1110         .af            = &sctp_af_inet
1111 };
1112
1113 /* Notifier for inetaddr addition/deletion events.  */
1114 static struct notifier_block sctp_inetaddr_notifier = {
1115         .notifier_call = sctp_inetaddr_event,
1116 };
1117
1118 /* Socket operations.  */
1119 static const struct proto_ops inet_seqpacket_ops = {
1120         .family            = PF_INET,
1121         .owner             = THIS_MODULE,
1122         .release           = inet_release,      /* Needs to be wrapped... */
1123         .bind              = inet_bind,
1124         .connect           = sctp_inet_connect,
1125         .socketpair        = sock_no_socketpair,
1126         .accept            = inet_accept,
1127         .getname           = inet_getname,      /* Semantics are different.  */
1128         .poll              = sctp_poll,
1129         .ioctl             = inet_ioctl,
1130         .gettstamp         = sock_gettstamp,
1131         .listen            = sctp_inet_listen,
1132         .shutdown          = inet_shutdown,     /* Looks harmless.  */
1133         .setsockopt        = sock_common_setsockopt, /* IP_SOL IP_OPTION is a problem */
1134         .getsockopt        = sock_common_getsockopt,
1135         .sendmsg           = inet_sendmsg,
1136         .recvmsg           = inet_recvmsg,
1137         .mmap              = sock_no_mmap,
1138         .sendpage          = sock_no_sendpage,
1139 };
1140
1141 /* Registration with AF_INET family.  */
1142 static struct inet_protosw sctp_seqpacket_protosw = {
1143         .type       = SOCK_SEQPACKET,
1144         .protocol   = IPPROTO_SCTP,
1145         .prot       = &sctp_prot,
1146         .ops        = &inet_seqpacket_ops,
1147         .flags      = SCTP_PROTOSW_FLAG
1148 };
1149 static struct inet_protosw sctp_stream_protosw = {
1150         .type       = SOCK_STREAM,
1151         .protocol   = IPPROTO_SCTP,
1152         .prot       = &sctp_prot,
1153         .ops        = &inet_seqpacket_ops,
1154         .flags      = SCTP_PROTOSW_FLAG
1155 };
1156
1157 static int sctp4_rcv(struct sk_buff *skb)
1158 {
1159         SCTP_INPUT_CB(skb)->encap_port = 0;
1160         return sctp_rcv(skb);
1161 }
1162
1163 /* Register with IP layer.  */
1164 static const struct net_protocol sctp_protocol = {
1165         .handler     = sctp4_rcv,
1166         .err_handler = sctp_v4_err,
1167         .no_policy   = 1,
1168         .icmp_strict_tag_validation = 1,
1169 };
1170
1171 /* IPv4 address related functions.  */
1172 static struct sctp_af sctp_af_inet = {
1173         .sa_family         = AF_INET,
1174         .sctp_xmit         = sctp_v4_xmit,
1175         .setsockopt        = ip_setsockopt,
1176         .getsockopt        = ip_getsockopt,
1177         .get_dst           = sctp_v4_get_dst,
1178         .get_saddr         = sctp_v4_get_saddr,
1179         .copy_addrlist     = sctp_v4_copy_addrlist,
1180         .from_skb          = sctp_v4_from_skb,
1181         .from_sk           = sctp_v4_from_sk,
1182         .from_addr_param   = sctp_v4_from_addr_param,
1183         .to_addr_param     = sctp_v4_to_addr_param,
1184         .cmp_addr          = sctp_v4_cmp_addr,
1185         .addr_valid        = sctp_v4_addr_valid,
1186         .inaddr_any        = sctp_v4_inaddr_any,
1187         .is_any            = sctp_v4_is_any,
1188         .available         = sctp_v4_available,
1189         .scope             = sctp_v4_scope,
1190         .skb_iif           = sctp_v4_skb_iif,
1191         .skb_sdif          = sctp_v4_skb_sdif,
1192         .is_ce             = sctp_v4_is_ce,
1193         .seq_dump_addr     = sctp_v4_seq_dump_addr,
1194         .ecn_capable       = sctp_v4_ecn_capable,
1195         .net_header_len    = sizeof(struct iphdr),
1196         .sockaddr_len      = sizeof(struct sockaddr_in),
1197         .ip_options_len    = sctp_v4_ip_options_len,
1198 };
1199
1200 struct sctp_pf *sctp_get_pf_specific(sa_family_t family)
1201 {
1202         switch (family) {
1203         case PF_INET:
1204                 return sctp_pf_inet_specific;
1205         case PF_INET6:
1206                 return sctp_pf_inet6_specific;
1207         default:
1208                 return NULL;
1209         }
1210 }
1211
1212 /* Register the PF specific function table.  */
1213 int sctp_register_pf(struct sctp_pf *pf, sa_family_t family)
1214 {
1215         switch (family) {
1216         case PF_INET:
1217                 if (sctp_pf_inet_specific)
1218                         return 0;
1219                 sctp_pf_inet_specific = pf;
1220                 break;
1221         case PF_INET6:
1222                 if (sctp_pf_inet6_specific)
1223                         return 0;
1224                 sctp_pf_inet6_specific = pf;
1225                 break;
1226         default:
1227                 return 0;
1228         }
1229         return 1;
1230 }
1231
1232 static inline int init_sctp_mibs(struct net *net)
1233 {
1234         net->sctp.sctp_statistics = alloc_percpu(struct sctp_mib);
1235         if (!net->sctp.sctp_statistics)
1236                 return -ENOMEM;
1237         return 0;
1238 }
1239
1240 static inline void cleanup_sctp_mibs(struct net *net)
1241 {
1242         free_percpu(net->sctp.sctp_statistics);
1243 }
1244
1245 static void sctp_v4_pf_init(void)
1246 {
1247         /* Initialize the SCTP specific PF functions. */
1248         sctp_register_pf(&sctp_pf_inet, PF_INET);
1249         sctp_register_af(&sctp_af_inet);
1250 }
1251
1252 static void sctp_v4_pf_exit(void)
1253 {
1254         list_del(&sctp_af_inet.list);
1255 }
1256
1257 static int sctp_v4_protosw_init(void)
1258 {
1259         int rc;
1260
1261         rc = proto_register(&sctp_prot, 1);
1262         if (rc)
1263                 return rc;
1264
1265         /* Register SCTP(UDP and TCP style) with socket layer.  */
1266         inet_register_protosw(&sctp_seqpacket_protosw);
1267         inet_register_protosw(&sctp_stream_protosw);
1268
1269         return 0;
1270 }
1271
1272 static void sctp_v4_protosw_exit(void)
1273 {
1274         inet_unregister_protosw(&sctp_stream_protosw);
1275         inet_unregister_protosw(&sctp_seqpacket_protosw);
1276         proto_unregister(&sctp_prot);
1277 }
1278
1279 static int sctp_v4_add_protocol(void)
1280 {
1281         /* Register notifier for inet address additions/deletions. */
1282         register_inetaddr_notifier(&sctp_inetaddr_notifier);
1283
1284         /* Register SCTP with inet layer.  */
1285         if (inet_add_protocol(&sctp_protocol, IPPROTO_SCTP) < 0)
1286                 return -EAGAIN;
1287
1288         return 0;
1289 }
1290
1291 static void sctp_v4_del_protocol(void)
1292 {
1293         inet_del_protocol(&sctp_protocol, IPPROTO_SCTP);
1294         unregister_inetaddr_notifier(&sctp_inetaddr_notifier);
1295 }
1296
1297 static int __net_init sctp_defaults_init(struct net *net)
1298 {
1299         int status;
1300
1301         /*
1302          * 14. Suggested SCTP Protocol Parameter Values
1303          */
1304         /* The following protocol parameters are RECOMMENDED:  */
1305         /* RTO.Initial              - 3  seconds */
1306         net->sctp.rto_initial                   = SCTP_RTO_INITIAL;
1307         /* RTO.Min                  - 1  second */
1308         net->sctp.rto_min                       = SCTP_RTO_MIN;
1309         /* RTO.Max                 -  60 seconds */
1310         net->sctp.rto_max                       = SCTP_RTO_MAX;
1311         /* RTO.Alpha                - 1/8 */
1312         net->sctp.rto_alpha                     = SCTP_RTO_ALPHA;
1313         /* RTO.Beta                 - 1/4 */
1314         net->sctp.rto_beta                      = SCTP_RTO_BETA;
1315
1316         /* Valid.Cookie.Life        - 60  seconds */
1317         net->sctp.valid_cookie_life             = SCTP_DEFAULT_COOKIE_LIFE;
1318
1319         /* Whether Cookie Preservative is enabled(1) or not(0) */
1320         net->sctp.cookie_preserve_enable        = 1;
1321
1322         /* Default sctp sockets to use md5 as their hmac alg */
1323 #if defined (CONFIG_SCTP_DEFAULT_COOKIE_HMAC_MD5)
1324         net->sctp.sctp_hmac_alg                 = "md5";
1325 #elif defined (CONFIG_SCTP_DEFAULT_COOKIE_HMAC_SHA1)
1326         net->sctp.sctp_hmac_alg                 = "sha1";
1327 #else
1328         net->sctp.sctp_hmac_alg                 = NULL;
1329 #endif
1330
1331         /* Max.Burst                - 4 */
1332         net->sctp.max_burst                     = SCTP_DEFAULT_MAX_BURST;
1333
1334         /* Disable of Primary Path Switchover by default */
1335         net->sctp.ps_retrans = SCTP_PS_RETRANS_MAX;
1336
1337         /* Enable pf state by default */
1338         net->sctp.pf_enable = 1;
1339
1340         /* Ignore pf exposure feature by default */
1341         net->sctp.pf_expose = SCTP_PF_EXPOSE_UNSET;
1342
1343         /* Association.Max.Retrans  - 10 attempts
1344          * Path.Max.Retrans         - 5  attempts (per destination address)
1345          * Max.Init.Retransmits     - 8  attempts
1346          */
1347         net->sctp.max_retrans_association       = 10;
1348         net->sctp.max_retrans_path              = 5;
1349         net->sctp.max_retrans_init              = 8;
1350
1351         /* Sendbuffer growth        - do per-socket accounting */
1352         net->sctp.sndbuf_policy                 = 0;
1353
1354         /* Rcvbuffer growth         - do per-socket accounting */
1355         net->sctp.rcvbuf_policy                 = 0;
1356
1357         /* HB.interval              - 30 seconds */
1358         net->sctp.hb_interval                   = SCTP_DEFAULT_TIMEOUT_HEARTBEAT;
1359
1360         /* delayed SACK timeout */
1361         net->sctp.sack_timeout                  = SCTP_DEFAULT_TIMEOUT_SACK;
1362
1363         /* Disable ADDIP by default. */
1364         net->sctp.addip_enable = 0;
1365         net->sctp.addip_noauth = 0;
1366         net->sctp.default_auto_asconf = 0;
1367
1368         /* Enable PR-SCTP by default. */
1369         net->sctp.prsctp_enable = 1;
1370
1371         /* Disable RECONF by default. */
1372         net->sctp.reconf_enable = 0;
1373
1374         /* Disable AUTH by default. */
1375         net->sctp.auth_enable = 0;
1376
1377         /* Enable ECN by default. */
1378         net->sctp.ecn_enable = 1;
1379
1380         /* Set UDP tunneling listening port to 0 by default */
1381         net->sctp.udp_port = 0;
1382
1383         /* Set remote encap port to 0 by default */
1384         net->sctp.encap_port = 0;
1385
1386         /* Set SCOPE policy to enabled */
1387         net->sctp.scope_policy = SCTP_SCOPE_POLICY_ENABLE;
1388
1389         /* Set the default rwnd update threshold */
1390         net->sctp.rwnd_upd_shift = SCTP_DEFAULT_RWND_SHIFT;
1391
1392         /* Initialize maximum autoclose timeout. */
1393         net->sctp.max_autoclose         = INT_MAX / HZ;
1394
1395 #ifdef CONFIG_NET_L3_MASTER_DEV
1396         net->sctp.l3mdev_accept = 1;
1397 #endif
1398
1399         status = sctp_sysctl_net_register(net);
1400         if (status)
1401                 goto err_sysctl_register;
1402
1403         /* Allocate and initialise sctp mibs.  */
1404         status = init_sctp_mibs(net);
1405         if (status)
1406                 goto err_init_mibs;
1407
1408 #ifdef CONFIG_PROC_FS
1409         /* Initialize proc fs directory.  */
1410         status = sctp_proc_init(net);
1411         if (status)
1412                 goto err_init_proc;
1413 #endif
1414
1415         sctp_dbg_objcnt_init(net);
1416
1417         /* Initialize the local address list. */
1418         INIT_LIST_HEAD(&net->sctp.local_addr_list);
1419         spin_lock_init(&net->sctp.local_addr_lock);
1420         sctp_get_local_addr_list(net);
1421
1422         /* Initialize the address event list */
1423         INIT_LIST_HEAD(&net->sctp.addr_waitq);
1424         INIT_LIST_HEAD(&net->sctp.auto_asconf_splist);
1425         spin_lock_init(&net->sctp.addr_wq_lock);
1426         net->sctp.addr_wq_timer.expires = 0;
1427         timer_setup(&net->sctp.addr_wq_timer, sctp_addr_wq_timeout_handler, 0);
1428
1429         return 0;
1430
1431 #ifdef CONFIG_PROC_FS
1432 err_init_proc:
1433         cleanup_sctp_mibs(net);
1434 #endif
1435 err_init_mibs:
1436         sctp_sysctl_net_unregister(net);
1437 err_sysctl_register:
1438         return status;
1439 }
1440
1441 static void __net_exit sctp_defaults_exit(struct net *net)
1442 {
1443         /* Free the local address list */
1444         sctp_free_addr_wq(net);
1445         sctp_free_local_addr_list(net);
1446
1447 #ifdef CONFIG_PROC_FS
1448         remove_proc_subtree("sctp", net->proc_net);
1449         net->sctp.proc_net_sctp = NULL;
1450 #endif
1451         cleanup_sctp_mibs(net);
1452         sctp_sysctl_net_unregister(net);
1453 }
1454
1455 static struct pernet_operations sctp_defaults_ops = {
1456         .init = sctp_defaults_init,
1457         .exit = sctp_defaults_exit,
1458 };
1459
1460 static int __net_init sctp_ctrlsock_init(struct net *net)
1461 {
1462         int status;
1463
1464         /* Initialize the control inode/socket for handling OOTB packets.  */
1465         status = sctp_ctl_sock_init(net);
1466         if (status)
1467                 pr_err("Failed to initialize the SCTP control sock\n");
1468
1469         return status;
1470 }
1471
1472 static void __net_exit sctp_ctrlsock_exit(struct net *net)
1473 {
1474         /* Free the control endpoint.  */
1475         inet_ctl_sock_destroy(net->sctp.ctl_sock);
1476 }
1477
1478 static struct pernet_operations sctp_ctrlsock_ops = {
1479         .init = sctp_ctrlsock_init,
1480         .exit = sctp_ctrlsock_exit,
1481 };
1482
1483 /* Initialize the universe into something sensible.  */
1484 static __init int sctp_init(void)
1485 {
1486         unsigned long nr_pages = totalram_pages();
1487         unsigned long limit;
1488         unsigned long goal;
1489         int max_entry_order;
1490         int num_entries;
1491         int max_share;
1492         int status;
1493         int order;
1494         int i;
1495
1496         sock_skb_cb_check_size(sizeof(struct sctp_ulpevent));
1497
1498         /* Allocate bind_bucket and chunk caches. */
1499         status = -ENOBUFS;
1500         sctp_bucket_cachep = kmem_cache_create("sctp_bind_bucket",
1501                                                sizeof(struct sctp_bind_bucket),
1502                                                0, SLAB_HWCACHE_ALIGN,
1503                                                NULL);
1504         if (!sctp_bucket_cachep)
1505                 goto out;
1506
1507         sctp_chunk_cachep = kmem_cache_create("sctp_chunk",
1508                                                sizeof(struct sctp_chunk),
1509                                                0, SLAB_HWCACHE_ALIGN,
1510                                                NULL);
1511         if (!sctp_chunk_cachep)
1512                 goto err_chunk_cachep;
1513
1514         status = percpu_counter_init(&sctp_sockets_allocated, 0, GFP_KERNEL);
1515         if (status)
1516                 goto err_percpu_counter_init;
1517
1518         /* Implementation specific variables. */
1519
1520         /* Initialize default stream count setup information. */
1521         sctp_max_instreams              = SCTP_DEFAULT_INSTREAMS;
1522         sctp_max_outstreams             = SCTP_DEFAULT_OUTSTREAMS;
1523
1524         /* Initialize handle used for association ids. */
1525         idr_init(&sctp_assocs_id);
1526
1527         limit = nr_free_buffer_pages() / 8;
1528         limit = max(limit, 128UL);
1529         sysctl_sctp_mem[0] = limit / 4 * 3;
1530         sysctl_sctp_mem[1] = limit;
1531         sysctl_sctp_mem[2] = sysctl_sctp_mem[0] * 2;
1532
1533         /* Set per-socket limits to no more than 1/128 the pressure threshold*/
1534         limit = (sysctl_sctp_mem[1]) << (PAGE_SHIFT - 7);
1535         max_share = min(4UL*1024*1024, limit);
1536
1537         sysctl_sctp_rmem[0] = PAGE_SIZE; /* give each asoc 1 page min */
1538         sysctl_sctp_rmem[1] = 1500 * SKB_TRUESIZE(1);
1539         sysctl_sctp_rmem[2] = max(sysctl_sctp_rmem[1], max_share);
1540
1541         sysctl_sctp_wmem[0] = PAGE_SIZE;
1542         sysctl_sctp_wmem[1] = 16*1024;
1543         sysctl_sctp_wmem[2] = max(64*1024, max_share);
1544
1545         /* Size and allocate the association hash table.
1546          * The methodology is similar to that of the tcp hash tables.
1547          * Though not identical.  Start by getting a goal size
1548          */
1549         if (nr_pages >= (128 * 1024))
1550                 goal = nr_pages >> (22 - PAGE_SHIFT);
1551         else
1552                 goal = nr_pages >> (24 - PAGE_SHIFT);
1553
1554         /* Then compute the page order for said goal */
1555         order = get_order(goal);
1556
1557         /* Now compute the required page order for the maximum sized table we
1558          * want to create
1559          */
1560         max_entry_order = get_order(MAX_SCTP_PORT_HASH_ENTRIES *
1561                                     sizeof(struct sctp_bind_hashbucket));
1562
1563         /* Limit the page order by that maximum hash table size */
1564         order = min(order, max_entry_order);
1565
1566         /* Allocate and initialize the endpoint hash table.  */
1567         sctp_ep_hashsize = 64;
1568         sctp_ep_hashtable =
1569                 kmalloc_array(64, sizeof(struct sctp_hashbucket), GFP_KERNEL);
1570         if (!sctp_ep_hashtable) {
1571                 pr_err("Failed endpoint_hash alloc\n");
1572                 status = -ENOMEM;
1573                 goto err_ehash_alloc;
1574         }
1575         for (i = 0; i < sctp_ep_hashsize; i++) {
1576                 rwlock_init(&sctp_ep_hashtable[i].lock);
1577                 INIT_HLIST_HEAD(&sctp_ep_hashtable[i].chain);
1578         }
1579
1580         /* Allocate and initialize the SCTP port hash table.
1581          * Note that order is initalized to start at the max sized
1582          * table we want to support.  If we can't get that many pages
1583          * reduce the order and try again
1584          */
1585         do {
1586                 sctp_port_hashtable = (struct sctp_bind_hashbucket *)
1587                         __get_free_pages(GFP_KERNEL | __GFP_NOWARN, order);
1588         } while (!sctp_port_hashtable && --order > 0);
1589
1590         if (!sctp_port_hashtable) {
1591                 pr_err("Failed bind hash alloc\n");
1592                 status = -ENOMEM;
1593                 goto err_bhash_alloc;
1594         }
1595
1596         /* Now compute the number of entries that will fit in the
1597          * port hash space we allocated
1598          */
1599         num_entries = (1UL << order) * PAGE_SIZE /
1600                       sizeof(struct sctp_bind_hashbucket);
1601
1602         /* And finish by rounding it down to the nearest power of two.
1603          * This wastes some memory of course, but it's needed because
1604          * the hash function operates based on the assumption that
1605          * the number of entries is a power of two.
1606          */
1607         sctp_port_hashsize = rounddown_pow_of_two(num_entries);
1608
1609         for (i = 0; i < sctp_port_hashsize; i++) {
1610                 spin_lock_init(&sctp_port_hashtable[i].lock);
1611                 INIT_HLIST_HEAD(&sctp_port_hashtable[i].chain);
1612         }
1613
1614         status = sctp_transport_hashtable_init();
1615         if (status)
1616                 goto err_thash_alloc;
1617
1618         pr_info("Hash tables configured (bind %d/%d)\n", sctp_port_hashsize,
1619                 num_entries);
1620
1621         sctp_sysctl_register();
1622
1623         INIT_LIST_HEAD(&sctp_address_families);
1624         sctp_v4_pf_init();
1625         sctp_v6_pf_init();
1626         sctp_sched_ops_init();
1627
1628         status = register_pernet_subsys(&sctp_defaults_ops);
1629         if (status)
1630                 goto err_register_defaults;
1631
1632         status = sctp_v4_protosw_init();
1633         if (status)
1634                 goto err_protosw_init;
1635
1636         status = sctp_v6_protosw_init();
1637         if (status)
1638                 goto err_v6_protosw_init;
1639
1640         status = register_pernet_subsys(&sctp_ctrlsock_ops);
1641         if (status)
1642                 goto err_register_ctrlsock;
1643
1644         status = sctp_v4_add_protocol();
1645         if (status)
1646                 goto err_add_protocol;
1647
1648         /* Register SCTP with inet6 layer.  */
1649         status = sctp_v6_add_protocol();
1650         if (status)
1651                 goto err_v6_add_protocol;
1652
1653         if (sctp_offload_init() < 0)
1654                 pr_crit("%s: Cannot add SCTP protocol offload\n", __func__);
1655
1656 out:
1657         return status;
1658 err_v6_add_protocol:
1659         sctp_v4_del_protocol();
1660 err_add_protocol:
1661         unregister_pernet_subsys(&sctp_ctrlsock_ops);
1662 err_register_ctrlsock:
1663         sctp_v6_protosw_exit();
1664 err_v6_protosw_init:
1665         sctp_v4_protosw_exit();
1666 err_protosw_init:
1667         unregister_pernet_subsys(&sctp_defaults_ops);
1668 err_register_defaults:
1669         sctp_v4_pf_exit();
1670         sctp_v6_pf_exit();
1671         sctp_sysctl_unregister();
1672         free_pages((unsigned long)sctp_port_hashtable,
1673                    get_order(sctp_port_hashsize *
1674                              sizeof(struct sctp_bind_hashbucket)));
1675 err_bhash_alloc:
1676         sctp_transport_hashtable_destroy();
1677 err_thash_alloc:
1678         kfree(sctp_ep_hashtable);
1679 err_ehash_alloc:
1680         percpu_counter_destroy(&sctp_sockets_allocated);
1681 err_percpu_counter_init:
1682         kmem_cache_destroy(sctp_chunk_cachep);
1683 err_chunk_cachep:
1684         kmem_cache_destroy(sctp_bucket_cachep);
1685         goto out;
1686 }
1687
1688 /* Exit handler for the SCTP protocol.  */
1689 static __exit void sctp_exit(void)
1690 {
1691         /* BUG.  This should probably do something useful like clean
1692          * up all the remaining associations and all that memory.
1693          */
1694
1695         /* Unregister with inet6/inet layers. */
1696         sctp_v6_del_protocol();
1697         sctp_v4_del_protocol();
1698
1699         unregister_pernet_subsys(&sctp_ctrlsock_ops);
1700
1701         /* Free protosw registrations */
1702         sctp_v6_protosw_exit();
1703         sctp_v4_protosw_exit();
1704
1705         unregister_pernet_subsys(&sctp_defaults_ops);
1706
1707         /* Unregister with socket layer. */
1708         sctp_v6_pf_exit();
1709         sctp_v4_pf_exit();
1710
1711         sctp_sysctl_unregister();
1712
1713         free_pages((unsigned long)sctp_port_hashtable,
1714                    get_order(sctp_port_hashsize *
1715                              sizeof(struct sctp_bind_hashbucket)));
1716         kfree(sctp_ep_hashtable);
1717         sctp_transport_hashtable_destroy();
1718
1719         percpu_counter_destroy(&sctp_sockets_allocated);
1720
1721         rcu_barrier(); /* Wait for completion of call_rcu()'s */
1722
1723         kmem_cache_destroy(sctp_chunk_cachep);
1724         kmem_cache_destroy(sctp_bucket_cachep);
1725 }
1726
1727 module_init(sctp_init);
1728 module_exit(sctp_exit);
1729
1730 /*
1731  * __stringify doesn't likes enums, so use IPPROTO_SCTP value (132) directly.
1732  */
1733 MODULE_ALIAS("net-pf-" __stringify(PF_INET) "-proto-132");
1734 MODULE_ALIAS("net-pf-" __stringify(PF_INET6) "-proto-132");
1735 MODULE_AUTHOR("Linux Kernel SCTP developers <linux-sctp@vger.kernel.org>");
1736 MODULE_DESCRIPTION("Support for the SCTP protocol (RFC2960)");
1737 module_param_named(no_checksums, sctp_checksum_disable, bool, 0644);
1738 MODULE_PARM_DESC(no_checksums, "Disable checksums computing and verification");
1739 MODULE_LICENSE("GPL");